Jelajahi Sumber

php beautify

causefx 8 tahun lalu
induk
melakukan
53a9cfb034

+ 27 - 27
api/config/default.php

@@ -1,11 +1,11 @@
 <?php
 return array(
     'branch' => 'v2-develop',
-	'authType' => 'internal',
+    'authType' => 'internal',
     'authBackend' => '',
-	'authBackendHost' => '',
-	'authBaseDN' => '',
-	'authBackendDomain' => '',
+    'authBackendHost' => '',
+    'authBaseDN' => '',
+    'authBackendDomain' => '',
     'logo' => 'plugins/images/organizr/logo-wide.png',
     'loginWallpaper' => '',
     'title' => 'Organizr V2',
@@ -33,15 +33,15 @@ return array(
     'ssoPlex' => false,
     'ssoOmbi' => false,
     'ssoTautulli' => false,
-	'sonarrURL' => '',
-	'sonarrToken' => '',
+    'sonarrURL' => '',
+    'sonarrToken' => '',
     'radarrURL' => '',
-	'radarrToken' => '',
-	'couchpotatoURL' => '',
-	'couchpotatoToken' => '',
+    'radarrToken' => '',
+    'couchpotatoURL' => '',
+    'couchpotatoToken' => '',
     'sickrageURL' => '',
-	'sickrageToken' => '',
-	'sabnzbdURL' => '',
+    'sickrageToken' => '',
+    'sabnzbdURL' => '',
     'sabnzbdToken' => '',
     'nzbgetURL' => '',
     'nzbgetUsername' => '',
@@ -70,7 +70,7 @@ return array(
     'homepageDelugeAuth' => '1',
     'homepageSabnzbdEnabled' => false,
     'homepageSabnzbdAuth' => '1',
-	'homepageSonarrEnabled' => false,
+    'homepageSonarrEnabled' => false,
     'homepageSonarrAuth' => '1',
     'homepageCouchpotatoEnabled' => false,
     'homepageCouchpotatoAuth' => '1',
@@ -97,15 +97,15 @@ return array(
     'homepageOrdertransmission' => '3',
     'homepageOrderqBittorrent' => '4',
     'homepageOrderdeluge' => '5',
-	'homepageOrdernzbget' => '6',
-	'homepageOrdersabnzbd' => '7',
-	'homepageOrderplexnowplaying' => '8',
-	'homepageOrderplexrecent' => '9',
-	'homepageOrderplexplaylist' => '10',
-	'homepageOrderembynowplaying' => '11',
-	'homepageOrderembyrecent' => '12',
-	'homepageOrderombi' => '13',
-	'homepageOrdercalendar' => '14',
+    'homepageOrdernzbget' => '6',
+    'homepageOrdersabnzbd' => '7',
+    'homepageOrderplexnowplaying' => '8',
+    'homepageOrderplexrecent' => '9',
+    'homepageOrderplexplaylist' => '10',
+    'homepageOrderembynowplaying' => '11',
+    'homepageOrderembyrecent' => '12',
+    'homepageOrderombi' => '13',
+    'homepageOrdercalendar' => '14',
     'homepageShowStreamNames' => false,
     'homepageShowStreamNamesAuth' => '1',
     'homepageStreamRefresh' => '60000',
@@ -115,7 +115,7 @@ return array(
     'homepagePlexStreamsAuth' => '1',
     'homepagePlexRecent' => false,
     'homepagePlexRecentAuth' => '1',
-	'homepagePlexPlaylist' => false,
+    'homepagePlexPlaylist' => false,
     'homepagePlexPlaylistAuth' => '1',
     'homepageEmbyStreams' => false,
     'homepageEmbyStreamsAuth' => '1',
@@ -128,12 +128,12 @@ return array(
     'calendarRefresh' => '60000',
     'calendarTimeFormat' => 'h(:mm)t',
     'calendarLimit' => '1000',
-	'customCss' => '',
+    'customCss' => '',
     'customHTMLone' => '',
     'customHTMLtwo' => '',
-	'mediaSearch' => false,
-	'mediaSearchType' => '',
-	'mediaSearchAuth' => '1',
-	'registrationPassword' => ''
+    'mediaSearch' => false,
+    'mediaSearchType' => '',
+    'mediaSearchAuth' => '1',
+    'registrationPassword' => ''
 
 );

+ 4 - 4
api/functions.php

@@ -4,23 +4,23 @@ date_default_timezone_set("UTC");
 // Autoload frameworks
 require_once(__DIR__.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php');
 // Include all function files
-foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.'*.php') as $filename){
+foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.'*.php') as $filename) {
     require_once $filename;
 }
 // Add in default and custom settings
 configLazy();
 // Define Logs and files after db location is set
-if(isset($GLOBALS['dbLocation'])){
+if (isset($GLOBALS['dbLocation'])) {
     $GLOBALS['organizrLog'] = $GLOBALS['dbLocation'].'organizrLog.json';
     $GLOBALS['organizrLoginLog'] = $GLOBALS['dbLocation'].'organizrLoginLog.json';
 }
 // Validate Token if set and set guest if not - sets GLOBALS
 getOrganizrUserToken();
 // Include all pages files
-foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'pages' . DIRECTORY_SEPARATOR . "*.php") as $filename){
+foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'pages' . DIRECTORY_SEPARATOR . "*.php") as $filename) {
     require_once $filename;
 }
 // Include all plugin files
-foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . "*.php") as $filename){
+foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . "*.php") as $filename) {
     require_once $filename;
 }

+ 237 - 228
api/functions/auth-functions.php

@@ -1,242 +1,251 @@
 <?php
-function authRegister($username,$password,$defaults,$email){
-	$defaults = defaultUserGroup();
-	if(createUser($username,$password,$defaults,$email)){
-		writeLog('success', 'Registration Function - A User has registered', $username);
-		if($GLOBALS['PHPMAILER-enabled']){
-			$emailTemplate = array(
-				'type' => 'registration',
-				'body' => $GLOBALS['PHPMAILER-emailTemplateRegisterUser'],
-				'subject' => $GLOBALS['PHPMAILER-emailTemplateRegisterUserSubject'],
-				'user' => $username,
-				'password' => null,
-				'inviteCode' => null,
-			);
-			$emailTemplate = phpmEmailTemplate($emailTemplate);
-			$sendEmail = array(
-				'to' => $email,
-				'user' => $username,
-				'subject' => $emailTemplate['subject'],
-				'body' => phpmBuildEmail($emailTemplate),
-			);
-			phpmSendEmail($sendEmail);
-		}
-		if(createToken($username,$email,gravatar($email),$defaults['group'],$defaults['group_id'],$GLOBALS['organizrHash'],7)){
-			writeLoginLog($username, 'success');
-			writeLog('success', 'Login Function - A User has logged in', $username);
-			return true;
-		}
-	}else{
-		writeLog('error', 'Registration Function - An error occured', $username);
-		return 'username taken';
-	}
+function authRegister($username, $password, $defaults, $email)
+{
+    $defaults = defaultUserGroup();
+    if (createUser($username, $password, $defaults, $email)) {
+        writeLog('success', 'Registration Function - A User has registered', $username);
+        if ($GLOBALS['PHPMAILER-enabled']) {
+            $emailTemplate = array(
+                'type' => 'registration',
+                'body' => $GLOBALS['PHPMAILER-emailTemplateRegisterUser'],
+                'subject' => $GLOBALS['PHPMAILER-emailTemplateRegisterUserSubject'],
+                'user' => $username,
+                'password' => null,
+                'inviteCode' => null,
+            );
+            $emailTemplate = phpmEmailTemplate($emailTemplate);
+            $sendEmail = array(
+                'to' => $email,
+                'user' => $username,
+                'subject' => $emailTemplate['subject'],
+                'body' => phpmBuildEmail($emailTemplate),
+            );
+            phpmSendEmail($sendEmail);
+        }
+        if (createToken($username, $email, gravatar($email), $defaults['group'], $defaults['group_id'], $GLOBALS['organizrHash'], 7)) {
+            writeLoginLog($username, 'success');
+            writeLog('success', 'Login Function - A User has logged in', $username);
+            return true;
+        }
+    } else {
+        writeLog('error', 'Registration Function - An error occured', $username);
+        return 'username taken';
+    }
 }
-function checkPlexUser($username){
-	try{
-		if(!empty($GLOBALS['plexToken'])){
-			$url = 'https://plex.tv/pms/friends/all';
-			$headers = array(
-				'X-Plex-Token' => $GLOBALS['plexToken'],
-			);
-			$response = Requests::get($url, $headers);
-			if($response->success){
-				libxml_use_internal_errors(true);
-				$userXML = simplexml_load_string($response->body);
-				if (is_array($userXML) || is_object($userXML)) {
-					$usernameLower = strtolower($username);
-					foreach($userXML AS $child) {
-						if(isset($child['username']) && strtolower($child['username']) == $usernameLower || isset($child['email']) && strtolower($child['email']) == $usernameLower) {
-							return true;
-						}
-					}
-				}
-			}
-		}
-		return false;
-	}catch( Requests_Exception $e ) {
-		writeLog('success', 'Plex User Check Function - Error: '.$e->getMessage(), $username);
-	};
+function checkPlexUser($username)
+{
+    try {
+        if (!empty($GLOBALS['plexToken'])) {
+            $url = 'https://plex.tv/pms/friends/all';
+            $headers = array(
+                'X-Plex-Token' => $GLOBALS['plexToken'],
+            );
+            $response = Requests::get($url, $headers);
+            if ($response->success) {
+                libxml_use_internal_errors(true);
+                $userXML = simplexml_load_string($response->body);
+                if (is_array($userXML) || is_object($userXML)) {
+                    $usernameLower = strtolower($username);
+                    foreach ($userXML as $child) {
+                        if (isset($child['username']) && strtolower($child['username']) == $usernameLower || isset($child['email']) && strtolower($child['email']) == $usernameLower) {
+                            return true;
+                        }
+                    }
+                }
+            }
+        }
+        return false;
+    } catch (Requests_Exception $e) {
+        writeLog('success', 'Plex User Check Function - Error: '.$e->getMessage(), $username);
+    };
 }
-function plugin_auth_plex($username, $password) {
-	try{
-		$usernameLower = strtolower($username);
-		if((!empty($GLOBALS['plexAdmin']) && strtolower($GLOBALS['plexAdmin']) == $usernameLower) || checkPlexUser($username)){
-			//Login User
-			$url = 'https://plex.tv/users/sign_in.json';
-			$headers = array(
-				'Accept'=> 'application/json',
-				'Content-Type' => 'application/x-www-form-urlencoded',
-				'X-Plex-Product' => 'Organizr',
-				'X-Plex-Version' => '2.0',
-				'X-Plex-Client-Identifier' => '01010101-10101010',
-			);
-			$data = array(
-				'user[login]' => $username,
-				'user[password]' => $password,
-			);
-			$response = Requests::post($url, $headers, $data);
-			if($response->success){
-				$json = json_decode($response->body, true);
-				if ((is_array($json) && isset($json['user']) && isset($json['user']['username'])) && strtolower($json['user']['username']) == $usernameLower || strtolower($json['user']['email']) == $usernameLower) {
-					//writeLog("success", $json['user']['username']." was logged into organizr using plex credentials");
-	                return array(
-						'username' => $json['user']['username'],
-						'email' => $json['user']['email'],
-						'image' => $json['user']['thumb'],
-						'token' => $json['user']['authToken']
-					);
-				}
-			}
-		}
-		return false;
-	}catch( Requests_Exception $e ) {
-		writeLog('success', 'Plex Auth Function - Error: '.$e->getMessage(), $username);
-	};
+function plugin_auth_plex($username, $password)
+{
+    try {
+        $usernameLower = strtolower($username);
+        if ((!empty($GLOBALS['plexAdmin']) && strtolower($GLOBALS['plexAdmin']) == $usernameLower) || checkPlexUser($username)) {
+            //Login User
+            $url = 'https://plex.tv/users/sign_in.json';
+            $headers = array(
+                'Accept'=> 'application/json',
+                'Content-Type' => 'application/x-www-form-urlencoded',
+                'X-Plex-Product' => 'Organizr',
+                'X-Plex-Version' => '2.0',
+                'X-Plex-Client-Identifier' => '01010101-10101010',
+            );
+            $data = array(
+                'user[login]' => $username,
+                'user[password]' => $password,
+            );
+            $response = Requests::post($url, $headers, $data);
+            if ($response->success) {
+                $json = json_decode($response->body, true);
+                if ((is_array($json) && isset($json['user']) && isset($json['user']['username'])) && strtolower($json['user']['username']) == $usernameLower || strtolower($json['user']['email']) == $usernameLower) {
+                    //writeLog("success", $json['user']['username']." was logged into organizr using plex credentials");
+                    return array(
+                        'username' => $json['user']['username'],
+                        'email' => $json['user']['email'],
+                        'image' => $json['user']['thumb'],
+                        'token' => $json['user']['authToken']
+                    );
+                }
+            }
+        }
+        return false;
+    } catch (Requests_Exception $e) {
+        writeLog('success', 'Plex Auth Function - Error: '.$e->getMessage(), $username);
+    };
 }
-if (function_exists('ldap_connect')){
-	// Pass credentials to LDAP backend
-	function plugin_auth_ldap($username, $password) {
-		if(!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])){
-			$ldapServers = explode(',',$GLOBALS['authBackendHost']);
-			foreach($ldapServers as $key => $value) {
-				// Calculate parts
-				$digest = parse_url(trim($value));
-				$scheme = strtolower((isset($digest['scheme'])?$digest['scheme']:'ldap'));
-				$host = (isset($digest['host'])?$digest['host']:(isset($digest['path'])?$digest['path']:''));
-				$port = (isset($digest['port'])?$digest['port']:(strtolower($scheme)=='ldap'?389:636));
-				// Reassign
-				$ldapServers[$key] = $scheme.'://'.$host.':'.$port;
-			}
-			$ldap = ldap_connect(implode(' ',$ldapServers));
-			ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
-			ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
-			$bind = @ldap_bind($ldap, sprintf($GLOBALS['authBaseDN'], $username), $password);
-			return ($bind) ? true : false;
-		}
-		return false;
-	}
-}else{
-	// Ldap Auth Missing Dependancy
-	function plugin_auth_ldap_disabled() {
-		return 'LDAP - Disabled (Dependancy: php-ldap missing!)';
-	}
+if (function_exists('ldap_connect')) {
+    // Pass credentials to LDAP backend
+    function plugin_auth_ldap($username, $password)
+    {
+        if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
+            $ldapServers = explode(',', $GLOBALS['authBackendHost']);
+            foreach ($ldapServers as $key => $value) {
+                // Calculate parts
+                $digest = parse_url(trim($value));
+                $scheme = strtolower((isset($digest['scheme'])?$digest['scheme']:'ldap'));
+                $host = (isset($digest['host'])?$digest['host']:(isset($digest['path'])?$digest['path']:''));
+                $port = (isset($digest['port'])?$digest['port']:(strtolower($scheme)=='ldap'?389:636));
+                // Reassign
+                $ldapServers[$key] = $scheme.'://'.$host.':'.$port;
+            }
+            $ldap = ldap_connect(implode(' ', $ldapServers));
+            ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
+            ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
+            $bind = @ldap_bind($ldap, sprintf($GLOBALS['authBaseDN'], $username), $password);
+            return ($bind) ? true : false;
+        }
+        return false;
+    }
+} else {
+    // Ldap Auth Missing Dependancy
+    function plugin_auth_ldap_disabled()
+    {
+        return 'LDAP - Disabled (Dependancy: php-ldap missing!)';
+    }
 }
 // Pass credentials to FTP backend
-function plugin_auth_ftp($username, $password) {
-	// Calculate parts
-	$digest = parse_url($GLOBALS['authBackendHost']);
-	$scheme = strtolower((isset($digest['scheme'])?$digest['scheme']:(function_exists('ftp_ssl_connect')?'ftps':'ftp')));
-	$host = (isset($digest['host'])?$digest['host']:(isset($digest['path'])?$digest['path']:''));
-	$port = (isset($digest['port'])?$digest['port']:21);
-	// Determine Connection Type
-	if ($scheme == 'ftps') {
-		$conn_id = ftp_ssl_connect($host, $port, 20);
-	} elseif ($scheme == 'ftp') {
-		$conn_id = ftp_connect($host, $port, 20);
-	} else {
-		return false;
-	}
-	// Check if valid FTP connection
-	if ($conn_id) {
-		// Attempt login
-		@$login_result = ftp_login($conn_id, $username, $password);
-		ftp_close($conn_id);
-		// Return Result
-		if ($login_result) {
-			return true;
-		} else {
-			return false;
-		}
-	} else {
-		return false;
-	}
-	return false;
+function plugin_auth_ftp($username, $password)
+{
+    // Calculate parts
+    $digest = parse_url($GLOBALS['authBackendHost']);
+    $scheme = strtolower((isset($digest['scheme'])?$digest['scheme']:(function_exists('ftp_ssl_connect')?'ftps':'ftp')));
+    $host = (isset($digest['host'])?$digest['host']:(isset($digest['path'])?$digest['path']:''));
+    $port = (isset($digest['port'])?$digest['port']:21);
+    // Determine Connection Type
+    if ($scheme == 'ftps') {
+        $conn_id = ftp_ssl_connect($host, $port, 20);
+    } elseif ($scheme == 'ftp') {
+        $conn_id = ftp_connect($host, $port, 20);
+    } else {
+        return false;
+    }
+    // Check if valid FTP connection
+    if ($conn_id) {
+        // Attempt login
+        @$login_result = ftp_login($conn_id, $username, $password);
+        ftp_close($conn_id);
+        // Return Result
+        if ($login_result) {
+            return true;
+        } else {
+            return false;
+        }
+    } else {
+        return false;
+    }
+    return false;
 }
 
 // Pass credentials to Emby Backend
-function plugin_auth_emby_local($username, $password) {
-	try{
-		$url = qualifyURL($GLOBALS['embyURL']).'/Users/AuthenticateByName';
-		$headers = array(
-			'Authorization'=> 'MediaBrowser UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", Client="None", Device="Organizr", DeviceId="xxx", Version="1.0.0.0"',
-			'Content-Type' => 'application/json',
-		);
-		$data = array(
-			'Username' => $username,
-			'Password' => sha1($password),
-			'PasswordMd5' => md5($password),
-		);
-		$response = Requests::post($url, $headers, json_encode($data));
-		if($response->success){
-			$json = json_decode($response->body, true);
-			if (is_array($json) && isset($json['SessionInfo']) && isset($json['User']) && $json['User']['HasPassword'] == true) {
-				// Login Success - Now Logout Emby Session As We No Longer Need It
-				$headers = array(
-					'X-Mediabrowser-Token' => $json['AccessToken'],
-				);
-				$response = Requests::post(qualifyURL($GLOBALS['embyURL']).'/Sessions/Logout', $headers, array());
-				return true;
-			}
-		}
-		return false;
-	}catch( Requests_Exception $e ) {
-		writeLog('error', 'Emby Local Auth Function - Error: '.$e->getMessage(), $username);
-	};
+function plugin_auth_emby_local($username, $password)
+{
+    try {
+        $url = qualifyURL($GLOBALS['embyURL']).'/Users/AuthenticateByName';
+        $headers = array(
+            'Authorization'=> 'MediaBrowser UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", Client="None", Device="Organizr", DeviceId="xxx", Version="1.0.0.0"',
+            'Content-Type' => 'application/json',
+        );
+        $data = array(
+            'Username' => $username,
+            'Password' => sha1($password),
+            'PasswordMd5' => md5($password),
+        );
+        $response = Requests::post($url, $headers, json_encode($data));
+        if ($response->success) {
+            $json = json_decode($response->body, true);
+            if (is_array($json) && isset($json['SessionInfo']) && isset($json['User']) && $json['User']['HasPassword'] == true) {
+                // Login Success - Now Logout Emby Session As We No Longer Need It
+                $headers = array(
+                    'X-Mediabrowser-Token' => $json['AccessToken'],
+                );
+                $response = Requests::post(qualifyURL($GLOBALS['embyURL']).'/Sessions/Logout', $headers, array());
+                return true;
+            }
+        }
+        return false;
+    } catch (Requests_Exception $e) {
+        writeLog('error', 'Emby Local Auth Function - Error: '.$e->getMessage(), $username);
+    };
 }
 // Authenicate against emby connect
-function plugin_auth_emby_connect($username, $password) {
-	try{
-		// Get A User
-		$connectId = '';
-		$url = qualifyURL($GLOBALS['embyURL']).'/Users?api_key='.$GLOBALS['embyToken'];
-		$response = Requests::get($url);
-		if($response->success){
-			$json = json_decode($response->body, true);
-			if (is_array($json)) {
-				foreach ($json as $key => $value) { // Scan for this user
-					if (isset($value['ConnectUserName']) && isset($value['ConnectUserId'])) { // Qualifty as connect account
-						if ($value['ConnectUserName'] == $username || $value['Name'] == $username) {
-							$connectId = $value['ConnectUserId'];
-							writeLog('success', 'Emby Connect Auth Function - Found User', $username);
-							break;
-						}
-					}
-				}
-				if ($connectId) {
-					$connectURL = 'https://connect.emby.media/service/user/authenticate';
-					$headers = array(
-						'Accept'=> 'application/json',
-						'Content-Type' => 'application/x-www-form-urlencoded',
-					);
-					$data = array(
-						'nameOrEmail' => $username,
-						'rawpw' => $password,
-					);
-					$response = Requests::post($connectURL, $headers, $data);
-					if($response->success){
-						$json = json_decode($response->body, true);
-						if (is_array($json) && isset($json['AccessToken']) && isset($json['User']) && $json['User']['Id'] == $connectId) {
-							return array(
-								'email' => $json['User']['Email'],
-								'image' => $json['User']['ImageUrl'],
-							);
-						}
-					}
-				}
-			}
-		}
-		return false;
-	}catch( Requests_Exception $e ) {
-		writeLog('error', 'Emby Connect Auth Function - Error: '.$e->getMessage(), $username);
-		return false;
-	};
+function plugin_auth_emby_connect($username, $password)
+{
+    try {
+        // Get A User
+        $connectId = '';
+        $url = qualifyURL($GLOBALS['embyURL']).'/Users?api_key='.$GLOBALS['embyToken'];
+        $response = Requests::get($url);
+        if ($response->success) {
+            $json = json_decode($response->body, true);
+            if (is_array($json)) {
+                foreach ($json as $key => $value) { // Scan for this user
+                    if (isset($value['ConnectUserName']) && isset($value['ConnectUserId'])) { // Qualifty as connect account
+                        if ($value['ConnectUserName'] == $username || $value['Name'] == $username) {
+                            $connectId = $value['ConnectUserId'];
+                            writeLog('success', 'Emby Connect Auth Function - Found User', $username);
+                            break;
+                        }
+                    }
+                }
+                if ($connectId) {
+                    $connectURL = 'https://connect.emby.media/service/user/authenticate';
+                    $headers = array(
+                        'Accept'=> 'application/json',
+                        'Content-Type' => 'application/x-www-form-urlencoded',
+                    );
+                    $data = array(
+                        'nameOrEmail' => $username,
+                        'rawpw' => $password,
+                    );
+                    $response = Requests::post($connectURL, $headers, $data);
+                    if ($response->success) {
+                        $json = json_decode($response->body, true);
+                        if (is_array($json) && isset($json['AccessToken']) && isset($json['User']) && $json['User']['Id'] == $connectId) {
+                            return array(
+                                'email' => $json['User']['Email'],
+                                'image' => $json['User']['ImageUrl'],
+                            );
+                        }
+                    }
+                }
+            }
+        }
+        return false;
+    } catch (Requests_Exception $e) {
+        writeLog('error', 'Emby Connect Auth Function - Error: '.$e->getMessage(), $username);
+        return false;
+    };
 }
 // Authenticate Against Emby Local (first) and Emby Connect
-function plugin_auth_emby_all($username, $password) {
-	$localResult = plugin_auth_emby_local($username, $password);
-	if ($localResult) {
-		return $localResult;
-	} else {
-		return plugin_auth_emby_connect($username, $password);
-	}
+function plugin_auth_emby_all($username, $password)
+{
+    $localResult = plugin_auth_emby_local($username, $password);
+    if ($localResult) {
+        return $localResult;
+    } else {
+        return plugin_auth_emby_connect($username, $password);
+    }
 }

+ 118 - 111
api/functions/config-functions.php

@@ -1,141 +1,148 @@
 <?php
 
 // Create config file in the return syntax
-function createConfig($array, $path = null, $nest = 0) {
+function createConfig($array, $path = null, $nest = 0)
+{
     $path = ($path) ? $path : $GLOBALS['userConfigPath'];
-	// Define Initial Value
-	$output = array();
+    // Define Initial Value
+    $output = array();
 
-	// Sort Items
-	ksort($array);
+    // Sort Items
+    ksort($array);
 
-	// Update the current config version
-	if (!$nest) {
-		// Inject Current Version
-		$output[] = "\t'configVersion' => '".(isset($array['apply_CONFIG_VERSION'])?$array['apply_CONFIG_VERSION']:$GLOBALS['installedVersion'])."'";
-	}
-	unset($array['configVersion']);
-	unset($array['apply_CONFIG_VERSION']);
+    // Update the current config version
+    if (!$nest) {
+        // Inject Current Version
+        $output[] = "\t'configVersion' => '".(isset($array['apply_CONFIG_VERSION'])?$array['apply_CONFIG_VERSION']:$GLOBALS['installedVersion'])."'";
+    }
+    unset($array['configVersion']);
+    unset($array['apply_CONFIG_VERSION']);
 
-	// Process Settings
-	foreach ($array as $k => $v) {
-		$allowCommit = true;
-		switch (gettype($v)) {
-			case 'boolean':
-				$item = ($v?'true':'false');
-				break;
-			case 'integer':
-			case 'double':
-			case 'integer':
-			case 'NULL':
-				$item = $v;
-				break;
-			case 'string':
-				$item = "'".str_replace(array('\\',"'"),array('\\\\',"\'"),$v)."'";
-				break;
-			case 'array':
-				$item = createConfig($v, false, $nest+1);
-				break;
-			default:
-				$allowCommit = false;
-		}
+    // Process Settings
+    foreach ($array as $k => $v) {
+        $allowCommit = true;
+        switch (gettype($v)) {
+            case 'boolean':
+                $item = ($v?'true':'false');
+                break;
+            case 'integer':
+            case 'double':
+            case 'integer':
+            case 'NULL':
+                $item = $v;
+                break;
+            case 'string':
+                $item = "'".str_replace(array('\\',"'"), array('\\\\',"\'"), $v)."'";
+                break;
+            case 'array':
+                $item = createConfig($v, false, $nest+1);
+                break;
+            default:
+                $allowCommit = false;
+        }
 
-		if($allowCommit) {
-			$output[] = str_repeat("\t",$nest+1)."'$k' => $item";
-		}
-	}
+        if ($allowCommit) {
+            $output[] = str_repeat("\t", $nest+1)."'$k' => $item";
+        }
+    }
 
-	// Build output
-	$output = (!$nest?"<?php\nreturn ":'')."array(\n".implode(",\n",$output)."\n".str_repeat("\t",$nest).')'.(!$nest?';':'');
+    // Build output
+    $output = (!$nest?"<?php\nreturn ":'')."array(\n".implode(",\n", $output)."\n".str_repeat("\t", $nest).')'.(!$nest?';':'');
 
-	if (!$nest && $path) {
-		$pathDigest = pathinfo($path);
+    if (!$nest && $path) {
+        $pathDigest = pathinfo($path);
 
-		@mkdir($pathDigest['dirname'], 0770, true);
+        @mkdir($pathDigest['dirname'], 0770, true);
 
-		if (file_exists($path)) {
-			rename($path, $pathDigest['dirname'].'/'.$pathDigest['filename'].'.bak.php');
-		}
+        if (file_exists($path)) {
+            rename($path, $pathDigest['dirname'].'/'.$pathDigest['filename'].'.bak.php');
+        }
 
-		$file = fopen($path, 'w');
-		fwrite($file, $output);
-		fclose($file);
-		if (file_exists($path)) {
-			return true;
-		}
-		// writeLog("error", "config was unable to write");
-		return false;
-	} else {
-  		// writeLog("success", "config was updated with new values");
-		return $output;
-	}
+        $file = fopen($path, 'w');
+        fwrite($file, $output);
+        fclose($file);
+        if (file_exists($path)) {
+            return true;
+        }
+        // writeLog("error", "config was unable to write");
+        return false;
+    } else {
+        // writeLog("success", "config was updated with new values");
+        return $output;
+    }
 }
 // Commit new values to the configuration
-function updateConfig($new, $current = false) {
-	// Get config if not supplied
-	if ($current === false) {
-		$current = loadConfig();
-	} else if (is_string($current) && is_file($current)) {
-		$current = loadConfig($current);
-	}
-	// Inject Parts
-	foreach ($new as $k => $v) {
-		$current[$k] = $v;
-	}
-	// Return Create
-	return createConfig($current);
+function updateConfig($new, $current = false)
+{
+    // Get config if not supplied
+    if ($current === false) {
+        $current = loadConfig();
+    } elseif (is_string($current) && is_file($current)) {
+        $current = loadConfig($current);
+    }
+    // Inject Parts
+    foreach ($new as $k => $v) {
+        $current[$k] = $v;
+    }
+    // Return Create
+    return createConfig($current);
 }
-function configLazy() {
-	// Load config or default
-	if (file_exists($GLOBALS['userConfigPath'])) {
-		$config = fillDefaultConfig(loadConfig($GLOBALS['userConfigPath']));
-	} else {
-		$config = loadConfig($GLOBALS['defaultConfigPath']);
-	}
-	if (is_array($config)) {
-		defineConfig($config);
-	}
-	return $config;
+function configLazy()
+{
+    // Load config or default
+    if (file_exists($GLOBALS['userConfigPath'])) {
+        $config = fillDefaultConfig(loadConfig($GLOBALS['userConfigPath']));
+    } else {
+        $config = loadConfig($GLOBALS['defaultConfigPath']);
+    }
+    if (is_array($config)) {
+        defineConfig($config);
+    }
+    return $config;
 }
-function loadConfig($path = null){
+function loadConfig($path = null)
+{
     $path = ($path) ? $path : $GLOBALS['userConfigPath'];
     if (!is_file($path)) {
         return null;
     } else {
-        return (array) call_user_func(function() use($path) {
+        return (array) call_user_func(function () use ($path) {
             return include($path);
         });
     }
 }
-function fillDefaultConfig($array) {
+function fillDefaultConfig($array)
+{
     $path = $GLOBALS['defaultConfigPath'];
-	if (is_string($path)) {
-		$loadedDefaults = loadConfig($path);
-	} else {
-		$loadedDefaults = $path;
-	}
-	// Include all plugin config files
-	foreach (glob(dirname(__DIR__,1).DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . "*.php") as $filename){
-		$loadedDefaults = array_merge($loadedDefaults , loadConfig($filename));
-	}
-	return (is_array($loadedDefaults) ? fillDefaultConfig_recurse($array, $loadedDefaults) : false);
+    if (is_string($path)) {
+        $loadedDefaults = loadConfig($path);
+    } else {
+        $loadedDefaults = $path;
+    }
+    // Include all plugin config files
+    foreach (glob(dirname(__DIR__, 1).DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . "*.php") as $filename) {
+        $loadedDefaults = array_merge($loadedDefaults, loadConfig($filename));
+    }
+    return (is_array($loadedDefaults) ? fillDefaultConfig_recurse($array, $loadedDefaults) : false);
 }
-function fillDefaultConfig_recurse($current, $defaults) {
-	foreach($defaults as $k => $v) {
-		if (!isset($current[$k])) {
-			$current[$k] = $v;
-		} else if (is_array($current[$k]) && is_array($v)) {
-			$current[$k] = fillDefaultConfig_recurse($current[$k], $v);
-		}
-	}
-	return $current;
+function fillDefaultConfig_recurse($current, $defaults)
+{
+    foreach ($defaults as $k => $v) {
+        if (!isset($current[$k])) {
+            $current[$k] = $v;
+        } elseif (is_array($current[$k]) && is_array($v)) {
+            $current[$k] = fillDefaultConfig_recurse($current[$k], $v);
+        }
+    }
+    return $current;
 }
-function defineConfig($array, $anyCase = true, $nest_prefix = false) {
-	foreach($array as $k => $v) {
-		if (is_scalar($v) && !defined($nest_prefix.$k)) {
+function defineConfig($array, $anyCase = true, $nest_prefix = false)
+{
+    foreach ($array as $k => $v) {
+        if (is_scalar($v) && !defined($nest_prefix.$k)) {
             $GLOBALS[$nest_prefix.$k] = $v;
-		} else if (is_array($v)) {
-			defineConfig($v, $anyCase, $nest_prefix.$k.'_');
-		}
-	}
+        } elseif (is_array($v)) {
+            defineConfig($v, $anyCase, $nest_prefix.$k.'_');
+        }
+    }
 }

+ 581 - 497
api/functions/deluge.class.php

@@ -1,500 +1,584 @@
 <?php
 
-class deluge {
-	private $ch;
-	private $url;
-	private $request_id;
-
-	function __construct($host, $password)
-	{
-		$this->url = $host . (substr($host, -1) == "/" ? "" : "/") . "json";
-		$this->request_id = 0;
-		$this->ch = curl_init($this->url);
-		$curl_options = array(
-			CURLOPT_RETURNTRANSFER => true,
-			CURLOPT_HTTPHEADER => array("Accept: application/json", "Content-Type: application/json"),
-			CURLOPT_ENCODING => "",
-			CURLOPT_COOKIEJAR  => "",
-			CURLOPT_CONNECTTIMEOUT => 10,
-			CURLOPT_TIMEOUT => 10,
-			CURLOPT_CAINFO => getCert(),
-	        CURLOPT_SSL_VERIFYHOST => localURL($host) ? 0 : 2,
-	        CURLOPT_SSL_VERIFYPEER => localURL($host) ? 0 : 2,
-			//CURLOPT_SSL_VERIFYPEER => false, THIS IS INSECURE!! However, deluge appears not to send intermediate certificates, so it can be necessary. Use with caution!
-		);
-		curl_setopt_array($this->ch, $curl_options);
-
-		//Log in and get cookies
-		try {
-			$result = $this->makeRequest("auth.login", array($password));
-			if ($result === false)
-				throw new Exception("Login failed");
-		}
-		catch (Exception $e) {
-			throw new Exception("Failed to initiate deluge api", 0, $e);
-		}
-	}
-
-	/////////////////////////////
-	//
-	//webapi functions (https://github.com/idlesign/deluge-webapi)
-	//
-	/////////////////////////////
-
-	//ids is an array of hashes, or null for all
-	//params is an array of params:
-	//active_time, all_time_download, comment, compact, distributed_copies, download_payload_rate, eta, file_priorities, file_progress, files, hash, is_auto_managed, is_finished, is_seed, max_connections, max_download_speed, max_upload_slots, max_upload_speed, message, move_completed, move_completed_path, move_on_completed, move_on_completed_path, name, next_announce, num_files, num_peers, num_pieces, num_seeds, paused, peers, piece_length, prioritize_first_last, private, progress, queue, ratio, remove_at_ratio, save_path, seed_rank, seeding_time, seeds_peers_ratio, state, stop_at_ratio, stop_ratio, time_added, total_done, total_payload_download, total_payload_upload, total_peers, total_seeds, total_size, total_uploaded, total_wanted, tracker, tracker_host, tracker_status, trackers, upload_payload_rate
-	//or an empty array for all (or null, which returns comment, hash, name, save_path)
-	public function getTorrents($ids, $params) {
-		return $this->makeRequest("webapi.get_torrents", array($ids, $params))->torrents;
-	}
-
-	//metainfo is base64 encoded torrent data or a magnet url
-	//returns a torrent hash or null if the torrent wasn't aded
-	//params are torrent addition parameters like download_location?
-	public function addTorrent($metaInfo, $params) {
-		return $this->makeRequest("webapi.add_torrent", array($metaInfo, $params));
-	}
-
-	/*implemented in core
-	public function removeTorrent($hash, $removeData) {
-		return $this->makeRequest("webapi.remove_torrent", array($hash, $removeData));
-	}*/
-
-	public function getWebAPIVersion() {
-		return $this->makeRequest("webapi.get_api_version", array());
-	}
-
-	/////////////////////////////
-	//
-	//core functions
-	//
-	//parsed from https://web.archive.org/web/20150423162855/http://deluge-torrent.org:80/docs/master/core/rpc.html
-	//
-	/////////////////////////////
-
-	//Adds a torrent file to the session.
-	//Parameters:
-	//filename (string) – the filename of the torrent
-	//filedump (string) – a base64 encoded string of the torrent file contents
-	//options (dict) – the options to apply to the torrent on add
-	public function addTorrentFile($filename, $filedump, $options) {
-		return $this->makeRequest("core.add_torrent_file", array($filename, $filedump, $options));
-	}
-
-	//Adds a torrent from a magnet link.
-	//Parameters:
-	//uri (string) – the magnet link
-	//options (dict) – the options to apply to the torrent on add
-	public function addTorrentMagnet($uri, $options) {
-		return $this->makeRequest("core.add_torrent_magnet", array($uri, $options));
-	}
-
-	//Adds a torrent from a url. Deluge will attempt to fetch the torrentfrom url prior to adding it to the session.
-	//Parameters:
-	//url (string) – the url pointing to the torrent file
-	//options (dict) – the options to apply to the torrent on add
-	//headers (dict) – any optional headers to send
-	public function addTorrentUrl($url, $options, $headers) {
-		return $this->makeRequest("core.add_torrent_url", array($url, $options, $headers));
-	}
-
-	public function connectPeer($torrentId, $ip, $port) {
-		return $this->makeRequest("core.connect_peer", array($torrentId, $ip, $port));
-	}
-
-	public function createTorrent($path, $tracker, $pieceLength, $comment, $target, $webseeds, $private, $createdBy, $trackers, $addToSession) {
-		return $this->makeRequest("core.create_torrent", array($path, $tracker, $pieceLength, $comment, $target, $webseeds, $private, $createdBy, $trackers, $addToSession));
-	}
-
-	public function disablePlugin($plugin) {
-		return $this->makeRequest("core.disable_plugin", array($plugin));
-	}
-
-	public function enablePlugin($plugin) {
-		return $this->makeRequest("core.enable_plugin", array($plugin));
-	}
-
-	public function forceReannounce($torrentIds) {
-		return $this->makeRequest("core.force_reannounce", array($torrentIds));
-	}
-
-	//Forces a data recheck on torrent_ids
-	public function forceRecheck($torrentIds) {
-		return $this->makeRequest("core.force_recheck", array($torrentIds));
-	}
-
-	//Returns a list of plugins available in the core
-	public function getAvailablePlugins() {
-		return $this->makeRequest("core.get_available_plugins", array());
-	}
-
-	//Returns a dictionary of the session’s cache status.
-	public function getCacheStatus() {
-		return $this->makeRequest("core.get_cache_status", array());
-	}
-
-	//Get all the preferences as a dictionary
-	public function getConfig() {
-		return $this->makeRequest("core.get_config", array());
-	}
-
-	//Get the config value for key
-	public function getConfigValue($key) {
-		return $this->makeRequest("core.get_config_value", array($key));
-	}
-
-	//Get the config values for the entered keys
-	public function getConfigValues($keys) {
-		return $this->makeRequest("core.get_config_values", array($keys));
-	}
-
-	//Returns a list of enabled plugins in the core
-	public function getEnabledPlugins() {
-		return $this->makeRequest("core.get_enabled_plugins", array());
-	}
-
-	//returns {field: [(value,count)] }for use in sidebar(s)
-	public function getFilterTree($showZeroHits, $hideCat) {
-		return $this->makeRequest("core.get_filter_tree", array($showZeroHits, $hideCat));
-	}
-
-	//Returns the number of free bytes at path
-	public function getFreeSpace($path) {
-		return $this->makeRequest("core.get_free_space", array($path));
-	}
-
-	//Returns the libtorrent version.
-	public function getLibtorrentVersion() {
-		return $this->makeRequest("core.get_libtorrent_version", array());
-	}
-
-	//Returns the active listen port
-	public function getListenPort() {
-		return $this->makeRequest("core.get_listen_port", array());
-	}
-
-	//Returns the current number of connections
-	public function getNumConnections() {
-		return $this->makeRequest("core.get_num_connections", array());
-	}
-
-	public function getPathSize($path) {
-		return $this->makeRequest("core.get_path_size", array($path));
-	}
-
-	//Returns a list of torrent_ids in the session.
-	public function getSessionState() {
-		return $this->makeRequest("core.get_session_state", array());
-	}
-
-	//Gets the session status values for ‘keys’, these keys are takingfrom libtorrent’s session status.
-	public function getSessionStatus($keys) {
-		return $this->makeRequest("core.get_session_status", array($keys));
-	}
-
-	public function getTorrentStatus($torrentId, $keys, $diff) {
-		return $this->makeRequest("core.get_torrent_status", array($torrentId, $keys, $diff));
-	}
-
-	//returns all torrents , optionally filtered by filter_dict.
-	public function getTorrentsStatus($filterDict, $keys, $diff) {
-		return $this->makeRequest("core.get_torrents_status", array($filterDict, $keys, $diff));
-	}
-
-	public function glob($path) {
-		return $this->makeRequest("core.glob", array($path));
-	}
-
-	public function moveStorage($torrentIds, $dest) {
-		return $this->makeRequest("core.move_storage", array($torrentIds, $dest));
-	}
-
-	//Pause all torrents in the session
-	public function pauseAllTorrents() {
-		return $this->makeRequest("core.pause_all_torrents", array());
-	}
-
-	public function pauseTorrent($torrentIds) {
-		return $this->makeRequest("core.pause_torrent", array($torrentIds));
-	}
-
-	public function queueBottom($torrentIds) {
-		return $this->makeRequest("core.queue_bottom", array($torrentIds));
-	}
-
-	public function queueDown($torrentIds) {
-		return $this->makeRequest("core.queue_down", array($torrentIds));
-	}
-
-	public function queueTop($torrentIds) {
-		return $this->makeRequest("core.queue_top", array($torrentIds));
-	}
-
-	public function queueUp($torrentIds) {
-		return $this->makeRequest("core.queue_up", array($torrentIds));
-	}
-
-	//Removes a torrent from the session.
-	//Parameters:
-	//torrentId (string) – the torrentId of the torrent to remove
-	//removeData (boolean) – if True, remove the data associated with this torrent
-	public function removeTorrent($torrentId, $removeData) {
-		return $this->makeRequest("core.remove_torrent", array($torrentId, $removeData));
-	}
-
-	//Rename files in torrent_id.  Since this is an asynchronous operation bylibtorrent, watch for the TorrentFileRenamedEvent to know when thefiles have been renamed.
-	//Parameters:
-	//torrentId (string) – the torrentId to rename files
-	//filenames (((index, filename), ...)) – a list of index, filename pairs
-	public function renameFiles($torrentId, $filenames) {
-		return $this->makeRequest("core.rename_files", array($torrentId, $filenames));
-	}
-
-	//Renames the ‘folder’ to ‘new_folder’ in ‘torrent_id’.  Watch for theTorrentFolderRenamedEvent which is emitted when the folder has beenrenamed successfully.
-	//Parameters:
-	//torrentId (string) – the torrent to rename folder in
-	//folder (string) – the folder to rename
-	//newFolder (string) – the new folder name
-	public function renameFolder($torrentId, $folder, $newFolder) {
-		return $this->makeRequest("core.rename_folder", array($torrentId, $folder, $newFolder));
-	}
-
-	//Rescans the plugin folders for new plugins
-	public function rescanPlugins() {
-		return $this->makeRequest("core.rescan_plugins", array());
-	}
-
-	//Resume all torrents in the session
-	public function resumeAllTorrents() {
-		return $this->makeRequest("core.resume_all_torrents", array());
-	}
-
-	public function resumeTorrent($torrentIds) {
-		return $this->makeRequest("core.resume_torrent", array($torrentIds));
-	}
-
-	//Set the config with values from dictionary
-	public function setConfig($config) {
-		return $this->makeRequest("core.set_config", array($config));
-	}
-
-	//Sets the auto managed flag for queueing purposes
-	public function setTorrentAutoManaged($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_auto_managed", array($torrentId, $value));
-	}
-
-	//Sets a torrents file priorities
-	public function setTorrentFilePriorities($torrentId, $priorities) {
-		return $this->makeRequest("core.set_torrent_file_priorities", array($torrentId, $priorities));
-	}
-
-	//Sets a torrents max number of connections
-	public function setTorrentMaxConnections($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_max_connections", array($torrentId, $value));
-	}
-
-	//Sets a torrents max download speed
-	public function setTorrentMaxDownloadSpeed($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_max_download_speed", array($torrentId, $value));
-	}
-
-	//Sets a torrents max number of upload slots
-	public function setTorrentMaxUploadSlots($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_max_upload_slots", array($torrentId, $value));
-	}
-
-	//Sets a torrents max upload speed
-	public function setTorrentMaxUploadSpeed($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_max_upload_speed", array($torrentId, $value));
-	}
-
-	//Sets the torrent to be moved when completed
-	public function setTorrentMoveCompleted($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_move_completed", array($torrentId, $value));
-	}
-
-	//Sets the path for the torrent to be moved when completed
-	public function setTorrentMoveCompletedPath($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_move_completed_path", array($torrentId, $value));
-	}
-
-	//Sets the torrent options for torrent_ids
-	public function setTorrentOptions($torrentIds, $options) {
-		return $this->makeRequest("core.set_torrent_options", array($torrentIds, $options));
-	}
-
-	//Sets a higher priority to the first and last pieces
-	public function setTorrentPrioritizeFirstLast($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_prioritize_first_last", array($torrentId, $value));
-	}
-
-	//Sets the torrent to be removed at ‘stop_ratio’
-	public function setTorrentRemoveAtRatio($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_remove_at_ratio", array($torrentId, $value));
-	}
-
-	//Sets the torrent to stop at ‘stop_ratio’
-	public function setTorrentStopAtRatio($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_stop_at_ratio", array($torrentId, $value));
-	}
-
-	//Sets the ratio when to stop a torrent if ‘stop_at_ratio’ is set
-	public function setTorrentStopRatio($torrentId, $value) {
-		return $this->makeRequest("core.set_torrent_stop_ratio", array($torrentId, $value));
-	}
-
-	//Sets a torrents tracker list.  trackers will be [{“url”, “tier”}]
-	public function setTorrentTrackers($torrentId, $trackers) {
-		return $this->makeRequest("core.set_torrent_trackers", array($torrentId, $trackers));
-	}
-
-	//Checks if the active port is open
-	public function testListenPort() {
-		return $this->makeRequest("core.test_listen_port", array());
-	}
-
-	public function uploadPlugin($filename, $filedump) {
-		return $this->makeRequest("core.upload_plugin", array($filename, $filedump));
-	}
-
-	//Returns a list of the exported methods.
-	public function getMethodList() {
-		return $this->makeRequest("daemon.get_method_list", array());
-	}
-
-	//Returns some info from the daemon.
-	public function info() {
-		return $this->makeRequest("daemon.info", array());
-	}
-
-	public function shutdown(...$params) {
-		return $this->makeRequest("daemon.shutdown", $params);
-	}
-
-	/////////////////////////////
-	//
-	//web ui functions
-	//
-	//parsed from https://web.archive.org/web/20150423143401/http://deluge-torrent.org:80/docs/master/modules/ui/web/json_api.html#module-deluge.ui.web.json_api
-	//
-	/////////////////////////////
-
-	//Parameters:
-	//host (string) – the hostname
-	//port (int) – the port
-	//username (string) – the username to login as
-	//password (string) – the password to login with
-	public function addHost($host, $port, $username, $password) {
-		return $this->makeRequest("web.add_host", array($host, $port, $username, $password));
-	}
-
-	//Usage
-	public function addTorrents($torrents) {
-		return $this->makeRequest("web.add_torrents", array($torrents));
-	}
-
-	public function connect($hostId) {
-		return $this->makeRequest("web.connect", array($hostId));
-	}
-
-	public function connected() {
-		return $this->makeRequest("web.connected", array());
-	}
-
-	public function deregisterEventListener($event) {
-		return $this->makeRequest("web.deregister_event_listener", array($event));
-	}
-
-	public function disconnect() {
-		return $this->makeRequest("web.disconnect", array());
-	}
-
-	public function downloadTorrentFromUrl($url, $cookie) {
-		return $this->makeRequest("web.download_torrent_from_url", array($url, $cookie));
-	}
-
-	/* in core
-	public function getConfig() {
-		return $this->makeRequest("web.get_config", array());
-	}*/
-
-	public function getEvents() {
-		return $this->makeRequest("web.get_events", array());
-	}
-
-	public function getHost($hostId) {
-		return $this->makeRequest("web.get_host", array($hostId));
-	}
-
-	public function getHostStatus($hostId) {
-		return $this->makeRequest("web.get_host_status", array($hostId));
-	}
-
-	public function getHosts() {
-		return $this->makeRequest("web.get_hosts", array());
-	}
-
-	public function getTorrentFiles($torrentId) {
-		return $this->makeRequest("web.get_torrent_files", array($torrentId));
-	}
-
-	public function getTorrentInfo($filename) {
-		return $this->makeRequest("web.get_torrent_info", array($filename));
-	}
-
-	public function registerEventListener($event) {
-		return $this->makeRequest("web.register_event_listener", array($event));
-	}
-
-	public function removeHost($connectionId) {
-		return $this->makeRequest("web.remove_host", array($connectionId));
-	}
-
-	/*in core
-	public function setConfig($config) {
-		return $this->makeRequest("web.set_config", array($config));
-	}*/
-
-	public function startDaemon($port) {
-		return $this->makeRequest("web.start_daemon", array($port));
-	}
-
-	public function stopDaemon($hostId) {
-		return $this->makeRequest("web.stop_daemon", array($hostId));
-	}
-
-	//Parameters:
-	//keys (list) – the information about the torrents to gather
-	//filterDict (dictionary) – the filters to apply when selecting torrents.
-	public function updateUi($keys, $filterDict) {
-		return $this->makeRequest("web.update_ui", array($keys, $filterDict));
-	}
-
-	private function makeRequest($method, $params) {
-		$post_data = array("id" => $this->request_id, "method" => $method, "params" => $params);
-		curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($post_data));
-
-		$result = curl_exec($this->ch);
-
-		if ($result === false)
-			throw new Exception("Could not log in due to curl error (no. " . curl_errno($this->ch) . "): " . curl_error($this->ch));
-
-		$http_code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
-
-		if ($http_code != 200)
-			throw new Exception("Request for method $method returned http code $http_code");
-
-		$result = json_decode($result);
-		if (!is_null($result->error))
-			throw new Exception("Method request returned an error (no. " . $result->error->code . "): " . $result->error->message);
-
-		if ($result->id != $this->request_id)
-			throw new Exception("Response id did not match request id");
-
-		$this->request_id++;
-		return $result->result;
-	}
+class deluge
+{
+    private $ch;
+    private $url;
+    private $request_id;
+
+    public function __construct($host, $password)
+    {
+        $this->url = $host . (substr($host, -1) == "/" ? "" : "/") . "json";
+        $this->request_id = 0;
+        $this->ch = curl_init($this->url);
+        $curl_options = array(
+            CURLOPT_RETURNTRANSFER => true,
+            CURLOPT_HTTPHEADER => array("Accept: application/json", "Content-Type: application/json"),
+            CURLOPT_ENCODING => "",
+            CURLOPT_COOKIEJAR  => "",
+            CURLOPT_CONNECTTIMEOUT => 10,
+            CURLOPT_TIMEOUT => 10,
+            CURLOPT_CAINFO => getCert(),
+            CURLOPT_SSL_VERIFYHOST => localURL($host) ? 0 : 2,
+            CURLOPT_SSL_VERIFYPEER => localURL($host) ? 0 : 2,
+            //CURLOPT_SSL_VERIFYPEER => false, THIS IS INSECURE!! However, deluge appears not to send intermediate certificates, so it can be necessary. Use with caution!
+        );
+        curl_setopt_array($this->ch, $curl_options);
+
+        //Log in and get cookies
+        try {
+            $result = $this->makeRequest("auth.login", array($password));
+            if ($result === false) {
+                throw new Exception("Login failed");
+            }
+        } catch (Exception $e) {
+            throw new Exception("Failed to initiate deluge api", 0, $e);
+        }
+    }
+
+    /////////////////////////////
+    //
+    //webapi functions (https://github.com/idlesign/deluge-webapi)
+    //
+    /////////////////////////////
+
+    //ids is an array of hashes, or null for all
+    //params is an array of params:
+    //active_time, all_time_download, comment, compact, distributed_copies, download_payload_rate, eta, file_priorities, file_progress, files, hash, is_auto_managed, is_finished, is_seed, max_connections, max_download_speed, max_upload_slots, max_upload_speed, message, move_completed, move_completed_path, move_on_completed, move_on_completed_path, name, next_announce, num_files, num_peers, num_pieces, num_seeds, paused, peers, piece_length, prioritize_first_last, private, progress, queue, ratio, remove_at_ratio, save_path, seed_rank, seeding_time, seeds_peers_ratio, state, stop_at_ratio, stop_ratio, time_added, total_done, total_payload_download, total_payload_upload, total_peers, total_seeds, total_size, total_uploaded, total_wanted, tracker, tracker_host, tracker_status, trackers, upload_payload_rate
+    //or an empty array for all (or null, which returns comment, hash, name, save_path)
+    public function getTorrents($ids, $params)
+    {
+        return $this->makeRequest("webapi.get_torrents", array($ids, $params))->torrents;
+    }
+
+    //metainfo is base64 encoded torrent data or a magnet url
+    //returns a torrent hash or null if the torrent wasn't aded
+    //params are torrent addition parameters like download_location?
+    public function addTorrent($metaInfo, $params)
+    {
+        return $this->makeRequest("webapi.add_torrent", array($metaInfo, $params));
+    }
+
+    /*implemented in core
+    public function removeTorrent($hash, $removeData) {
+        return $this->makeRequest("webapi.remove_torrent", array($hash, $removeData));
+    }*/
+
+    public function getWebAPIVersion()
+    {
+        return $this->makeRequest("webapi.get_api_version", array());
+    }
+
+    /////////////////////////////
+    //
+    //core functions
+    //
+    //parsed from https://web.archive.org/web/20150423162855/http://deluge-torrent.org:80/docs/master/core/rpc.html
+    //
+    /////////////////////////////
+
+    //Adds a torrent file to the session.
+    //Parameters:
+    //filename (string) – the filename of the torrent
+    //filedump (string) – a base64 encoded string of the torrent file contents
+    //options (dict) – the options to apply to the torrent on add
+    public function addTorrentFile($filename, $filedump, $options)
+    {
+        return $this->makeRequest("core.add_torrent_file", array($filename, $filedump, $options));
+    }
+
+    //Adds a torrent from a magnet link.
+    //Parameters:
+    //uri (string) – the magnet link
+    //options (dict) – the options to apply to the torrent on add
+    public function addTorrentMagnet($uri, $options)
+    {
+        return $this->makeRequest("core.add_torrent_magnet", array($uri, $options));
+    }
+
+    //Adds a torrent from a url. Deluge will attempt to fetch the torrentfrom url prior to adding it to the session.
+    //Parameters:
+    //url (string) – the url pointing to the torrent file
+    //options (dict) – the options to apply to the torrent on add
+    //headers (dict) – any optional headers to send
+    public function addTorrentUrl($url, $options, $headers)
+    {
+        return $this->makeRequest("core.add_torrent_url", array($url, $options, $headers));
+    }
+
+    public function connectPeer($torrentId, $ip, $port)
+    {
+        return $this->makeRequest("core.connect_peer", array($torrentId, $ip, $port));
+    }
+
+    public function createTorrent($path, $tracker, $pieceLength, $comment, $target, $webseeds, $private, $createdBy, $trackers, $addToSession)
+    {
+        return $this->makeRequest("core.create_torrent", array($path, $tracker, $pieceLength, $comment, $target, $webseeds, $private, $createdBy, $trackers, $addToSession));
+    }
+
+    public function disablePlugin($plugin)
+    {
+        return $this->makeRequest("core.disable_plugin", array($plugin));
+    }
+
+    public function enablePlugin($plugin)
+    {
+        return $this->makeRequest("core.enable_plugin", array($plugin));
+    }
+
+    public function forceReannounce($torrentIds)
+    {
+        return $this->makeRequest("core.force_reannounce", array($torrentIds));
+    }
+
+    //Forces a data recheck on torrent_ids
+    public function forceRecheck($torrentIds)
+    {
+        return $this->makeRequest("core.force_recheck", array($torrentIds));
+    }
+
+    //Returns a list of plugins available in the core
+    public function getAvailablePlugins()
+    {
+        return $this->makeRequest("core.get_available_plugins", array());
+    }
+
+    //Returns a dictionary of the session’s cache status.
+    public function getCacheStatus()
+    {
+        return $this->makeRequest("core.get_cache_status", array());
+    }
+
+    //Get all the preferences as a dictionary
+    public function getConfig()
+    {
+        return $this->makeRequest("core.get_config", array());
+    }
+
+    //Get the config value for key
+    public function getConfigValue($key)
+    {
+        return $this->makeRequest("core.get_config_value", array($key));
+    }
+
+    //Get the config values for the entered keys
+    public function getConfigValues($keys)
+    {
+        return $this->makeRequest("core.get_config_values", array($keys));
+    }
+
+    //Returns a list of enabled plugins in the core
+    public function getEnabledPlugins()
+    {
+        return $this->makeRequest("core.get_enabled_plugins", array());
+    }
+
+    //returns {field: [(value,count)] }for use in sidebar(s)
+    public function getFilterTree($showZeroHits, $hideCat)
+    {
+        return $this->makeRequest("core.get_filter_tree", array($showZeroHits, $hideCat));
+    }
+
+    //Returns the number of free bytes at path
+    public function getFreeSpace($path)
+    {
+        return $this->makeRequest("core.get_free_space", array($path));
+    }
+
+    //Returns the libtorrent version.
+    public function getLibtorrentVersion()
+    {
+        return $this->makeRequest("core.get_libtorrent_version", array());
+    }
+
+    //Returns the active listen port
+    public function getListenPort()
+    {
+        return $this->makeRequest("core.get_listen_port", array());
+    }
+
+    //Returns the current number of connections
+    public function getNumConnections()
+    {
+        return $this->makeRequest("core.get_num_connections", array());
+    }
+
+    public function getPathSize($path)
+    {
+        return $this->makeRequest("core.get_path_size", array($path));
+    }
+
+    //Returns a list of torrent_ids in the session.
+    public function getSessionState()
+    {
+        return $this->makeRequest("core.get_session_state", array());
+    }
+
+    //Gets the session status values for ‘keys’, these keys are takingfrom libtorrent’s session status.
+    public function getSessionStatus($keys)
+    {
+        return $this->makeRequest("core.get_session_status", array($keys));
+    }
+
+    public function getTorrentStatus($torrentId, $keys, $diff)
+    {
+        return $this->makeRequest("core.get_torrent_status", array($torrentId, $keys, $diff));
+    }
+
+    //returns all torrents , optionally filtered by filter_dict.
+    public function getTorrentsStatus($filterDict, $keys, $diff)
+    {
+        return $this->makeRequest("core.get_torrents_status", array($filterDict, $keys, $diff));
+    }
+
+    public function glob($path)
+    {
+        return $this->makeRequest("core.glob", array($path));
+    }
+
+    public function moveStorage($torrentIds, $dest)
+    {
+        return $this->makeRequest("core.move_storage", array($torrentIds, $dest));
+    }
+
+    //Pause all torrents in the session
+    public function pauseAllTorrents()
+    {
+        return $this->makeRequest("core.pause_all_torrents", array());
+    }
+
+    public function pauseTorrent($torrentIds)
+    {
+        return $this->makeRequest("core.pause_torrent", array($torrentIds));
+    }
+
+    public function queueBottom($torrentIds)
+    {
+        return $this->makeRequest("core.queue_bottom", array($torrentIds));
+    }
+
+    public function queueDown($torrentIds)
+    {
+        return $this->makeRequest("core.queue_down", array($torrentIds));
+    }
+
+    public function queueTop($torrentIds)
+    {
+        return $this->makeRequest("core.queue_top", array($torrentIds));
+    }
+
+    public function queueUp($torrentIds)
+    {
+        return $this->makeRequest("core.queue_up", array($torrentIds));
+    }
+
+    //Removes a torrent from the session.
+    //Parameters:
+    //torrentId (string) – the torrentId of the torrent to remove
+    //removeData (boolean) – if True, remove the data associated with this torrent
+    public function removeTorrent($torrentId, $removeData)
+    {
+        return $this->makeRequest("core.remove_torrent", array($torrentId, $removeData));
+    }
+
+    //Rename files in torrent_id.  Since this is an asynchronous operation bylibtorrent, watch for the TorrentFileRenamedEvent to know when thefiles have been renamed.
+    //Parameters:
+    //torrentId (string) – the torrentId to rename files
+    //filenames (((index, filename), ...)) – a list of index, filename pairs
+    public function renameFiles($torrentId, $filenames)
+    {
+        return $this->makeRequest("core.rename_files", array($torrentId, $filenames));
+    }
+
+    //Renames the ‘folder’ to ‘new_folder’ in ‘torrent_id’.  Watch for theTorrentFolderRenamedEvent which is emitted when the folder has beenrenamed successfully.
+    //Parameters:
+    //torrentId (string) – the torrent to rename folder in
+    //folder (string) – the folder to rename
+    //newFolder (string) – the new folder name
+    public function renameFolder($torrentId, $folder, $newFolder)
+    {
+        return $this->makeRequest("core.rename_folder", array($torrentId, $folder, $newFolder));
+    }
+
+    //Rescans the plugin folders for new plugins
+    public function rescanPlugins()
+    {
+        return $this->makeRequest("core.rescan_plugins", array());
+    }
+
+    //Resume all torrents in the session
+    public function resumeAllTorrents()
+    {
+        return $this->makeRequest("core.resume_all_torrents", array());
+    }
+
+    public function resumeTorrent($torrentIds)
+    {
+        return $this->makeRequest("core.resume_torrent", array($torrentIds));
+    }
+
+    //Set the config with values from dictionary
+    public function setConfig($config)
+    {
+        return $this->makeRequest("core.set_config", array($config));
+    }
+
+    //Sets the auto managed flag for queueing purposes
+    public function setTorrentAutoManaged($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_auto_managed", array($torrentId, $value));
+    }
+
+    //Sets a torrents file priorities
+    public function setTorrentFilePriorities($torrentId, $priorities)
+    {
+        return $this->makeRequest("core.set_torrent_file_priorities", array($torrentId, $priorities));
+    }
+
+    //Sets a torrents max number of connections
+    public function setTorrentMaxConnections($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_max_connections", array($torrentId, $value));
+    }
+
+    //Sets a torrents max download speed
+    public function setTorrentMaxDownloadSpeed($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_max_download_speed", array($torrentId, $value));
+    }
+
+    //Sets a torrents max number of upload slots
+    public function setTorrentMaxUploadSlots($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_max_upload_slots", array($torrentId, $value));
+    }
+
+    //Sets a torrents max upload speed
+    public function setTorrentMaxUploadSpeed($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_max_upload_speed", array($torrentId, $value));
+    }
+
+    //Sets the torrent to be moved when completed
+    public function setTorrentMoveCompleted($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_move_completed", array($torrentId, $value));
+    }
+
+    //Sets the path for the torrent to be moved when completed
+    public function setTorrentMoveCompletedPath($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_move_completed_path", array($torrentId, $value));
+    }
+
+    //Sets the torrent options for torrent_ids
+    public function setTorrentOptions($torrentIds, $options)
+    {
+        return $this->makeRequest("core.set_torrent_options", array($torrentIds, $options));
+    }
+
+    //Sets a higher priority to the first and last pieces
+    public function setTorrentPrioritizeFirstLast($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_prioritize_first_last", array($torrentId, $value));
+    }
+
+    //Sets the torrent to be removed at ‘stop_ratio’
+    public function setTorrentRemoveAtRatio($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_remove_at_ratio", array($torrentId, $value));
+    }
+
+    //Sets the torrent to stop at ‘stop_ratio’
+    public function setTorrentStopAtRatio($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_stop_at_ratio", array($torrentId, $value));
+    }
+
+    //Sets the ratio when to stop a torrent if ‘stop_at_ratio’ is set
+    public function setTorrentStopRatio($torrentId, $value)
+    {
+        return $this->makeRequest("core.set_torrent_stop_ratio", array($torrentId, $value));
+    }
+
+    //Sets a torrents tracker list.  trackers will be [{“url”, “tier”}]
+    public function setTorrentTrackers($torrentId, $trackers)
+    {
+        return $this->makeRequest("core.set_torrent_trackers", array($torrentId, $trackers));
+    }
+
+    //Checks if the active port is open
+    public function testListenPort()
+    {
+        return $this->makeRequest("core.test_listen_port", array());
+    }
+
+    public function uploadPlugin($filename, $filedump)
+    {
+        return $this->makeRequest("core.upload_plugin", array($filename, $filedump));
+    }
+
+    //Returns a list of the exported methods.
+    public function getMethodList()
+    {
+        return $this->makeRequest("daemon.get_method_list", array());
+    }
+
+    //Returns some info from the daemon.
+    public function info()
+    {
+        return $this->makeRequest("daemon.info", array());
+    }
+
+    public function shutdown(...$params)
+    {
+        return $this->makeRequest("daemon.shutdown", $params);
+    }
+
+    /////////////////////////////
+    //
+    //web ui functions
+    //
+    //parsed from https://web.archive.org/web/20150423143401/http://deluge-torrent.org:80/docs/master/modules/ui/web/json_api.html#module-deluge.ui.web.json_api
+    //
+    /////////////////////////////
+
+    //Parameters:
+    //host (string) – the hostname
+    //port (int) – the port
+    //username (string) – the username to login as
+    //password (string) – the password to login with
+    public function addHost($host, $port, $username, $password)
+    {
+        return $this->makeRequest("web.add_host", array($host, $port, $username, $password));
+    }
+
+    //Usage
+    public function addTorrents($torrents)
+    {
+        return $this->makeRequest("web.add_torrents", array($torrents));
+    }
+
+    public function connect($hostId)
+    {
+        return $this->makeRequest("web.connect", array($hostId));
+    }
+
+    public function connected()
+    {
+        return $this->makeRequest("web.connected", array());
+    }
+
+    public function deregisterEventListener($event)
+    {
+        return $this->makeRequest("web.deregister_event_listener", array($event));
+    }
+
+    public function disconnect()
+    {
+        return $this->makeRequest("web.disconnect", array());
+    }
+
+    public function downloadTorrentFromUrl($url, $cookie)
+    {
+        return $this->makeRequest("web.download_torrent_from_url", array($url, $cookie));
+    }
+
+    /* in core
+    public function getConfig() {
+        return $this->makeRequest("web.get_config", array());
+    }*/
+
+    public function getEvents()
+    {
+        return $this->makeRequest("web.get_events", array());
+    }
+
+    public function getHost($hostId)
+    {
+        return $this->makeRequest("web.get_host", array($hostId));
+    }
+
+    public function getHostStatus($hostId)
+    {
+        return $this->makeRequest("web.get_host_status", array($hostId));
+    }
+
+    public function getHosts()
+    {
+        return $this->makeRequest("web.get_hosts", array());
+    }
+
+    public function getTorrentFiles($torrentId)
+    {
+        return $this->makeRequest("web.get_torrent_files", array($torrentId));
+    }
+
+    public function getTorrentInfo($filename)
+    {
+        return $this->makeRequest("web.get_torrent_info", array($filename));
+    }
+
+    public function registerEventListener($event)
+    {
+        return $this->makeRequest("web.register_event_listener", array($event));
+    }
+
+    public function removeHost($connectionId)
+    {
+        return $this->makeRequest("web.remove_host", array($connectionId));
+    }
+
+    /*in core
+    public function setConfig($config) {
+        return $this->makeRequest("web.set_config", array($config));
+    }*/
+
+    public function startDaemon($port)
+    {
+        return $this->makeRequest("web.start_daemon", array($port));
+    }
+
+    public function stopDaemon($hostId)
+    {
+        return $this->makeRequest("web.stop_daemon", array($hostId));
+    }
+
+    //Parameters:
+    //keys (list) – the information about the torrents to gather
+    //filterDict (dictionary) – the filters to apply when selecting torrents.
+    public function updateUi($keys, $filterDict)
+    {
+        return $this->makeRequest("web.update_ui", array($keys, $filterDict));
+    }
+
+    private function makeRequest($method, $params)
+    {
+        $post_data = array("id" => $this->request_id, "method" => $method, "params" => $params);
+        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($post_data));
+
+        $result = curl_exec($this->ch);
+
+        if ($result === false) {
+            throw new Exception("Could not log in due to curl error (no. " . curl_errno($this->ch) . "): " . curl_error($this->ch));
+        }
+
+        $http_code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
+
+        if ($http_code != 200) {
+            throw new Exception("Request for method $method returned http code $http_code");
+        }
+
+        $result = json_decode($result);
+        if (!is_null($result->error)) {
+            throw new Exception("Method request returned an error (no. " . $result->error->code . "): " . $result->error->message);
+        }
+
+        if ($result->id != $this->request_id) {
+            throw new Exception("Response id did not match request id");
+        }
+
+        $this->request_id++;
+        return $result->result;
+    }
 }
-
-?>

File diff ditekan karena terlalu besar
+ 319 - 197
api/functions/homepage-connect-functions.php


File diff ditekan karena terlalu besar
+ 470 - 466
api/functions/homepage-functions.php


+ 12 - 8
api/functions/log-functions.php

@@ -1,13 +1,14 @@
 <?php
 
-function writeLoginLog($username, $authType) {
-    if(file_exists($GLOBALS['organizrLoginLog'])) {
+function writeLoginLog($username, $authType)
+{
+    if (file_exists($GLOBALS['organizrLoginLog'])) {
         $getLog = str_replace("\r\ndate", "date", file_get_contents($GLOBALS['organizrLoginLog']));
         $gotLog = json_decode($getLog, true);
     }
     $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)));
     $logEntry = array('date' => date("Y-m-d H:i:s"), 'utc_date' => $GLOBALS['currentTime'], 'username' => $username, 'ip' => userIP(), 'auth_type' => $authType);
-    if(isset($gotLog)) {
+    if (isset($gotLog)) {
         array_push($gotLog["auth"], $logEntry);
         $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotLog));
     } else {
@@ -15,15 +16,16 @@ function writeLoginLog($username, $authType) {
     }
     file_put_contents($GLOBALS['organizrLoginLog'], $writeFailLog);
 };
-function writeLog($type='error', $message, $username=null) {
+function writeLog($type='error', $message, $username=null)
+{
     $username = ($username) ? $username : $GLOBALS['organizrUser']['username'];
-    if(file_exists($GLOBALS['organizrLog'])) {
+    if (file_exists($GLOBALS['organizrLog'])) {
         $getLog = str_replace("\r\ndate", "date", file_get_contents($GLOBALS['organizrLog']));
         $gotLog = json_decode($getLog, true);
     }
     $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)));
     $logEntry = array('date' => date("Y-m-d H:i:s"), 'utc_date' => $GLOBALS['currentTime'], 'type' => $type, 'username' => $username, 'ip' => userIP(), 'message' => $message);
-    if(isset($gotLog)) {
+    if (isset($gotLog)) {
         array_push($gotLog["log_items"], $logEntry);
         $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotLog));
     } else {
@@ -31,7 +33,8 @@ function writeLog($type='error', $message, $username=null) {
     }
     file_put_contents($GLOBALS['organizrLog'], $writeFailLog);
 };
-function getLog($type,$reverse=true){
+function getLog($type, $reverse=true)
+{
     switch ($type) {
         case 'login':
         case 'loginLog':
@@ -42,10 +45,11 @@ function getLog($type,$reverse=true){
         case 'organizrLog':
             $file = $GLOBALS['organizrLog'];
             $parent = 'log_items';
+            // no break
         default:
             break;
     }
-    if(!file_exists($file)){
+    if (!file_exists($file)) {
         return false;
     }
     $getLog = str_replace("\r\ndate", "date", file_get_contents($file));

+ 277 - 241
api/functions/normal-functions.php

@@ -1,105 +1,116 @@
 <?php
 // Print output all purrty
-function prettyPrint($v) {
-	$trace = debug_backtrace()[0];
-	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/>';
+function prettyPrint($v)
+{
+    $trace = debug_backtrace()[0];
+    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/>';
 }
 // Clean Directory string
-function cleanDirectory($path){
-	$path = str_replace(array('/', '\\'), '/', $path);
-    if(substr($path, -1) != '/'){
+function cleanDirectory($path)
+{
+    $path = str_replace(array('/', '\\'), '/', $path);
+    if (substr($path, -1) != '/') {
         $path = $path . '/';
     }
-    if($path[0] != '/' && $path[1] != ':'){
+    if ($path[0] != '/' && $path[1] != ':') {
         $path = '/' . $path;
     }
     return $path;
 }
 // Get Gravatar Email Image
-function gravatar($email = '') {
+function gravatar($email = '')
+{
     $email = md5(strtolower(trim($email)));
     $gravurl = "https://www.gravatar.com/avatar/$email?s=100&d=mm";
     return $gravurl;
 }
 // Cookie Custom Function
-function coookie($type, $name, $value = '', $days = -1, $http = true){
-	$badDomains = array('ddns.net','ddnsking.com','3utilities.com','bounceme.net','freedynamicdns.net','freedynamicdns.org','gotdns.ch','hopto.org','myddns.me','myftp.biz','myftp.org','myvnc.com','onthewifi.com','redirectme.net','serveblog.net','servecounterstrike.com','serveftp.com','servegame.com','servehalflife.com','servehttp.com','serveirc.com','serveminecraft.net','servemp3.com','servepics.com','servequake.com','sytes.net','viewdns.net','webhop.me','zapto.org');
-	if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https"){
-		$Secure = true;
- 	   	$HTTPOnly = true;
-	}elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
-		$Secure = true;
- 	   	$HTTPOnly = true;
-	} else {
-		$Secure = false;
- 	   	$HTTPOnly = false;
-   }
-   if(!$http){ $HTTPOnly = false; }
-	$Path = '/';
-	$Domain = $_SERVER['HTTP_HOST'];
-	$Port = strpos($Domain, ':');
-	if ($Port !== false)  $Domain = substr($Domain, 0, $Port);
-	$Port = strpos($Domain, ':');
-	$check = substr_count($Domain, '.');
-	if($check >= 3){
-		if(is_numeric($Domain[0])){
-			$Domain = '';
-		}else{
-			if(in_array(strtolower(explode('.',$Domain)[2].'.'.explode('.',$Domain)[3]), $badDomains)){
-				$Domain = '.'.explode('.',$Domain)[0].'.'.explode('.',$Domain)[1].'.'.explode('.',$Domain)[2].'.'.explode('.',$Domain)[3];
-			}else{
-				$Domain = '.'.explode('.',$Domain)[1].'.'.explode('.',$Domain)[2].'.'.explode('.',$Domain)[3];
-			}
-		}
-	}elseif($check == 2){
-		if(in_array(strtolower(explode('.',$Domain)[1].'.'.explode('.',$Domain)[2]), $badDomains)){
-			$Domain = '.'.explode('.',$Domain)[0].'.'.explode('.',$Domain)[1].'.'.explode('.',$Domain)[2];
-		}else{
-			$Domain = '.'.explode('.',$Domain)[1].'.'.explode('.',$Domain)[2];
-		}
-	}elseif($check == 1){
-		$Domain = '.' . $Domain;
-	}else{
-		$Domain = '';
-	}
-	if($type = 'set'){
-		$_COOKIE[$name] = $value;
-		header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
-							. (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + (86400 * $days)) . ' GMT')
-							. (empty($Path) ? '' : '; path=' . $Path)
-							. (empty($Domain) ? '' : '; domain=' . $Domain)
-							. (!$Secure ? '' : '; secure')
-							. (!$HTTPOnly ? '' : '; HttpOnly'), false);
-	}elseif($type = 'delete'){
-		unset($_COOKIE[$name]);
-		header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
-							. (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
-							. (empty($Path) ? '' : '; path=' . $Path)
-							. (empty($Domain) ? '' : '; domain=' . $Domain)
-							. (!$Secure ? '' : '; secure')
-							. (!$HTTPOnly ? '' : '; HttpOnly'), false);
-	}
+function coookie($type, $name, $value = '', $days = -1, $http = true)
+{
+    $badDomains = array('ddns.net','ddnsking.com','3utilities.com','bounceme.net','freedynamicdns.net','freedynamicdns.org','gotdns.ch','hopto.org','myddns.me','myftp.biz','myftp.org','myvnc.com','onthewifi.com','redirectme.net','serveblog.net','servecounterstrike.com','serveftp.com','servegame.com','servehalflife.com','servehttp.com','serveirc.com','serveminecraft.net','servemp3.com','servepics.com','servequake.com','sytes.net','viewdns.net','webhop.me','zapto.org');
+    if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
+        $Secure = true;
+        $HTTPOnly = true;
+    } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
+        $Secure = true;
+        $HTTPOnly = true;
+    } else {
+        $Secure = false;
+        $HTTPOnly = false;
+    }
+    if (!$http) {
+        $HTTPOnly = false;
+    }
+    $Path = '/';
+    $Domain = $_SERVER['HTTP_HOST'];
+    $Port = strpos($Domain, ':');
+    if ($Port !== false) {
+        $Domain = substr($Domain, 0, $Port);
+    }
+    $Port = strpos($Domain, ':');
+    $check = substr_count($Domain, '.');
+    if ($check >= 3) {
+        if (is_numeric($Domain[0])) {
+            $Domain = '';
+        } else {
+            if (in_array(strtolower(explode('.', $Domain)[2].'.'.explode('.', $Domain)[3]), $badDomains)) {
+                $Domain = '.'.explode('.', $Domain)[0].'.'.explode('.', $Domain)[1].'.'.explode('.', $Domain)[2].'.'.explode('.', $Domain)[3];
+            } else {
+                $Domain = '.'.explode('.', $Domain)[1].'.'.explode('.', $Domain)[2].'.'.explode('.', $Domain)[3];
+            }
+        }
+    } elseif ($check == 2) {
+        if (in_array(strtolower(explode('.', $Domain)[1].'.'.explode('.', $Domain)[2]), $badDomains)) {
+            $Domain = '.'.explode('.', $Domain)[0].'.'.explode('.', $Domain)[1].'.'.explode('.', $Domain)[2];
+        } else {
+            $Domain = '.'.explode('.', $Domain)[1].'.'.explode('.', $Domain)[2];
+        }
+    } elseif ($check == 1) {
+        $Domain = '.' . $Domain;
+    } else {
+        $Domain = '';
+    }
+    if ($type = 'set') {
+        $_COOKIE[$name] = $value;
+        header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
+                            . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + (86400 * $days)) . ' GMT')
+                            . (empty($Path) ? '' : '; path=' . $Path)
+                            . (empty($Domain) ? '' : '; domain=' . $Domain)
+                            . (!$Secure ? '' : '; secure')
+                            . (!$HTTPOnly ? '' : '; HttpOnly'), false);
+    } elseif ($type = 'delete') {
+        unset($_COOKIE[$name]);
+        header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
+                            . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
+                            . (empty($Path) ? '' : '; path=' . $Path)
+                            . (empty($Domain) ? '' : '; domain=' . $Domain)
+                            . (!$Secure ? '' : '; secure')
+                            . (!$HTTPOnly ? '' : '; HttpOnly'), false);
+    }
 }
-function getOS(){
-	if(PHP_SHLIB_SUFFIX == "dll"){
-		return "win";
-	}else{
-		return "*nix";
-	}
+function getOS()
+{
+    if (PHP_SHLIB_SUFFIX == "dll") {
+        return "win";
+    } else {
+        return "*nix";
+    }
 }
-if(!function_exists('getallheaders')){
-    function getallheaders(){
-        $headers = array ();
-        foreach ($_SERVER as $name => $value){
-            if (substr($name, 0, 5) == 'HTTP_'){
+if (!function_exists('getallheaders')) {
+    function getallheaders()
+    {
+        $headers = array();
+        foreach ($_SERVER as $name => $value) {
+            if (substr($name, 0, 5) == 'HTTP_') {
                 $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
             }
         }
         return $headers;
     }
 }
-function random_ascii_string($length){
-	$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+function random_ascii_string($length)
+{
+    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
     $charactersLength = strlen($characters);
     $randomString = '';
     for ($i = 0; $i < $length; $i++) {
@@ -108,81 +119,91 @@ function random_ascii_string($length){
     return $randomString;
 }
 // Generate Random string
-function randString($length = 10, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
-	$tmp = '';
-	for ($i = 0; $i < $length; $i++) {
-		$tmp .= substr(str_shuffle($chars), 0, 1);
-	}
+function randString($length = 10, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
+{
+    $tmp = '';
+    for ($i = 0; $i < $length; $i++) {
+        $tmp .= substr(str_shuffle($chars), 0, 1);
+    }
     return $tmp;
 }
-function encrypt($password, $key = null) {
+function encrypt($password, $key = null)
+{
     $key = (isset($GLOBALS['organizrHash'])) ? $GLOBALS['organizrHash'] : $key;
-    return openssl_encrypt($password, 'AES-256-CBC', $key, 0, fillString($key,16));
+    return openssl_encrypt($password, 'AES-256-CBC', $key, 0, fillString($key, 16));
 }
-function decrypt($password, $key = null) {
-	if(empty($password)){ return ''; }
+function decrypt($password, $key = null)
+{
+    if (empty($password)) {
+        return '';
+    }
     $key = (isset($GLOBALS['organizrHash'])) ? $GLOBALS['organizrHash'] : $key;
-    return openssl_decrypt($password, 'AES-256-CBC', $key, 0, fillString($key,16));
+    return openssl_decrypt($password, 'AES-256-CBC', $key, 0, fillString($key, 16));
 }
-function fillString($string, $length){
+function fillString($string, $length)
+{
     $filler = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*';
-    if(strlen($string) < $length){
+    if (strlen($string) < $length) {
         $diff = $length - strlen($string);
-        $filler = substr($filler,0,$diff);
+        $filler = substr($filler, 0, $diff);
         return $string.$filler;
-    }elseif(strlen($string) > $length){
-        return substr($string,0,$length);
-    }else{
+    } elseif (strlen($string) > $length) {
+        return substr($string, 0, $length);
+    } else {
         return $string;
     }
     return $diff;
 }
-function userIP() {
-    if (isset($_SERVER['HTTP_CLIENT_IP']))
+function userIP()
+{
+    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
         $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
-    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
+    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
         $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
-    else if(isset($_SERVER['HTTP_X_FORWARDED']))
+    } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
         $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
-    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
+    } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
         $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
-    else if(isset($_SERVER['HTTP_FORWARDED']))
+    } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
         $ipaddress = $_SERVER['HTTP_FORWARDED'];
-    else if(isset($_SERVER['REMOTE_ADDR']))
+    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
         $ipaddress = $_SERVER['REMOTE_ADDR'];
-    else
+    } else {
         $ipaddress = 'UNKNOWN';
+    }
     if (strpos($ipaddress, ',') !== false) {
         list($first, $last) = explode(",", $ipaddress);
         return $first;
-    }else{
+    } else {
         return $ipaddress;
     }
-
 }
-function arrayIP($string){
+function arrayIP($string)
+{
     if (strpos($string, ',') !== false) {
         $result = explode(",", $string);
-    }else{
+    } else {
         $result = array($string);
     }
-    foreach($result as &$ip){
+    foreach ($result as &$ip) {
         $ip = is_numeric(substr($ip, 0, 1)) ? $ip : gethostbyname($ip);
     }
     return $result;
 }
-function getCert(){
-	$url = 'http://curl.haxx.se/ca/cacert.pem';
-	$file = __DIR__.DIRECTORY_SEPARATOR.'cert'.DIRECTORY_SEPARATOR.'cacert.pem';
-	$directory = __DIR__.DIRECTORY_SEPARATOR.'cert'.DIRECTORY_SEPARATOR;
-	if(!file_exists($file)){
-    	file_put_contents( $file, fopen($url, 'r'));
-	}elseif (file_exists($file) && time() - 2592000 > filemtime($file)) {
-		file_put_contents( $file, fopen($url, 'r'));
-	}
-	return $file;
+function getCert()
+{
+    $url = 'http://curl.haxx.se/ca/cacert.pem';
+    $file = __DIR__.DIRECTORY_SEPARATOR.'cert'.DIRECTORY_SEPARATOR.'cacert.pem';
+    $directory = __DIR__.DIRECTORY_SEPARATOR.'cert'.DIRECTORY_SEPARATOR;
+    if (!file_exists($file)) {
+        file_put_contents($file, fopen($url, 'r'));
+    } elseif (file_exists($file) && time() - 2592000 > filemtime($file)) {
+        file_put_contents($file, fopen($url, 'r'));
+    }
+    return $file;
 }
-function curl($curl, $url, $headers=array(), $data=array()){
+function curl($curl, $url, $headers=array(), $data=array())
+{
     // Initiate cURL
     $curlReq = curl_init($url);
     if (in_array(trim(strtoupper($curl)), ["GET","POST","PUT","DELETE"])) {
@@ -193,7 +214,7 @@ function curl($curl, $url, $headers=array(), $data=array()){
     curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($curlReq, CURLOPT_CAINFO, getCert());
     curl_setopt($curlReq, CURLOPT_CONNECTTIMEOUT, 5);
-    if(localURL($url)){
+    if (localURL($url)) {
         curl_setopt($curlReq, CURLOPT_SSL_VERIFYHOST, 0);
         curl_setopt($curlReq, CURLOPT_SSL_VERIFYPEER, 0);
     }
@@ -225,143 +246,158 @@ function curl($curl, $url, $headers=array(), $data=array()){
     // Return
     return array('content'=>$result, 'http_code'=>$httpcode);
 }
-function getHeaders($url){
-	$ch = curl_init($url);
-	curl_setopt( $ch, CURLOPT_NOBODY, true );
-	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
-	curl_setopt( $ch, CURLOPT_HEADER, false );
-	curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
-	curl_setopt( $ch, CURLOPT_MAXREDIRS, 3 );
-	curl_setopt( $ch, CURLOPT_CAINFO, getCert());
-	if(localURL($url)){
-		curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
-		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
-	}
-	curl_exec( $ch );
-	$headers = curl_getinfo( $ch );
-	curl_close( $ch );
+function getHeaders($url)
+{
+    $ch = curl_init($url);
+    curl_setopt($ch, CURLOPT_NOBODY, true);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
+    curl_setopt($ch, CURLOPT_HEADER, false);
+    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+    curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
+    curl_setopt($ch, CURLOPT_CAINFO, getCert());
+    if (localURL($url)) {
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
+    }
+    curl_exec($ch);
+    $headers = curl_getinfo($ch);
+    curl_close($ch);
 
-	return $headers;
+    return $headers;
 }
-function download($url, $path){
-	ini_set('max_execution_time',0);
-	set_time_limit(0);
-	$ch = curl_init($url);
-	curl_setopt($ch, CURLOPT_HEADER, 1);
-	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-	curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
-	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
-	curl_setopt( $ch, CURLOPT_CAINFO, getCert());
-	if(localURL($url)){
-		curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
-		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
-	}
-	$raw_file_data = curl_exec($ch);
-	curl_close($ch);
-	file_put_contents($path, $raw_file_data);
-	return (filesize($path) > 0)? true : false;
+function download($url, $path)
+{
+    ini_set('max_execution_time', 0);
+    set_time_limit(0);
+    $ch = curl_init($url);
+    curl_setopt($ch, CURLOPT_HEADER, 1);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
+    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
+    curl_setopt($ch, CURLOPT_CAINFO, getCert());
+    if (localURL($url)) {
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
+    }
+    $raw_file_data = curl_exec($ch);
+    curl_close($ch);
+    file_put_contents($path, $raw_file_data);
+    return (filesize($path) > 0)? true : false;
 }
-function localURL($url){
-	if (strpos($url, 'https') !== false) {
-		preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $url, $result);
-		$result = (!empty($result) ? true : false);
-		return $result;
-	}
+function localURL($url)
+{
+    if (strpos($url, 'https') !== false) {
+        preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $url, $result);
+        $result = (!empty($result) ? true : false);
+        return $result;
+    }
 }
-function array_filter_key(array $array, $callback){
-	$matchedKeys = array_filter(array_keys($array), $callback);
-	return array_intersect_key($array, array_flip($matchedKeys));
+function array_filter_key(array $array, $callback)
+{
+    $matchedKeys = array_filter(array_keys($array), $callback);
+    return array_intersect_key($array, array_flip($matchedKeys));
 }
 // Qualify URL
-function qualifyURL($url, $return=false) {
-	//local address?
-	if(substr($url, 0,1) == "/"){
-		if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
-			$protocol = "https://";
-		} else {
-			$protocol = "http://";
-		}
-		$url = $protocol.getServer().$url;
-	}
-	// Get Digest
-	$digest = parse_url($url);
-	// http/https
-	if (!isset($digest['scheme'])) {
-		if (isset($digest['port']) && in_array($digest['port'], array(80,8080,8096,32400,7878,8989,8182,8081,6789))) {
-			$scheme = 'http';
-		} else {
-			$scheme = 'https';
-		}
-	} else {
-		$scheme = $digest['scheme'];
-	}
-	// Host
-	$host = (isset($digest['host'])?$digest['host']:'');
-	// Port
-	$port = (isset($digest['port'])?':'.$digest['port']:'');
-	// Path
-	$path = (isset($digest['path']) && $digest['path'] !== '/'?$digest['path']:'');
-	// Output
-	$array = array(
-		'scheme' => $scheme,
-		'host' => $host,
-		'port' => $port,
-		'path' => $path
-	);
-	return ($return) ? $array : $scheme.'://'.$host.$port.$path;
+function qualifyURL($url, $return=false)
+{
+    //local address?
+    if (substr($url, 0, 1) == "/") {
+        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
+            $protocol = "https://";
+        } else {
+            $protocol = "http://";
+        }
+        $url = $protocol.getServer().$url;
+    }
+    // Get Digest
+    $digest = parse_url($url);
+    // http/https
+    if (!isset($digest['scheme'])) {
+        if (isset($digest['port']) && in_array($digest['port'], array(80,8080,8096,32400,7878,8989,8182,8081,6789))) {
+            $scheme = 'http';
+        } else {
+            $scheme = 'https';
+        }
+    } else {
+        $scheme = $digest['scheme'];
+    }
+    // Host
+    $host = (isset($digest['host'])?$digest['host']:'');
+    // Port
+    $port = (isset($digest['port'])?':'.$digest['port']:'');
+    // Path
+    $path = (isset($digest['path']) && $digest['path'] !== '/'?$digest['path']:'');
+    // Output
+    $array = array(
+        'scheme' => $scheme,
+        'host' => $host,
+        'port' => $port,
+        'path' => $path
+    );
+    return ($return) ? $array : $scheme.'://'.$host.$port.$path;
 }
-function getServerPath($over=false) {
-	if($over){
-		if($GLOBALS['PHPMAILER-domain'] !== ''){
-			return $GLOBALS['PHPMAILER-domain'];
-		}
-	}
-	if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https"){
-		$protocol = "https://";
-	}elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
+function getServerPath($over=false)
+{
+    if ($over) {
+        if ($GLOBALS['PHPMAILER-domain'] !== '') {
+            return $GLOBALS['PHPMAILER-domain'];
+        }
+    }
+    if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
+        $protocol = "https://";
+    } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
         $protocol = "https://";
     } else {
         $protocol = "http://";
     }
-	$domain = '';
-    if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], '.') !== false){
+    $domain = '';
+    if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], '.') !== false) {
         $domain = $_SERVER['SERVER_NAME'];
-	}elseif(isset($_SERVER['HTTP_HOST'])){
-		if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
-			$domain = explode(':', $_SERVER['HTTP_HOST'])[0];
-			$port = explode(':', $_SERVER['HTTP_HOST'])[1];
-			if ($port == "80" || $port == "443"){
-				$domain = $domain;
-			}else{
-				$domain = $_SERVER['HTTP_HOST'];
-			}
-		}else{
-        	$domain = $_SERVER['HTTP_HOST'];
-		}
-	}
-	$url = $protocol . $domain . str_replace("\\", "/", dirname($_SERVER['REQUEST_URI']));
-	if (strpos($url, '/api') !== false) {
-		$url = explode('/api', $url);
-		return $url[0].'/';
-	}else{
-		return $url;
-	}
+    } elseif (isset($_SERVER['HTTP_HOST'])) {
+        if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
+            $domain = explode(':', $_SERVER['HTTP_HOST'])[0];
+            $port = explode(':', $_SERVER['HTTP_HOST'])[1];
+            if ($port == "80" || $port == "443") {
+                $domain = $domain;
+            } else {
+                $domain = $_SERVER['HTTP_HOST'];
+            }
+        } else {
+            $domain = $_SERVER['HTTP_HOST'];
+        }
+    }
+    $url = $protocol . $domain . str_replace("\\", "/", dirname($_SERVER['REQUEST_URI']));
+    if (strpos($url, '/api') !== false) {
+        $url = explode('/api', $url);
+        return $url[0].'/';
+    } else {
+        return $url;
+    }
 }
-function get_browser_name() {
+function get_browser_name()
+{
     $user_agent = $_SERVER['HTTP_USER_AGENT'];
-    if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
-    elseif (strpos($user_agent, 'Edge')) return 'Edge';
-    elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
-    elseif (strpos($user_agent, 'Safari')) return 'Safari';
-    elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
-    elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
+    if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) {
+        return 'Opera';
+    } elseif (strpos($user_agent, 'Edge')) {
+        return 'Edge';
+    } elseif (strpos($user_agent, 'Chrome')) {
+        return 'Chrome';
+    } elseif (strpos($user_agent, 'Safari')) {
+        return 'Safari';
+    } elseif (strpos($user_agent, 'Firefox')) {
+        return 'Firefox';
+    } elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) {
+        return 'Internet Explorer';
+    }
     return 'Other';
 }
-function getServer($over=false){
-	if($over){
-		if($GLOBALS['PHPMAILER-domain'] !== ''){
-			return $GLOBALS['PHPMAILER-domain'];
-		}
-	}
+function getServer($over=false)
+{
+    if ($over) {
+        if ($GLOBALS['PHPMAILER-domain'] !== '') {
+            return $GLOBALS['PHPMAILER-domain'];
+        }
+    }
     return isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"];
 }

+ 66 - 63
api/functions/sso-functions.php

@@ -1,68 +1,71 @@
 <?php
 
-function ssoCheck($username, $password, $token=null){
-	$test = '';
-	if($GLOBALS['ssoPlex'] && $token){
-		coookie('set','mpt',$token,7);
-	}
-	if($GLOBALS['ssoOmbi']){
-		$ombiToken = getOmbiToken($username, $password);
-		if($ombiToken){
-			coookie('set','Auth',$ombiToken,7, false);
-		}
-	}
-	if($GLOBALS['ssoTautulli']){
-		$tautulliToken = getTautulliToken($username, $password);
-		if($tautulliToken){
-			coookie('set','tautulli_token_'.$tautulliToken['uuid'],$tautulliToken['token'],7, false);
-		}
-	}
-	return true;
+function ssoCheck($username, $password, $token=null)
+{
+    $test = '';
+    if ($GLOBALS['ssoPlex'] && $token) {
+        coookie('set', 'mpt', $token, 7);
+    }
+    if ($GLOBALS['ssoOmbi']) {
+        $ombiToken = getOmbiToken($username, $password);
+        if ($ombiToken) {
+            coookie('set', 'Auth', $ombiToken, 7, false);
+        }
+    }
+    if ($GLOBALS['ssoTautulli']) {
+        $tautulliToken = getTautulliToken($username, $password);
+        if ($tautulliToken) {
+            coookie('set', 'tautulli_token_'.$tautulliToken['uuid'], $tautulliToken['token'], 7, false);
+        }
+    }
+    return true;
 }
-function getOmbiToken($username, $password){
-	try{
-		$url = $GLOBALS['ombiURL'].'/api/v1/Token';
-		$token = null;
-		$headers = array(
-			"Accept" => "application/json",
-			"Content-Type" => "application/json"
-		);
-		$data = array(
-			"username" => $username,
-			"password" => $password,
-			"rememberMe" => "true",
-		);
-		$options = (localURL($url)) ? array('verify' => false ) : array();
-		$response = Requests::post($url, $headers, json_encode($data), $options);
-		if($response->success){
-			$token = json_decode($response->body, true)['access_token'];
-		}
-		return ($token) ? $token : false;
-	}catch( Requests_Exception $e ) {
-		writeLog('success', 'Ombi Token Function - Error: '.$e->getMessage(), $username);
-	};
+function getOmbiToken($username, $password)
+{
+    try {
+        $url = $GLOBALS['ombiURL'].'/api/v1/Token';
+        $token = null;
+        $headers = array(
+            "Accept" => "application/json",
+            "Content-Type" => "application/json"
+        );
+        $data = array(
+            "username" => $username,
+            "password" => $password,
+            "rememberMe" => "true",
+        );
+        $options = (localURL($url)) ? array('verify' => false ) : array();
+        $response = Requests::post($url, $headers, json_encode($data), $options);
+        if ($response->success) {
+            $token = json_decode($response->body, true)['access_token'];
+        }
+        return ($token) ? $token : false;
+    } catch (Requests_Exception $e) {
+        writeLog('success', 'Ombi Token Function - Error: '.$e->getMessage(), $username);
+    };
 }
-function getTautulliToken($username, $password){
-	try{
-		$url = $GLOBALS['tautulliURL'].'/auth/signin';
-		$token = null;
-		$headers = array(
-			"Accept" => "application/json",
-			"Content-Type" => "application/x-www-form-urlencoded"
-		);
-		$data = array(
-			"username" => $username,
-			"password" => $password,
-			"remember_me" => 1,
-		);
-		$options = (localURL($url)) ? array('verify' => false ) : array();
-		$response = Requests::post($url, $headers, $data, $options);
-		if($response->success){
-			$token['token'] = json_decode($response->body, true)['token'];
-			$token['uuid'] = json_decode($response->body, true)['uuid'];
-		}
-		return ($token) ? $token : false;
-	}catch( Requests_Exception $e ) {
-		writeLog('success', 'Tautulli Token Function - Error: '.$e->getMessage(), $username);
-	};
+function getTautulliToken($username, $password)
+{
+    try {
+        $url = $GLOBALS['tautulliURL'].'/auth/signin';
+        $token = null;
+        $headers = array(
+            "Accept" => "application/json",
+            "Content-Type" => "application/x-www-form-urlencoded"
+        );
+        $data = array(
+            "username" => $username,
+            "password" => $password,
+            "remember_me" => 1,
+        );
+        $options = (localURL($url)) ? array('verify' => false ) : array();
+        $response = Requests::post($url, $headers, $data, $options);
+        if ($response->success) {
+            $token['token'] = json_decode($response->body, true)['token'];
+            $token['uuid'] = json_decode($response->body, true)['uuid'];
+        }
+        return ($token) ? $token : false;
+    } catch (Requests_Exception $e) {
+        writeLog('success', 'Tautulli Token Function - Error: '.$e->getMessage(), $username);
+    };
 }

+ 20 - 19
api/functions/static-globals.php

@@ -5,25 +5,26 @@
 $GLOBALS['installedVersion'] = '2.0.0-alpha.815';
 // ===================================
 // Set GLOBALS from config file
-$GLOBALS['userConfigPath'] = dirname(__DIR__,1).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php';
-$GLOBALS['defaultConfigPath'] = dirname(__DIR__,1).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'default.php';
+$GLOBALS['userConfigPath'] = dirname(__DIR__, 1).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php';
+$GLOBALS['defaultConfigPath'] = dirname(__DIR__, 1).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'default.php';
 $GLOBALS['currentTime'] = gmdate("Y-m-d\TH:i:s\Z");
 // Quick function for plugins
-function pluginFiles($type){
-	$files = '';
-	switch ($type) {
-		case 'js':
-			foreach (glob(dirname(__DIR__,1).DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . "*.js") as $filename){
-				$files .= '<script src="api/plugins/js/'.basename($filename).'?v='.$GLOBALS['installedVersion'].'" defer="true"></script>';
-			}
-			break;
-		case 'css':
-			foreach (glob(dirname(__DIR__,1).DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . "*.js") as $filename){
-				$files .= '<link href="api/plugins/css/'.basename($filename).$GLOBALS['installedVersion'].'" rel="stylesheet">';
-			}
-			break;
-		default:
-			break;
-	}
-	return $files;
+function pluginFiles($type)
+{
+    $files = '';
+    switch ($type) {
+        case 'js':
+            foreach (glob(dirname(__DIR__, 1).DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . "*.js") as $filename) {
+                $files .= '<script src="api/plugins/js/'.basename($filename).'?v='.$GLOBALS['installedVersion'].'" defer="true"></script>';
+            }
+            break;
+        case 'css':
+            foreach (glob(dirname(__DIR__, 1).DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . "*.js") as $filename) {
+                $files .= '<link href="api/plugins/css/'.basename($filename).$GLOBALS['installedVersion'].'" rel="stylesheet">';
+            }
+            break;
+        default:
+            break;
+    }
+    return $files;
 }

+ 64 - 56
api/functions/token-functions.php

@@ -1,12 +1,13 @@
 <?php
 
-function jwtParse($token){
+function jwtParse($token)
+{
     try {
         $result = array();
         $result['valid'] = false;
         // Check Token with JWT
         // Set key
-        if(!isset($GLOBALS['organizrHash'])){
+        if (!isset($GLOBALS['organizrHash'])) {
             return null;
         }
         $key = $GLOBALS['organizrHash'];
@@ -16,11 +17,11 @@ function jwtParse($token){
         $jwttoken->getHeaders(); // Retrieves the token header
         $jwttoken->getClaims(); // Retrieves the token claims
         // Start Validation
-        if($jwttoken->verify($signer, $key)){
+        if ($jwttoken->verify($signer, $key)) {
             $data = new Lcobucci\JWT\ValidationData(); // It will use the current time to validate (iat, nbf and exp)
             $data->setIssuer('Organizr');
             $data->setAudience('Organizr');
-            if($jwttoken->validate($data)){
+            if ($jwttoken->validate($data)) {
                 $result['valid'] = true;
                 $result['username'] = $jwttoken->getClaim('username');
                 $result['group'] = $jwttoken->getClaim('group');
@@ -33,63 +34,69 @@ function jwtParse($token){
                 $result['token'] = $jwttoken->getClaim('exp');
             }
         }
-        if($result['valid'] == true){ return $result; }else{ return false; }
-    } catch(\RunException $e) {
+        if ($result['valid'] == true) {
+            return $result;
+        } else {
+            return false;
+        }
+    } catch (\RunException $e) {
         return false;
-    } catch(\OutOfBoundsException $e) {
+    } catch (\OutOfBoundsException $e) {
         return false;
-    } catch(\RunTimeException $e) {
+    } catch (\RunTimeException $e) {
         return false;
-    } catch(\InvalidArgumentException $e) {
+    } catch (\InvalidArgumentException $e) {
         return false;
     }
 }
-function createToken($username,$email,$image,$group,$groupID,$key,$days = 1){
-	//Quick get user ID
-	try {
-    	$database = new Dibi\Connection([
-    		'driver' => 'sqlite3',
-    		'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
-    	]);
-        $result = $database->fetch('SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE',$username,$email);
-	    // Create JWT
-	    // Set key
-	    // SHA256 Encryption
-	    $signer = new Lcobucci\JWT\Signer\Hmac\Sha256();
-	    // Start Builder
-	    $jwttoken = (new Lcobucci\JWT\Builder())->setIssuer('Organizr') // Configures the issuer (iss claim)
-	                                ->setAudience('Organizr') // Configures the audience (aud claim)
-	                                ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
-	                                ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
-	                                ->setExpiration(time() + (86400 * $days)) // Configures the expiration time of the token (exp claim)
-	                                ->set('username', $result['username']) // Configures a new claim, called "username"
-	                                ->set('group', $result['group']) // Configures a new claim, called "group"
-	                                ->set('groupID', $result['group_id']) // Configures a new claim, called "groupID"
-	                                ->set('email', $result['email']) // Configures a new claim, called "email"
-									->set('image', $result['image']) // Configures a new claim, called "image"
-	                                ->set('userID', $result['id']) // Configures a new claim, called "image"
-	                                ->sign($signer, $key) // creates a signature using "testing" as key
-	                                ->getToken(); // Retrieves the generated token
-	    $jwttoken->getHeaders(); // Retrieves the token headers
-	    $jwttoken->getClaims(); // Retrieves the token claims
-	    coookie('set','organizrToken',$jwttoken,$days);
-	    return $jwttoken;
-	} catch (Dibi\Exception $e) {
-		return false;
-	}
+function createToken($username, $email, $image, $group, $groupID, $key, $days = 1)
+{
+    //Quick get user ID
+    try {
+        $database = new Dibi\Connection([
+            'driver' => 'sqlite3',
+            'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
+        ]);
+        $result = $database->fetch('SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE', $username, $email);
+        // Create JWT
+        // Set key
+        // SHA256 Encryption
+        $signer = new Lcobucci\JWT\Signer\Hmac\Sha256();
+        // Start Builder
+        $jwttoken = (new Lcobucci\JWT\Builder())->setIssuer('Organizr') // Configures the issuer (iss claim)
+                                    ->setAudience('Organizr') // Configures the audience (aud claim)
+                                    ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
+                                    ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
+                                    ->setExpiration(time() + (86400 * $days)) // Configures the expiration time of the token (exp claim)
+                                    ->set('username', $result['username']) // Configures a new claim, called "username"
+                                    ->set('group', $result['group']) // Configures a new claim, called "group"
+                                    ->set('groupID', $result['group_id']) // Configures a new claim, called "groupID"
+                                    ->set('email', $result['email']) // Configures a new claim, called "email"
+                                    ->set('image', $result['image']) // Configures a new claim, called "image"
+                                    ->set('userID', $result['id']) // Configures a new claim, called "image"
+                                    ->sign($signer, $key) // creates a signature using "testing" as key
+                                    ->getToken(); // Retrieves the generated token
+        $jwttoken->getHeaders(); // Retrieves the token headers
+        $jwttoken->getClaims(); // Retrieves the token claims
+        coookie('set', 'organizrToken', $jwttoken, $days);
+        return $jwttoken;
+    } catch (Dibi\Exception $e) {
+        return false;
+    }
 }
-function validateToken($token,$global=false){
+function validateToken($token, $global=false)
+{
     // Validate script
     $userInfo = jwtParse($token);
     $validated = $userInfo ? true : false;
-    if($validated == true){
-        if($global == true){
+    if ($validated == true) {
+        if ($global == true) {
             try {
-            	$database = new Dibi\Connection([
-            		'driver' => 'sqlite3',
-            		'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
-            	]);
-                $result = $database->fetch('SELECT * FROM users WHERE id = ?',$userInfo['userID']);
+                $database = new Dibi\Connection([
+                    'driver' => 'sqlite3',
+                    'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
+                ]);
+                $result = $database->fetch('SELECT * FROM users WHERE id = ?', $userInfo['userID']);
                 $GLOBALS['organizrUser'] = array(
                     "token"=>$token,
                     "tokenDate"=>$userInfo['tokenDate'],
@@ -106,17 +113,18 @@ function validateToken($token,$global=false){
                 $GLOBALS['organizrUser'] = false;
             }
         }
-    }else{
+    } else {
         // Delete cookie & reload page
-        coookie('delete','organizrToken');
+        coookie('delete', 'organizrToken');
         $GLOBALS['organizrUser'] = false;
     }
 }
-function getOrganizrUserToken(){
-    if(isset($_COOKIE['organizrToken'])){
+function getOrganizrUserToken()
+{
+    if (isset($_COOKIE['organizrToken'])) {
         // Get token form cookie and validate
-        validateToken($_COOKIE['organizrToken'],true);
-    }else{
+        validateToken($_COOKIE['organizrToken'], true);
+    } else {
         $GLOBALS['organizrUser'] = array(
             "token"=>null,
             "tokenDate"=>null,

+ 132 - 120
api/functions/update-functions.php

@@ -1,134 +1,146 @@
 <?php
 
-
 // Upgrade the installation
-function upgradeInstall($branch = 'v2-master', $stage) {
-	ini_set('max_execution_time',0);
-	set_time_limit(0);
+function upgradeInstall($branch = 'v2-master', $stage)
+{
+    ini_set('max_execution_time', 0);
+    set_time_limit(0);
     $url = 'https://github.com/causefx/Organizr/archive/'.$branch.'.zip';
     $file = "upgrade.zip";
-    $source = dirname(__DIR__,2).DIRECTORY_SEPARATOR.'upgrade'.DIRECTORY_SEPARATOR.'Organizr-'.str_replace('v2','2',$branch).DIRECTORY_SEPARATOR;
-    $cleanup = dirname(__DIR__,2) .DIRECTORY_SEPARATOR."upgrade".DIRECTORY_SEPARATOR;
-    $destination = dirname(__DIR__,2).DIRECTORY_SEPARATOR;
-	switch ($stage) {
-		case '1':
-			writeLog('success', 'Update Function -  Started Upgrade Process', $GLOBALS['organizrUser']['username']);
-			if(downloadFile($url, $file)){
-				writeLog('success', 'Update Function -  Downloaded Update File for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
-				return true;
-			}else{
-				writeLog('error', 'Update Function -  Downloaded Update File Failed  for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
-				return false;
-			}
-			break;
-		case '2':
-			if(unzipFile($file)){
-				writeLog('success', 'Update Function -  Unzipped Update File for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
-				return true;
-			}else{
-				writeLog('error', 'Update Function -  Unzip Failed for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
-				return false;
-			}
-			break;
-		case '3':
-			if(rcopy($source, $destination)){
-				writeLog('success', 'Update Function -  Overwrited Files using Updated Files from Branch: '.$branch, $GLOBALS['organizrUser']['username']);
-				return true;
-			}else{
-				writeLog('error', 'Update Function -  Overwrite Failed for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
-				return false;
-			}
-			break;
-		case '4':
-			if(rrmdir($cleanup)){
-				writeLog('success', 'Update Function -  Deleted Update Files from Branch: '.$branch, $GLOBALS['organizrUser']['username']);
-				writeLog('success', 'Update Function -  Update Completed', $GLOBALS['organizrUser']['username']);
-				return true;
-			}else{
-				writeLog('error', 'Update Function -  Removal of Update Files Failed for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
-				return false;
-			}
-			break;
-		default:
-			return false;
-			break;
-	}
-	return false;
+    $source = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'upgrade'.DIRECTORY_SEPARATOR.'Organizr-'.str_replace('v2', '2', $branch).DIRECTORY_SEPARATOR;
+    $cleanup = dirname(__DIR__, 2) .DIRECTORY_SEPARATOR."upgrade".DIRECTORY_SEPARATOR;
+    $destination = dirname(__DIR__, 2).DIRECTORY_SEPARATOR;
+    switch ($stage) {
+        case '1':
+            writeLog('success', 'Update Function -  Started Upgrade Process', $GLOBALS['organizrUser']['username']);
+            if (downloadFile($url, $file)) {
+                writeLog('success', 'Update Function -  Downloaded Update File for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
+                return true;
+            } else {
+                writeLog('error', 'Update Function -  Downloaded Update File Failed  for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
+                return false;
+            }
+            break;
+        case '2':
+            if (unzipFile($file)) {
+                writeLog('success', 'Update Function -  Unzipped Update File for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
+                return true;
+            } else {
+                writeLog('error', 'Update Function -  Unzip Failed for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
+                return false;
+            }
+            break;
+        case '3':
+            if (rcopy($source, $destination)) {
+                writeLog('success', 'Update Function -  Overwrited Files using Updated Files from Branch: '.$branch, $GLOBALS['organizrUser']['username']);
+                return true;
+            } else {
+                writeLog('error', 'Update Function -  Overwrite Failed for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
+                return false;
+            }
+            break;
+        case '4':
+            if (rrmdir($cleanup)) {
+                writeLog('success', 'Update Function -  Deleted Update Files from Branch: '.$branch, $GLOBALS['organizrUser']['username']);
+                writeLog('success', 'Update Function -  Update Completed', $GLOBALS['organizrUser']['username']);
+                return true;
+            } else {
+                writeLog('error', 'Update Function -  Removal of Update Files Failed for Branch: '.$branch, $GLOBALS['organizrUser']['username']);
+                return false;
+            }
+            break;
+        default:
+            return false;
+            break;
+    }
+    return false;
 }
-function downloadFile($url, $path){
-	ini_set('max_execution_time',0);
-	set_time_limit(0);
-	$folderPath = dirname(__DIR__,2).DIRECTORY_SEPARATOR."upgrade".DIRECTORY_SEPARATOR;
-	if(!mkdir($folderPath)){
-		//writeLog("error", "organizr could not create upgrade folder");
-	}
-	$newfname = $folderPath . $path;
-	$file = fopen ($url, 'rb');
-	if ($file) {
-		$newf = fopen ($newfname, 'wb');
-		if ($newf) {
-			while(!feof($file)) {
-				fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
-			}
-		}
-	}else{
-		//writeLog("error", "organizr could not download $url");
-	}
+function downloadFile($url, $path)
+{
+    ini_set('max_execution_time', 0);
+    set_time_limit(0);
+    $folderPath = dirname(__DIR__, 2).DIRECTORY_SEPARATOR."upgrade".DIRECTORY_SEPARATOR;
+    if (!mkdir($folderPath)) {
+        //writeLog("error", "organizr could not create upgrade folder");
+    }
+    $newfname = $folderPath . $path;
+    $file = fopen($url, 'rb');
+    if ($file) {
+        $newf = fopen($newfname, 'wb');
+        if ($newf) {
+            while (!feof($file)) {
+                fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
+            }
+        }
+    } else {
+        //writeLog("error", "organizr could not download $url");
+    }
 
-	if ($file) {
-		fclose($file);
-		//writeLog("success", "organizr finished downloading the github zip file");
-	}else{
-		//writeLog("error", "organizr could not download the github zip file");
-	}
+    if ($file) {
+        fclose($file);
+    //writeLog("success", "organizr finished downloading the github zip file");
+    } else {
+        //writeLog("error", "organizr could not download the github zip file");
+    }
 
-	if ($newf) {
-		fclose($newf);
-		//writeLog("success", "organizr created upgrade zip file from github zip file");
-	}else{
-		//writeLog("error", "organizr could not create upgrade zip file from github zip file");
-	}
-	return true;
+    if ($newf) {
+        fclose($newf);
+    //writeLog("success", "organizr created upgrade zip file from github zip file");
+    } else {
+        //writeLog("error", "organizr could not create upgrade zip file from github zip file");
+    }
+    return true;
 }
-function unzipFile($zipFile){
-	ini_set('max_execution_time',0);
-	set_time_limit(0);
-	$zip = new ZipArchive;
-	$extractPath = dirname(__DIR__,2).DIRECTORY_SEPARATOR."upgrade/";
-	if($zip->open($extractPath . $zipFile) != "true"){
-		//writeLog("error", "organizr could not unzip upgrade.zip");
-	}else{
-		//writeLog("success", "organizr unzipped upgrade.zip");
-	}
-	/* Extract Zip File */
-	$zip->extractTo($extractPath);
-	$zip->close();
-	return true;
+function unzipFile($zipFile)
+{
+    ini_set('max_execution_time', 0);
+    set_time_limit(0);
+    $zip = new ZipArchive;
+    $extractPath = dirname(__DIR__, 2).DIRECTORY_SEPARATOR."upgrade/";
+    if ($zip->open($extractPath . $zipFile) != "true") {
+        //writeLog("error", "organizr could not unzip upgrade.zip");
+    } else {
+        //writeLog("success", "organizr unzipped upgrade.zip");
+    }
+    /* Extract Zip File */
+    $zip->extractTo($extractPath);
+    $zip->close();
+    return true;
 }
 // Function to remove folders and files
-function rrmdir($dir) {
-	ini_set('max_execution_time',0);
-	set_time_limit(0);
-	if (is_dir($dir)) {
-		$files = scandir($dir);
-		foreach ($files as $file)
-			if ($file != "." && $file != "..") rrmdir("$dir/$file");
-		rmdir($dir);
-	}
-	else if (file_exists($dir)) unlink($dir);
-	return true;
+function rrmdir($dir)
+{
+    ini_set('max_execution_time', 0);
+    set_time_limit(0);
+    if (is_dir($dir)) {
+        $files = scandir($dir);
+        foreach ($files as $file) {
+            if ($file != "." && $file != "..") {
+                rrmdir("$dir/$file");
+            }
+        }
+        rmdir($dir);
+    } elseif (file_exists($dir)) {
+        unlink($dir);
+    }
+    return true;
 }
 // Function to Copy folders and files
-function rcopy($src, $dst) {
-	ini_set('max_execution_time',0);
-	set_time_limit(0);
-	if (is_dir ( $src )) {
-		if (!file_exists($dst)) : mkdir ( $dst ); endif;
-		$files = scandir ( $src );
-		foreach ( $files as $file )
-			if ($file != "." && $file != "..")
-				rcopy ( "$src/$file", "$dst/$file" );
-	} else if (file_exists ( $src ))
-		copy ( $src, $dst );
-	return true;
+function rcopy($src, $dst)
+{
+    ini_set('max_execution_time', 0);
+    set_time_limit(0);
+    if (is_dir($src)) {
+        if (!file_exists($dst)) : mkdir($dst);
+        endif;
+        $files = scandir($src);
+        foreach ($files as $file) {
+            if ($file != "." && $file != "..") {
+                rcopy("$src/$file", "$dst/$file");
+            }
+        }
+    } elseif (file_exists($src)) {
+        copy($src, $dst);
+    }
+    return true;
 }

+ 23 - 26
api/functions/upgrade-functions.php

@@ -1,31 +1,28 @@
 <?php
 
-function upgradeCheck() {
-	$updateDB = false;
+function upgradeCheck()
+{
+    $updateDB = false;
     $compare = new Composer\Semver\Comparator;
-	// Upgrade check start for vserion below
-	$versionCheck = '2.0.0-alpha-120';
-	$config = loadConfig();
-	$oldVer = $config['configVersion'];
-	echo 'Doing check if version '.$oldVer.' is less than '.$versionCheck.'<br />';
-	if (isset($config['dbLocation']) && (!isset($config['configVersion']) || $compare->lessThan($config['configVersion'], $versionCheck))) {
+    // Upgrade check start for vserion below
+    $versionCheck = '2.0.0-alpha-120';
+    $config = loadConfig();
+    $oldVer = $config['configVersion'];
+    echo 'Doing check if version '.$oldVer.' is less than '.$versionCheck.'<br />';
+    if (isset($config['dbLocation']) && (!isset($config['configVersion']) || $compare->lessThan($config['configVersion'], $versionCheck))) {
         $updateDB = true;
-	}
-
-
-
-
-	if($updateDB == true){
-		return 'Upgraded Needed - Current Version '.$oldVer.' - New Version: '.$versionCheck;
-		// Upgrade database to latest version
-		//updateDB($GLOBALS['dbLocation'],$GLOBALS['dbName'],$oldVer);
-		// Update Version and Commit
-		//$config['configVersion'] = $versionCheck;
-		//copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.40].bak.php');
-		//$createConfigSuccess = createConfig($config);
-		//unset($config);
-	}else{
-		return 'No Upgraded Needed - Current Version Above: '.$versionCheck;
-	}
-	return true;
+    }
+    if ($updateDB == true) {
+        return 'Upgraded Needed - Current Version '.$oldVer.' - New Version: '.$versionCheck;
+    // Upgrade database to latest version
+        //updateDB($GLOBALS['dbLocation'],$GLOBALS['dbName'],$oldVer);
+        // Update Version and Commit
+        //$config['configVersion'] = $versionCheck;
+        //copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.40].bak.php');
+        //$createConfigSuccess = createConfig($config);
+        //unset($config);
+    } else {
+        return 'No Upgraded Needed - Current Version Above: '.$versionCheck;
+    }
+    return true;
 }

+ 167 - 167
api/index.php

@@ -7,9 +7,9 @@ $result = array();
 //Get request method
 $method = $_SERVER['REQUEST_METHOD'];
 reset($_GET);
-$function = (key($_GET) ? str_replace("/","_",key($_GET)) : false);
+$function = (key($_GET) ? str_replace("/", "_", key($_GET)) : false);
 //Exit if $function is blank
-if($function === false){
+if ($function === false) {
     $result['status'] = "error";
     $result['statusText'] = "No API Path Supplied";
     exit(json_encode($result));
@@ -19,12 +19,12 @@ switch ($function) {
     case 'v1_settings_page':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettings;
                     writeLog('success', 'Admin Function -  Accessed Settings Page', $GLOBALS['organizrUser']['username']);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -53,11 +53,11 @@ switch ($function) {
     case 'v1_settings_plugins':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsPlugins;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -72,11 +72,30 @@ switch ($function) {
     case 'v1_settings_tab_editor_homepage':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsTabEditorHomepage;
-                }else{
+                } else {
+                    $result['status'] = 'error';
+                    $result['statusText'] = 'API/Token invalid or not set';
+                    $result['data'] = null;
+                }
+                break;
+            default:
+                $result['status'] = 'error';
+                $result['statusText'] = 'The function requested is not defined for method: '.$method;
+                break;
+        }
+        break;
+    case 'v1_settings_tab_editor_homepage_order':
+        switch ($method) {
+            case 'GET':
+                if (qualifyRequest(1)) {
+                    $result['status'] = 'success';
+                    $result['statusText'] = 'success';
+                    $result['data'] = $pageSettingsTabEditorHomepageOrder;
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -88,44 +107,25 @@ switch ($function) {
                 break;
         }
         break;
-	case 'v1_settings_tab_editor_homepage_order':
-		switch ($method) {
-			case 'GET':
-				if(qualifyRequest(1)){
-					$result['status'] = 'success';
-					$result['statusText'] = 'success';
-					$result['data'] = $pageSettingsTabEditorHomepageOrder;
-				}else{
-					$result['status'] = 'error';
-					$result['statusText'] = 'API/Token invalid or not set';
-					$result['data'] = null;
-				}
-				break;
-			default:
-				$result['status'] = 'error';
-				$result['statusText'] = 'The function requested is not defined for method: '.$method;
-				break;
-		}
-		break;
     case 'v1_settings_homepage_list':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = getHomepageList();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
                 }
                 break;
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editPlugins($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -140,22 +140,22 @@ switch ($function) {
     case 'v1_settings_plugins_list':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = getPlugins();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
                 }
                 break;
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editPlugins($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -170,11 +170,11 @@ switch ($function) {
     case 'v1_settings_settings_logs':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsSettingsLogs;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -189,11 +189,11 @@ switch ($function) {
     case 'v1_settings_settings_sso':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsSettingsSSO;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -205,44 +205,44 @@ switch ($function) {
                 break;
         }
         break;
-	case 'v1_settings_settings_main':
-		switch ($method) {
-			case 'GET':
-				if(qualifyRequest(1)){
-					$result['status'] = 'success';
-					$result['statusText'] = 'success';
-					$result['data'] = $pageSettingsSettingsMain;
-				}else{
-					$result['status'] = 'error';
-					$result['statusText'] = 'API/Token invalid or not set';
-					$result['data'] = null;
-				}
-				break;
-			default:
-				$result['status'] = 'error';
-				$result['statusText'] = 'The function requested is not defined for method: '.$method;
-				break;
-		}
-			break;
+    case 'v1_settings_settings_main':
+        switch ($method) {
+            case 'GET':
+                if (qualifyRequest(1)) {
+                    $result['status'] = 'success';
+                    $result['statusText'] = 'success';
+                    $result['data'] = $pageSettingsSettingsMain;
+                } else {
+                    $result['status'] = 'error';
+                    $result['statusText'] = 'API/Token invalid or not set';
+                    $result['data'] = null;
+                }
+                break;
+            default:
+                $result['status'] = 'error';
+                $result['statusText'] = 'The function requested is not defined for method: '.$method;
+                break;
+        }
+            break;
     case 'v1_settings_customize_appearance':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsCustomizeAppearance;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
                 }
                 break;
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editAppearance($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -254,14 +254,14 @@ switch ($function) {
                 break;
         }
         break;
-	case 'v1_remove_file':
+    case 'v1_remove_file':
         switch ($method) {
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = removeFile($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -276,11 +276,11 @@ switch ($function) {
     case 'v1_update_config':
         switch ($method) {
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = updateConfigItem($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -295,11 +295,11 @@ switch ($function) {
     case 'v1_update_config_multiple':
         switch ($method) {
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = updateConfigMultiple($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -327,22 +327,22 @@ switch ($function) {
     case 'v1_settings_tab_editor_tabs':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsTabEditorTabs;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
                 }
                 break;
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editTabs($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -357,22 +357,22 @@ switch ($function) {
     case 'v1_settings_tab_editor_categories':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsTabEditorCategories;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
                 }
                 break;
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editCategories($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -387,26 +387,26 @@ switch ($function) {
     case 'v1_settings_user_manage_users':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsUserManageUsers;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
                 }
                 break;
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = adminEditUser($_POST);
-                }elseif(qualifyRequest(998)){
+                } elseif (qualifyRequest(998)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editUser($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -418,14 +418,14 @@ switch ($function) {
                 break;
         }
         break;
-	case 'v1_manage_user':
+    case 'v1_manage_user':
         switch ($method) {
             case 'POST':
-                if(qualifyRequest(998)){
+                if (qualifyRequest(998)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editUser($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -440,22 +440,22 @@ switch ($function) {
     case 'v1_settings_user_manage_groups':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsUserManageGroups;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
                 }
                 break;
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = adminEditGroup($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -470,22 +470,22 @@ switch ($function) {
     case 'v1_settings_image_manager_view':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageSettingsImageManager;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
                 }
                 break;
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editImages();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -500,11 +500,11 @@ switch ($function) {
     case 'v1_wizard_page':
         switch ($method) {
             case 'GET':
-                if(!file_exists('config'.DIRECTORY_SEPARATOR.'config.php')){
+                if (!file_exists('config'.DIRECTORY_SEPARATOR.'config.php')) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = $pageWizard;
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'Wizard has already been run';
                     $result['data'] = null;
@@ -532,11 +532,11 @@ switch ($function) {
     case 'v1_wizard_config':
         switch ($method) {
             case 'POST':
-                if(!file_exists('config'.DIRECTORY_SEPARATOR.'config.php')){
+                if (!file_exists('config'.DIRECTORY_SEPARATOR.'config.php')) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = wizardConfig($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'Wizard has already been run';
                     $result['data'] = null;
@@ -551,11 +551,11 @@ switch ($function) {
     case 'v1_wizard_path':
         switch ($method) {
             case 'POST':
-                if(!file_exists('config'.DIRECTORY_SEPARATOR.'config.php')){
+                if (!file_exists('config'.DIRECTORY_SEPARATOR.'config.php')) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = wizardPath($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'Wizard has already been run';
                     $result['data'] = null;
@@ -611,11 +611,11 @@ switch ($function) {
     case 'v1_force':
         switch ($method) {
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
-                    $result['data'] = upgradeInstall($_POST['data']['branch'],$_POST['data']['stage']);
-                }else{
+                    $result['data'] = upgradeInstall($_POST['data']['branch'], $_POST['data']['stage']);
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -656,11 +656,11 @@ switch ($function) {
     case 'v1_login_log':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = getLog('loginLog');
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -672,14 +672,14 @@ switch ($function) {
                 break;
         }
         break;
-	case 'v1_organizr_log':
+    case 'v1_organizr_log':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = getLog('org');
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -694,11 +694,11 @@ switch ($function) {
     case 'v1_user_list':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = allUsers();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -713,11 +713,11 @@ switch ($function) {
     case 'v1_tab_list':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = allTabs();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -732,11 +732,11 @@ switch ($function) {
     case 'v1_image_list':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = getImages();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -751,11 +751,11 @@ switch ($function) {
     case 'v1_customize_appearance':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = getCustomizeAppearance();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -770,11 +770,11 @@ switch ($function) {
     case 'v1_sso':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = getSSO();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -789,11 +789,11 @@ switch ($function) {
     case 'v1_settings_main':
         switch ($method) {
             case 'GET':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = getSettingsMain();
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -808,15 +808,15 @@ switch ($function) {
     case 'v1_user_edit':
         switch ($method) {
             case 'POST':
-                if(qualifyRequest(1)){
+                if (qualifyRequest(1)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = adminEditUser($_POST);
-                }elseif(qualifyRequest(998)){
+                } elseif (qualifyRequest(998)) {
                     $result['status'] = 'success';
                     $result['statusText'] = 'success';
                     $result['data'] = editUser($_POST);
-                }else{
+                } else {
                     $result['status'] = 'error';
                     $result['statusText'] = 'API/Token invalid or not set';
                     $result['data'] = null;
@@ -844,7 +844,7 @@ switch ($function) {
     case 'v1_launch_organizr':
         switch ($method) {
             case 'GET':
-				$pluginSearch = '-enabled';
+                $pluginSearch = '-enabled';
                 $pluginInclude = '-include';
                 $status = array();
                 $result['status'] = 'success';
@@ -854,18 +854,18 @@ switch ($function) {
                 $status['user'] = $GLOBALS['organizrUser'];
                 $status['categories'] = loadTabs()['categories'];
                 $status['tabs'] = loadTabs()['tabs'];
-				$status['plugins'] = array_filter($GLOBALS, function($k)use($pluginSearch){
-                    return stripos($k, $pluginSearch) !== FALSE;
+                $status['plugins'] = array_filter($GLOBALS, function ($k) use ($pluginSearch) {
+                    return stripos($k, $pluginSearch) !== false;
                 }, ARRAY_FILTER_USE_KEY);
-                $status['plugins']['includes'] = array_filter($GLOBALS, function($k)use($pluginInclude){
-                    return stripos($k, $pluginInclude) !== FALSE;
+                $status['plugins']['includes'] = array_filter($GLOBALS, function ($k) use ($pluginInclude) {
+                    return stripos($k, $pluginInclude) !== false;
                 }, ARRAY_FILTER_USE_KEY);
                 $result['data'] = $status;
                 $result['branch'] = $GLOBALS['branch'];
-				$result['theme'] = $GLOBALS['theme'];
+                $result['theme'] = $GLOBALS['theme'];
                 $result['style'] = $GLOBALS['style'];
                 $result['version'] = $GLOBALS['installedVersion'];
-				$result['sso'] = array(
+                $result['sso'] = array(
                     'myPlexAccessToken' => isset($_COOKIE['mpt']) ? $_COOKIE['mpt'] : false,
                     'id_token' => isset($_COOKIE['Auth']) ? $_COOKIE['Auth'] : false
                 );
@@ -877,7 +877,7 @@ switch ($function) {
                 break;
         }
         break;
-	case 'v1_auth':
+    case 'v1_auth':
         switch ($method) {
             case 'GET':
                 auth();
@@ -892,7 +892,7 @@ switch ($function) {
         switch ($method) {
             case 'POST':
                 // Include all plugin api Calls
-                foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . "*.php") as $filename){
+                foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'plugins' . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . "*.php") as $filename) {
                     require_once $filename;
                 }
                 break;
@@ -913,45 +913,45 @@ switch ($function) {
                 break;
         }
         break;
-	case 'v1_downloader':
-		switch ($method) {
-			case 'POST':
+    case 'v1_downloader':
+        switch ($method) {
+            case 'POST':
                 $result['status'] = 'success';
                 $result['statusText'] = 'success';
                 $result['data'] = downloader($_POST);
-				break;
-			default:
-				$result['status'] = 'error';
-				$result['statusText'] = 'The function requested is not defined for method: '.$method;
-				break;
-		}
-		break;
-	case 'v1_ombi':
-		switch ($method) {
-			case 'POST':
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = ombiAPI($_POST);
-				break;
-			default:
-				$result['status'] = 'error';
-				$result['statusText'] = 'The function requested is not defined for method: '.$method;
-				break;
-		}
-		break;
+                break;
+            default:
+                $result['status'] = 'error';
+                $result['statusText'] = 'The function requested is not defined for method: '.$method;
+                break;
+        }
+        break;
+    case 'v1_ombi':
+        switch ($method) {
+            case 'POST':
+                $result['status'] = 'success';
+                $result['statusText'] = 'success';
+                $result['data'] = ombiAPI($_POST);
+                break;
+            default:
+                $result['status'] = 'error';
+                $result['statusText'] = 'The function requested is not defined for method: '.$method;
+                break;
+        }
+        break;
     case 'v1_plex_join':
-		switch ($method) {
-			case 'POST':
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = plexJoinAPI($_POST);
-				break;
-			default:
-				$result['status'] = 'error';
-				$result['statusText'] = 'The function requested is not defined for method: '.$method;
-				break;
-		}
-		break;
+        switch ($method) {
+            case 'POST':
+                $result['status'] = 'success';
+                $result['statusText'] = 'success';
+                $result['data'] = plexJoinAPI($_POST);
+                break;
+            default:
+                $result['status'] = 'error';
+                $result['statusText'] = 'The function requested is not defined for method: '.$method;
+                break;
+        }
+        break;
     default:
         //No Function Available
         $result['status'] = 'error';
@@ -959,7 +959,7 @@ switch ($function) {
         break;
 }
 //Set Default Result
-if(!$result){
+if (!$result) {
     $result['status'] = "error";
     $result['error'] = "An error has occurred";
 }

+ 3 - 3
api/plugins/api/invites.php

@@ -1,12 +1,12 @@
 <?php
-if(isset($_POST['data']['plugin'])){
+if (isset($_POST['data']['plugin'])) {
     switch ($_POST['data']['plugin']) {
         case 'Invites/settings/get':
-            if(qualifyRequest(1)){
+            if (qualifyRequest(1)) {
                 $result['status'] = 'success';
                 $result['statusText'] = 'success';
                 $result['data'] = invitesGetSettings();
-            }else{
+            } else {
                 $result['status'] = 'error';
                 $result['statusText'] = 'API/Token invalid or not set';
                 $result['data'] = null;

+ 11 - 11
api/plugins/api/php-mailer.php

@@ -1,50 +1,50 @@
 <?php
-if(isset($_POST['data']['plugin'])){
+if (isset($_POST['data']['plugin'])) {
     switch ($_POST['data']['plugin']) {
         case 'PHPMailer/settings/get':
-            if(qualifyRequest(1)){
+            if (qualifyRequest(1)) {
                 $result['status'] = 'success';
                 $result['statusText'] = 'success';
                 $result['data'] = phpmGetSettings();
-            }else{
+            } else {
                 $result['status'] = 'error';
                 $result['statusText'] = 'API/Token invalid or not set';
                 $result['data'] = null;
             }
             break;
         case 'PHPMailer/send/test':
-            if(qualifyRequest(1)){
+            if (qualifyRequest(1)) {
                 $result['status'] = 'success';
                 $result['statusText'] = 'success';
                 $result['data'] = phpmSendTestEmail();
-            }else{
+            } else {
                 $result['status'] = 'error';
                 $result['statusText'] = 'API/Token invalid or not set';
                 $result['data'] = null;
             }
             break;
         case 'PHPMailer/send/email':
-            if(qualifyRequest(1)){
+            if (qualifyRequest(1)) {
                 $result['status'] = 'success';
                 $result['statusText'] = 'success';
                 $result['data'] = phpmAdminSendEmail();
-            }else{
+            } else {
                 $result['status'] = 'error';
                 $result['statusText'] = 'API/Token invalid or not set';
                 $result['data'] = null;
             }
             break;
-		case 'PHPMailer/users/get':
-            if(qualifyRequest(1)){
+        case 'PHPMailer/users/get':
+            if (qualifyRequest(1)) {
                 $result['status'] = 'success';
                 $result['statusText'] = 'success';
                 $result['data'] = getEmails();
-            }else{
+            } else {
                 $result['status'] = 'error';
                 $result['statusText'] = 'API/Token invalid or not set';
                 $result['data'] = null;
             }
-	            break;
+                break;
         default:
             //DO NOTHING!!
             break;

+ 3 - 3
api/plugins/api/speedTest.php

@@ -1,12 +1,12 @@
 <?php
-if(isset($_POST['data']['plugin'])){
+if (isset($_POST['data']['plugin'])) {
     switch ($_POST['data']['plugin']) {
         case 'SpeedTest/settings/get':
-            if(qualifyRequest(1)){
+            if (qualifyRequest(1)) {
                 $result['status'] = 'success';
                 $result['statusText'] = 'success';
                 $result['data'] = speedTestGetSettings();
-            }else{
+            } else {
                 $result['status'] = 'error';
                 $result['statusText'] = 'API/Token invalid or not set';
                 $result['data'] = null;

+ 1 - 1
api/plugins/config/invites.php

@@ -1,6 +1,6 @@
 <?php
 return array(
     'INVITES-enabled' => false,
-	'INVITES-type-include' => 'plex',
+    'INVITES-type-include' => 'plex',
     'INVITES-plexLibraries' => '',
 );

+ 21 - 21
api/plugins/config/php-mailer.php

@@ -9,38 +9,38 @@ return array(
     'PHPMAILER-smtpHostSenderName' => 'Organizr',
     'PHPMAILER-smtpHostSenderEmail' => 'no-reply@Organizr.tld',
     'PHPMAILER-smtpHostType' => 'tls',
-	'PHPMAILER-domain' => '',
-	'PHPMAILER-template' => 'default',
-	'PHPMAILER-logo' => 'https://raw.githubusercontent.com/causefx/Organizr/master/images/organizr-logo-h.png',
+    'PHPMAILER-domain' => '',
+    'PHPMAILER-template' => 'default',
+    'PHPMAILER-logo' => 'https://raw.githubusercontent.com/causefx/Organizr/master/images/organizr-logo-h.png',
     'PHPMAILER-emailTemplateResetPassword' => '
 	<h2>Hey there {user}!</h2><br />
 	Looks like you forgot your password.  Well, I got you...  Here is your new password: {password}<br />
 	If you want to change it once you log in, you can.  Head over to my website: {domain}<br />
 	',
-	'PHPMAILER-emailTemplateResetPasswordSubject' => 'Password Reset',
-	'PHPMAILER-emailTemplateInviteUser' => '
+    'PHPMAILER-emailTemplateResetPasswordSubject' => 'Password Reset',
+    'PHPMAILER-emailTemplateInviteUser' => '
 	<h2>Hey there {user}!</h2><br />
 	Here is the invite code to join my cool media server: {inviteCode}<br/>
 	Head over to my website and enter the code to join: {domain}<br />
 	',
-	'PHPMAILER-emailTemplateInviteUserSubject' => 'You have been invited to join my server',
-	'PHPMAILER-emailTemplateRegisterUser' => '
+    'PHPMAILER-emailTemplateInviteUserSubject' => 'You have been invited to join my server',
+    'PHPMAILER-emailTemplateRegisterUser' => '
 	<h2>Hey there {user}!</h2><br />
 	Welcome to my site.<br/>
 	If you need anything, please let me know.<br />
 	',
-	'PHPMAILER-emailTemplateRegisterUserSubject' => 'Thank you For Registering',
-	'PHPMAILER-emailTemplateRegisterUserEnabled' => true,
-	'PHPMAILER-emailTemplateCustom-include-One' => '',
-	'PHPMAILER-emailTemplateCustom-include-OneName' => 'Template #1',
-	'PHPMAILER-emailTemplateCustom-include-OneSubject' => '',
-	'PHPMAILER-emailTemplateCustom-include-Two' => '',
-	'PHPMAILER-emailTemplateCustom-include-TwoName' => 'Template #2',
-	'PHPMAILER-emailTemplateCustom-include-TwoSubject' => '',
-	'PHPMAILER-emailTemplateCustom-include-Three' => '',
-	'PHPMAILER-emailTemplateCustom-include-ThreeName' => 'Template #3',
-	'PHPMAILER-emailTemplateCustom-include-ThreeSubject' => '',
-	'PHPMAILER-emailTemplateCustom-include-Four' => '',
-	'PHPMAILER-emailTemplateCustom-include-FourName' => 'Template #4',
-	'PHPMAILER-emailTemplateCustom-include-FourSubject' => '',
+    'PHPMAILER-emailTemplateRegisterUserSubject' => 'Thank you For Registering',
+    'PHPMAILER-emailTemplateRegisterUserEnabled' => true,
+    'PHPMAILER-emailTemplateCustom-include-One' => '',
+    'PHPMAILER-emailTemplateCustom-include-OneName' => 'Template #1',
+    'PHPMAILER-emailTemplateCustom-include-OneSubject' => '',
+    'PHPMAILER-emailTemplateCustom-include-Two' => '',
+    'PHPMAILER-emailTemplateCustom-include-TwoName' => 'Template #2',
+    'PHPMAILER-emailTemplateCustom-include-TwoSubject' => '',
+    'PHPMAILER-emailTemplateCustom-include-Three' => '',
+    'PHPMAILER-emailTemplateCustom-include-ThreeName' => 'Template #3',
+    'PHPMAILER-emailTemplateCustom-include-ThreeSubject' => '',
+    'PHPMAILER-emailTemplateCustom-include-Four' => '',
+    'PHPMAILER-emailTemplateCustom-include-FourName' => 'Template #4',
+    'PHPMAILER-emailTemplateCustom-include-FourSubject' => '',
 );

+ 1 - 1
api/plugins/config/speedTest.php

@@ -2,5 +2,5 @@
 return array(
     'SPEEDTEST-enabled' => false,
     'SPEEDTEST-Auth-include' => '1',
-	'SPEEDTEST-option2-include' => '',
+    'SPEEDTEST-option2-include' => '',
 );

+ 242 - 241
api/plugins/invites.php

@@ -3,259 +3,260 @@
 // PLUGIN INFORMATION
 $GLOBALS['plugins'][]['Invites'] = array( // Plugin Name
     'name'=>'Invites', // Plugin Name
-	'author'=>'CauseFX', // Who wrote the plugin
+    'author'=>'CauseFX', // Who wrote the plugin
     'category'=>'Management', // One to Two Word Description
     'link'=>'https://github.com/PHPMailer/PHPMailer', // Link to plugin info
-	'license'=>'personal', // License Type use , for multiple
+    'license'=>'personal', // License Type use , for multiple
     //'fileName'=>'php-mailer.php',
-	//'configFile'=>'php-mailer.php',
-	//'apiFile'=>'php-mailer.php',
-	'idPrefix'=>'INVITES', // html element id prefix
-	'configPrefix'=>'INVITES', // config file prefix for array items without the hypen
+    //'configFile'=>'php-mailer.php',
+    //'apiFile'=>'php-mailer.php',
+    'idPrefix'=>'INVITES', // html element id prefix
+    'configPrefix'=>'INVITES', // config file prefix for array items without the hypen
     'version'=>'1.0.0', // SemVer of plugin
     'image'=>'plugins/images/invites.png', // 1:1 non transparent image for plugin
-	'settings'=>true, // does plugin need a settings page? true or false
+    'settings'=>true, // does plugin need a settings page? true or false
     'homepage'=>false // Is plugin for use on homepage? true or false
 );
 // INCLUDE/REQUIRE FILES
 
 // PLUGIN FUNCTIONS
-function inviteCodes($array) {
-	$action = isset($array['data']['action']) ? $array['data']['action'] : null;
-	$code = isset($array['data']['code']) ? $array['data']['code'] : null;
-	$usedBy = isset($array['data']['usedby']) ? $array['data']['usedby'] : null;
-	$username = isset($array['data']['username']) ? $array['data']['username'] : null;
-	$email = isset($array['data']['email']) ? $array['data']['email'] : null;
-	$id = isset($array['data']['id']) ? $array['data']['id'] : null;
-	$now = date("Y-m-d H:i:s");
-	$currentIP = userIP();
-	switch ($action) {
-		case "check":
-			try {
-		    	$connect = new Dibi\Connection([
-		    		'driver' => 'sqlite3',
-		    		'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
-		    	]);
-		        $all = $connect->fetch('SELECT * FROM invites WHERE valid = "Yes" AND code = ?',$code);
-		        return ($all) ? true : false;
-		    } catch (Dibi\Exception $e) {
-		        return false;
-		    }
-			break;
-		case "use":
-			try {
-				if(inviteCodes(array('data' => array('action' => 'check','code' => $code)))){
-					$connect = new Dibi\Connection([
-	                    'driver' => 'sqlite3',
-	                    'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
-	                ]);
-	                $connect->query('
+function inviteCodes($array)
+{
+    $action = isset($array['data']['action']) ? $array['data']['action'] : null;
+    $code = isset($array['data']['code']) ? $array['data']['code'] : null;
+    $usedBy = isset($array['data']['usedby']) ? $array['data']['usedby'] : null;
+    $username = isset($array['data']['username']) ? $array['data']['username'] : null;
+    $email = isset($array['data']['email']) ? $array['data']['email'] : null;
+    $id = isset($array['data']['id']) ? $array['data']['id'] : null;
+    $now = date("Y-m-d H:i:s");
+    $currentIP = userIP();
+    switch ($action) {
+        case "check":
+            try {
+                $connect = new Dibi\Connection([
+                    'driver' => 'sqlite3',
+                    'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
+                ]);
+                $all = $connect->fetch('SELECT * FROM invites WHERE valid = "Yes" AND code = ?', $code);
+                return ($all) ? true : false;
+            } catch (Dibi\Exception $e) {
+                return false;
+            }
+            break;
+        case "use":
+            try {
+                if (inviteCodes(array('data' => array('action' => 'check','code' => $code)))) {
+                    $connect = new Dibi\Connection([
+                        'driver' => 'sqlite3',
+                        'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
+                    ]);
+                    $connect->query('
 	                	UPDATE invites SET', [
-							'valid' => 'No',
-	                        'usedby' => $usedBy,
-							'dateused' => $now,
-	                		'ip' => $currentIP,
-	                	], '
+                            'valid' => 'No',
+                            'usedby' => $usedBy,
+                            'dateused' => $now,
+                            'ip' => $currentIP,
+                        ], '
 	                	WHERE code=?', $code);
-	                    writeLog('success', 'Invite Management Function -  Invite Used ['.$code.']', 'SYSTEM');
-						return inviteAction($usedBy,'share',$GLOBALS['INVITES-type-include']);
-				}else{
-					return false;
-				}
-
+                    writeLog('success', 'Invite Management Function -  Invite Used ['.$code.']', 'SYSTEM');
+                    return inviteAction($usedBy, 'share', $GLOBALS['INVITES-type-include']);
+                } else {
+                    return false;
+                }
             } catch (Dibi\Exception $e) {
                 return false;
             }/*
-			if(ENABLEMAIL){
-				if (!isset($GLOBALS['USER'])) {
-					require_once("user.php");
-					$GLOBALS['USER'] = new User('registration_callback');
-				}
-				$emailTemplate = array(
-					'type' => 'mass',
-					'body' => 'The user: {user} has reddemed the code: {inviteCode} his IP Address was '.$currentIP,
-					'subject' => 'Invite Code '.$code.' Has Been Used',
-					'user' => $usedBy,
-					'password' => null,
-					'inviteCode' => $code,
-				);
-				$emailTemplate = emailTemplate($emailTemplate);
-				$subject = $emailTemplate['subject'];
-				$body = buildEmail($emailTemplate);
-				sendEmail($GLOBALS['USER']->adminEmail, "Admin", $subject, $body);
-			}*/
-			break;
-		default:
-		if(qualifyRequest(1)){
-			switch ($action) {
-				case "create":
-					try {
-						$connect = new Dibi\Connection([
-							'driver' => 'sqlite3',
-							'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
-						]);
-						$newCode = [
-							'code' => $code,
-							'email' => $email,
-							'username' => $username,
-							'valid' => 'Yes',
-							'type' => $GLOBALS['INVITES-type-include'],
-						];
-						$connect->query('INSERT INTO [invites]', $newCode);
-						writeLog('success', 'Invite Management Function -  Added Invite ['.$code.']', $GLOBALS['organizrUser']['username']);
-						if($GLOBALS['PHPMAILER-enabled']){
-							$emailTemplate = array(
-								'type' => 'invite',
-								'body' => $GLOBALS['PHPMAILER-emailTemplateInviteUser'],
-								'subject' => $GLOBALS['PHPMAILER-emailTemplateInviteUserSubject'],
-								'user' => $username,
-								'password' => null,
-								'inviteCode' => $code,
-							);
-							$emailTemplate = phpmEmailTemplate($emailTemplate);
-							$sendEmail = array(
-								'to' => $email,
-								'subject' => $emailTemplate['subject'],
-								'body' => phpmBuildEmail($emailTemplate),
-							);
-							phpmSendEmail($sendEmail);
-						}
-						return true;
-					} catch (Dibi\Exception $e) {
-						writeLog('error', 'Invite Management Function  -  Error ['.$e.']', 'SYSTEM');
-						return false;
-					}
-					break;
-				case "get":
-					try {
-						$connect = new Dibi\Connection([
-							'driver' => 'sqlite3',
-							'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
-						]);
-						$invites = $connect->fetchAll('SELECT * FROM invites');
-						return $invites;
-					} catch (Dibi\Exception $e) {
-						writeLog('error', 'Invite Management Function  -  Error ['.$e.']', 'SYSTEM');
-						return false;
-					}
-					break;
-				case "delete":
-					try {
-						$connect = new Dibi\Connection([
-							'driver' => 'sqlite3',
-							'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
-						]);
-						$connect->query('DELETE FROM invites WHERE id = ?', $id);
-						return true;
-					} catch (Dibi\Exception $e) {
-						writeLog('error', 'Invite Management Function  -  Error ['.$e.']', 'SYSTEM');
-						return false;
-					}
-					break;
-				default:
-				return false;
-			}
-		}
-	}
-
+            if(ENABLEMAIL){
+                if (!isset($GLOBALS['USER'])) {
+                    require_once("user.php");
+                    $GLOBALS['USER'] = new User('registration_callback');
+                }
+                $emailTemplate = array(
+                    'type' => 'mass',
+                    'body' => 'The user: {user} has reddemed the code: {inviteCode} his IP Address was '.$currentIP,
+                    'subject' => 'Invite Code '.$code.' Has Been Used',
+                    'user' => $usedBy,
+                    'password' => null,
+                    'inviteCode' => $code,
+                );
+                $emailTemplate = emailTemplate($emailTemplate);
+                $subject = $emailTemplate['subject'];
+                $body = buildEmail($emailTemplate);
+                sendEmail($GLOBALS['USER']->adminEmail, "Admin", $subject, $body);
+            }*/
+            break;
+        default:
+        if (qualifyRequest(1)) {
+            switch ($action) {
+                case "create":
+                    try {
+                        $connect = new Dibi\Connection([
+                            'driver' => 'sqlite3',
+                            'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
+                        ]);
+                        $newCode = [
+                            'code' => $code,
+                            'email' => $email,
+                            'username' => $username,
+                            'valid' => 'Yes',
+                            'type' => $GLOBALS['INVITES-type-include'],
+                        ];
+                        $connect->query('INSERT INTO [invites]', $newCode);
+                        writeLog('success', 'Invite Management Function -  Added Invite ['.$code.']', $GLOBALS['organizrUser']['username']);
+                        if ($GLOBALS['PHPMAILER-enabled']) {
+                            $emailTemplate = array(
+                                'type' => 'invite',
+                                'body' => $GLOBALS['PHPMAILER-emailTemplateInviteUser'],
+                                'subject' => $GLOBALS['PHPMAILER-emailTemplateInviteUserSubject'],
+                                'user' => $username,
+                                'password' => null,
+                                'inviteCode' => $code,
+                            );
+                            $emailTemplate = phpmEmailTemplate($emailTemplate);
+                            $sendEmail = array(
+                                'to' => $email,
+                                'subject' => $emailTemplate['subject'],
+                                'body' => phpmBuildEmail($emailTemplate),
+                            );
+                            phpmSendEmail($sendEmail);
+                        }
+                        return true;
+                    } catch (Dibi\Exception $e) {
+                        writeLog('error', 'Invite Management Function  -  Error ['.$e.']', 'SYSTEM');
+                        return false;
+                    }
+                    break;
+                case "get":
+                    try {
+                        $connect = new Dibi\Connection([
+                            'driver' => 'sqlite3',
+                            'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
+                        ]);
+                        $invites = $connect->fetchAll('SELECT * FROM invites');
+                        return $invites;
+                    } catch (Dibi\Exception $e) {
+                        writeLog('error', 'Invite Management Function  -  Error ['.$e.']', 'SYSTEM');
+                        return false;
+                    }
+                    break;
+                case "delete":
+                    try {
+                        $connect = new Dibi\Connection([
+                            'driver' => 'sqlite3',
+                            'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
+                        ]);
+                        $connect->query('DELETE FROM invites WHERE id = ?', $id);
+                        return true;
+                    } catch (Dibi\Exception $e) {
+                        writeLog('error', 'Invite Management Function  -  Error ['.$e.']', 'SYSTEM');
+                        return false;
+                    }
+                    break;
+                default:
+                return false;
+            }
+        }
+    }
 }
 /* GET PHPMAILER SETTINGS */
-function invitesGetSettings(){
-	if($GLOBALS['plexID'] !== '' && $GLOBALS['plexToken'] !== '' && $GLOBALS['INVITES-type-include'] !== ''){
-		$loop = libraryList($GLOBALS['INVITES-type-include'])['libraries'];
-		foreach ($loop as $key => $value) {
-		    $libraryList[] = array(
-		        'name' => $key,
-		        'value' => $value
-		    );
-		}
-	}else{
-		$libraryList = array(
-			array(
-				'name'=>'Refresh page to update List',
-				'value'=>'',
-				'disabled' => true,
-			),
-		);
-	}
-	return array(
-		'Backend' => array(
-			array(
-				'type' => 'select',
-				'name' => 'INVITES-type-include',
-				'label' => 'Media Server',
-				'value' => $GLOBALS['INVITES-type-include'],
-				'options' => array(
-					array(
-						'name'=>'N/A',
-						'value'=>'n/a'
-					),
-					array(
-						'name'=>'Plex',
-						'value'=>'plex'
-					),
-					array(
-						'name'=>'Emby [Not Ready]',
-						'value'=>'emby'
-					)
-				)
-			)
-		),
-		'Plex Settings' => array(
-    		array(
-    			'type' => 'password-alt',
-    			'name' => 'plexToken',
-    			'label' => 'Plex Token',
-    			'value' => $GLOBALS['plexToken'],
-    			'placeholder' => 'Use Get Token Button'
-    		),
-    		array(
-    			'type' => 'password-alt',
-    			'name' => 'plexID',
-    			'label' => 'Plex Machine',
-    			'value' => $GLOBALS['plexID'],
-    			'placeholder' => 'Use Get Plex Machine Button'
-    		),
-			array(
-				'type' => 'select2',
-				'name' => 'INVITES-plexLibraries',
-				'label' => 'Libraries',
-				'value' => $GLOBALS['INVITES-plexLibraries'],
-				'options' => $libraryList
-			)
-		),
-		'Emby Settings' => array(
+function invitesGetSettings()
+{
+    if ($GLOBALS['plexID'] !== '' && $GLOBALS['plexToken'] !== '' && $GLOBALS['INVITES-type-include'] !== '') {
+        $loop = libraryList($GLOBALS['INVITES-type-include'])['libraries'];
+        foreach ($loop as $key => $value) {
+            $libraryList[] = array(
+                'name' => $key,
+                'value' => $value
+            );
+        }
+    } else {
+        $libraryList = array(
+            array(
+                'name'=>'Refresh page to update List',
+                'value'=>'',
+                'disabled' => true,
+            ),
+        );
+    }
+    return array(
+        'Backend' => array(
+            array(
+                'type' => 'select',
+                'name' => 'INVITES-type-include',
+                'label' => 'Media Server',
+                'value' => $GLOBALS['INVITES-type-include'],
+                'options' => array(
+                    array(
+                        'name'=>'N/A',
+                        'value'=>'n/a'
+                    ),
+                    array(
+                        'name'=>'Plex',
+                        'value'=>'plex'
+                    ),
+                    array(
+                        'name'=>'Emby [Not Ready]',
+                        'value'=>'emby'
+                    )
+                )
+            )
+        ),
+        'Plex Settings' => array(
+            array(
+                'type' => 'password-alt',
+                'name' => 'plexToken',
+                'label' => 'Plex Token',
+                'value' => $GLOBALS['plexToken'],
+                'placeholder' => 'Use Get Token Button'
+            ),
+            array(
+                'type' => 'password-alt',
+                'name' => 'plexID',
+                'label' => 'Plex Machine',
+                'value' => $GLOBALS['plexID'],
+                'placeholder' => 'Use Get Plex Machine Button'
+            ),
+            array(
+                'type' => 'select2',
+                'name' => 'INVITES-plexLibraries',
+                'label' => 'Libraries',
+                'value' => $GLOBALS['INVITES-plexLibraries'],
+                'options' => $libraryList
+            )
+        ),
+        'Emby Settings' => array(
 
-		),
-		'FYI' => array(
-			array(
-				'type' => 'html',
-				'label' => 'Note',
-				'html' => 'After enabling for the first time, please reload the page'
-			),
-			array(
-				'type' => 'button',
-				'label' => 'Open Invite Modal',
-				'class' => 'inline-popups inviteModal',
-				'attr' => 'data-effect="mfp-zoom-out"',
-				'href' => '#invite-area',
-				'icon' => 'fa fa-paper-plane',
-				'text' => 'Open'
-			)
-		)
-	);
+        ),
+        'FYI' => array(
+            array(
+                'type' => 'html',
+                'label' => 'Note',
+                'html' => 'After enabling for the first time, please reload the page'
+            ),
+            array(
+                'type' => 'button',
+                'label' => 'Open Invite Modal',
+                'class' => 'inline-popups inviteModal',
+                'attr' => 'data-effect="mfp-zoom-out"',
+                'href' => '#invite-area',
+                'icon' => 'fa fa-paper-plane',
+                'text' => 'Open'
+            )
+        )
+    );
 }
-function inviteAction($username,$action=null,$type=null){
-    if($action == null){
+function inviteAction($username, $action=null, $type=null)
+{
+    if ($action == null) {
         return false;
     }
     switch ($type) {
         case 'plex':
-            if(!empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'])){
+            if (!empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'])) {
                 $url = "https://plex.tv/api/servers/".$GLOBALS['plexID']."/shared_servers/";
-                if($GLOBALS['INVITES-plexLibraries'] !== ""){
-                    $libraries = explode(',',$GLOBALS['INVITES-plexLibraries']);
-                }else{
+                if ($GLOBALS['INVITES-plexLibraries'] !== "") {
+                    $libraries = explode(',', $GLOBALS['INVITES-plexLibraries']);
+                } else {
                     $libraries = '';
                 }
                 $headers = array(
@@ -270,7 +271,7 @@ function inviteAction($username,$action=null,$type=null){
                         "invited_email" => $username
                     )
                 );
-                try{
+                try {
                     switch ($action) {
                         case 'share':
                             $response = Requests::post($url, $headers, json_encode($data), array());
@@ -284,33 +285,33 @@ function inviteAction($username,$action=null,$type=null){
                             return false;
                             break;
                     }
-                    if($response->success){
-						writeLog('success', 'Plex Invite Function - Plex User now has access to system', $username);
+                    if ($response->success) {
+                        writeLog('success', 'Plex Invite Function - Plex User now has access to system', $username);
                         return true;
-                    }else{
+                    } else {
                         switch ($response->status_code) {
                             case 400:
-								writeLog('error', 'Plex Invite Function - Plex User already has access', $username);
+                                writeLog('error', 'Plex Invite Function - Plex User already has access', $username);
                                 return false;
                                 break;
                             case 401:
-								writeLog('error', 'Plex Invite Function - Incorrect Token', 'SYSTEM');
+                                writeLog('error', 'Plex Invite Function - Incorrect Token', 'SYSTEM');
                                 return false;
                                 break;
                             default:
-								writeLog('error', 'Plex Invite Function - An error occured', $username);
+                                writeLog('error', 'Plex Invite Function - An error occured', $username);
                                 return false;
                                 break;
                         }
                     }
-					return false;
-                }catch( Requests_Exception $e ) {
+                    return false;
+                } catch (Requests_Exception $e) {
                     writeLog('error', 'Plex Invite Function - Error: '.$e->getMessage(), 'SYSTEM');
-					return false;
+                    return false;
                 };
-            }else{
+            } else {
                 writeLog('error', 'Plex Invite Function - Plex Token/ID not set', 'SYSTEM');
-				return false;
+                return false;
             }
             break;
         case 'emby':

+ 433 - 421
api/plugins/php-mailer.php

@@ -3,444 +3,456 @@
 // PLUGIN INFORMATION
 $GLOBALS['plugins'][]['PHP Mailer'] = array( // Plugin Name
     'name'=>'PHP Mailer', // Plugin Name
-	'author'=>'PHP Mailer', // Who wrote the plugin
+    'author'=>'PHP Mailer', // Who wrote the plugin
     'category'=>'Mail', // One to Two Word Description
     'link'=>'https://github.com/PHPMailer/PHPMailer', // Link to plugin info
-	'license'=>'personal,business', // License Type use , for multiple
+    'license'=>'personal,business', // License Type use , for multiple
     //'fileName'=>'php-mailer.php',
-	//'configFile'=>'php-mailer.php',
-	//'apiFile'=>'php-mailer.php',
-	'idPrefix'=>'PHPMAILER', // html element id prefix
-	'configPrefix'=>'PHPMAILER', // config file prefix for array items without the hypen
+    //'configFile'=>'php-mailer.php',
+    //'apiFile'=>'php-mailer.php',
+    'idPrefix'=>'PHPMAILER', // html element id prefix
+    'configPrefix'=>'PHPMAILER', // config file prefix for array items without the hypen
     'version'=>'1.0.0', // SemVer of plugin
     'image'=>'plugins/images/php-mailer.png', // 1:1 non transparent image for plugin
-	'settings'=>true, // does plugin need a settings page? true or false
+    'settings'=>true, // does plugin need a settings page? true or false
     'homepage'=>false // Is plugin for use on homepage? true or false
 );
 // INCLUDE/REQUIRE FILES
 
 // PLUGIN FUNCTIONS
-function getEmails(){
-	if($GLOBALS['authBackend']){
-		if($GLOBALS['authBackend'] == 'plex'){
-			$type = 'plex';
-		}
-	}else{
-		$type = 'none';
-	}
-	if($type == 'plex'){
-		$emails = array_merge(libraryList('plex')['both'],getOrgUsers());
-	}elseif($type == 'emby'){
-		$emails = getOrgUsers();
-	}else{
-		$emails = getOrgUsers();
-	}
-	return $emails;
+function getEmails()
+{
+    if ($GLOBALS['authBackend']) {
+        if ($GLOBALS['authBackend'] == 'plex') {
+            $type = 'plex';
+        }
+    } else {
+        $type = 'none';
+    }
+    if ($type == 'plex') {
+        $emails = array_merge(libraryList('plex')['both'], getOrgUsers());
+    } elseif ($type == 'emby') {
+        $emails = getOrgUsers();
+    } else {
+        $emails = getOrgUsers();
+    }
+    return $emails;
 }
-function getTemplates(){
-	foreach (glob(dirname(__DIR__,2).DIRECTORY_SEPARATOR.'api' .DIRECTORY_SEPARATOR.'plugins' .DIRECTORY_SEPARATOR.'misc' . DIRECTORY_SEPARATOR . 'emailTemplates' . DIRECTORY_SEPARATOR . "*.php") as $filename){
-		$templates[] = array(
-			'name' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename)),
-			'value' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename))
-		);
-	}
-	return $templates;
+function getTemplates()
+{
+    foreach (glob(dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'api' .DIRECTORY_SEPARATOR.'plugins' .DIRECTORY_SEPARATOR.'misc' . DIRECTORY_SEPARATOR . 'emailTemplates' . DIRECTORY_SEPARATOR . "*.php") as $filename) {
+        $templates[] = array(
+            'name' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename)),
+            'value' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename))
+        );
+    }
+    return $templates;
 }
-function phpmEmailTemplate($emailTemplate){
-	$variables = [
-		'{user}' => $emailTemplate['user'],
-		'{domain}' => getServerPath(true),
-		'{password}' => $emailTemplate['password'],
-		'{inviteCode}' => $emailTemplate['inviteCode'],
-		'{fullDomain}' => getServerPath(true),
-		'{title}' => $GLOBALS['title'],
-	];
-	$emailTemplate['body'] = strtr($emailTemplate['body'], $variables);
-	$emailTemplate['subject'] = strtr($emailTemplate['subject'], $variables);
-	return $emailTemplate;
+function phpmEmailTemplate($emailTemplate)
+{
+    $variables = [
+        '{user}' => $emailTemplate['user'],
+        '{domain}' => getServerPath(true),
+        '{password}' => $emailTemplate['password'],
+        '{inviteCode}' => $emailTemplate['inviteCode'],
+        '{fullDomain}' => getServerPath(true),
+        '{title}' => $GLOBALS['title'],
+    ];
+    $emailTemplate['body'] = strtr($emailTemplate['body'], $variables);
+    $emailTemplate['subject'] = strtr($emailTemplate['subject'], $variables);
+    return $emailTemplate;
 }
-function phpmBuildEmail($email){
-	$subject = (isset($email['subject'])) ? $email['subject'] : 'Message from Server';
-	$body = (isset($email['body'])) ? $email['body'] : 'Message Error Occured';
-	$type = (isset($email['type'])) ? $email['type'] : 'No Type';
-	switch ($type) {
-		case 'invite':
-			$extra = 'invite';
-			break;
-		case 'reset':
-			$extra = 'reset';
-			break;
-		default:
-			$extra = null;
-			break;
-	}
-	include('misc/emailTemplates/'.$GLOBALS['PHPMAILER-template'].'.php');
-	return $email;
+function phpmBuildEmail($email)
+{
+    $subject = (isset($email['subject'])) ? $email['subject'] : 'Message from Server';
+    $body = (isset($email['body'])) ? $email['body'] : 'Message Error Occured';
+    $type = (isset($email['type'])) ? $email['type'] : 'No Type';
+    switch ($type) {
+        case 'invite':
+            $extra = 'invite';
+            break;
+        case 'reset':
+            $extra = 'reset';
+            break;
+        default:
+            $extra = null;
+            break;
+    }
+    include('misc/emailTemplates/'.$GLOBALS['PHPMAILER-template'].'.php');
+    return $email;
 }
-function phpmAdminSendEmail(){
-	if($GLOBALS['PHPMAILER-enabled']){
-		$emailTemplate = array(
-			'type' => 'admin',
-			'body' => $_POST['data']['body'],
-			'subject' => $_POST['data']['subject'],
-			'user' => null,
-			'password' => null,
-			'inviteCode' => null,
-		);
-		$emailTemplate = phpmEmailTemplate($emailTemplate);
-		$sendEmail = array(
-			'bcc' => $_POST['data']['bcc'],
-			'subject' => $emailTemplate['subject'],
-			'body' => phpmBuildEmail($emailTemplate),
-		);
-		return phpmSendEmail($sendEmail);
-	}
-	return false;
+function phpmAdminSendEmail()
+{
+    if ($GLOBALS['PHPMAILER-enabled']) {
+        $emailTemplate = array(
+            'type' => 'admin',
+            'body' => $_POST['data']['body'],
+            'subject' => $_POST['data']['subject'],
+            'user' => null,
+            'password' => null,
+            'inviteCode' => null,
+        );
+        $emailTemplate = phpmEmailTemplate($emailTemplate);
+        $sendEmail = array(
+            'bcc' => $_POST['data']['bcc'],
+            'subject' => $emailTemplate['subject'],
+            'body' => phpmBuildEmail($emailTemplate),
+        );
+        return phpmSendEmail($sendEmail);
+    }
+    return false;
 }
-function phpmSendTestEmail(){
-	try {
-		$mail = new PHPMailer\PHPMailer\PHPMailer(true);
-		$mail->isSMTP();
-		//$mail->SMTPDebug = 3;
-		$mail->Host = $GLOBALS['PHPMAILER-smtpHost'];
-		$mail->Port = $GLOBALS['PHPMAILER-smtpHostPort'];
-		$mail->SMTPSecure = $GLOBALS['PHPMAILER-smtpHostType'];
-		$mail->SMTPAuth = $GLOBALS['PHPMAILER-smtpHostAuth'];
-		$mail->Username = $GLOBALS['PHPMAILER-smtpHostUsername'];
-		$mail->Password = decrypt($GLOBALS['PHPMAILER-smtpHostPassword']);
-		$mail->setFrom($GLOBALS['PHPMAILER-smtpHostSenderEmail'], $GLOBALS['PHPMAILER-smtpHostSenderName']);
-		$mail->addReplyTo($GLOBALS['PHPMAILER-smtpHostSenderEmail'], $GLOBALS['PHPMAILER-smtpHostSenderName']);
-		$mail->isHTML(true);
-		$mail->addAddress($GLOBALS['organizrUser']['email'], $GLOBALS['organizrUser']['username']);
-		$mail->Subject = "Organizr Test E-Mail";
-		$mail->Body    = "This was just a test!";
-		$mail->send();
-		writeLog('success', 'Mail Function -  E-Mail Test Sent', $GLOBALS['organizrUser']['username']);
-		return true;
-	} catch (PHPMailer\PHPMailer\Exception $e) {
-		writeLog('error', 'Mail Function -  E-Mail Test Failed['.$mail->ErrorInfo.']', $GLOBALS['organizrUser']['username']);
-		return $e->errorMessage();
-	}
-	return false;
+function phpmSendTestEmail()
+{
+    try {
+        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
+        $mail->isSMTP();
+        //$mail->SMTPDebug = 3;
+        $mail->Host = $GLOBALS['PHPMAILER-smtpHost'];
+        $mail->Port = $GLOBALS['PHPMAILER-smtpHostPort'];
+        $mail->SMTPSecure = $GLOBALS['PHPMAILER-smtpHostType'];
+        $mail->SMTPAuth = $GLOBALS['PHPMAILER-smtpHostAuth'];
+        $mail->Username = $GLOBALS['PHPMAILER-smtpHostUsername'];
+        $mail->Password = decrypt($GLOBALS['PHPMAILER-smtpHostPassword']);
+        $mail->setFrom($GLOBALS['PHPMAILER-smtpHostSenderEmail'], $GLOBALS['PHPMAILER-smtpHostSenderName']);
+        $mail->addReplyTo($GLOBALS['PHPMAILER-smtpHostSenderEmail'], $GLOBALS['PHPMAILER-smtpHostSenderName']);
+        $mail->isHTML(true);
+        $mail->addAddress($GLOBALS['organizrUser']['email'], $GLOBALS['organizrUser']['username']);
+        $mail->Subject = "Organizr Test E-Mail";
+        $mail->Body    = "This was just a test!";
+        $mail->send();
+        writeLog('success', 'Mail Function -  E-Mail Test Sent', $GLOBALS['organizrUser']['username']);
+        return true;
+    } catch (PHPMailer\PHPMailer\Exception $e) {
+        writeLog('error', 'Mail Function -  E-Mail Test Failed['.$mail->ErrorInfo.']', $GLOBALS['organizrUser']['username']);
+        return $e->errorMessage();
+    }
+    return false;
 }
-function phpmSendEmail($emailInfo){
-	$to = isset($emailInfo['to']) ? $emailInfo['to'] : null;
-	$cc = isset($emailInfo['cc']) ? $emailInfo['cc'] : null;
-	$bcc = isset($emailInfo['bcc']) ? $emailInfo['bcc'] : null;
-	$subject = isset($emailInfo['subject']) ? $emailInfo['subject'] : null;
-	$body = isset($emailInfo['body']) ? $emailInfo['body'] : null;
-	$username = isset($emailInfo['user']) ? $emailInfo['user'] : 'Organizr User';
+function phpmSendEmail($emailInfo)
+{
+    $to = isset($emailInfo['to']) ? $emailInfo['to'] : null;
+    $cc = isset($emailInfo['cc']) ? $emailInfo['cc'] : null;
+    $bcc = isset($emailInfo['bcc']) ? $emailInfo['bcc'] : null;
+    $subject = isset($emailInfo['subject']) ? $emailInfo['subject'] : null;
+    $body = isset($emailInfo['body']) ? $emailInfo['body'] : null;
+    $username = isset($emailInfo['user']) ? $emailInfo['user'] : 'Organizr User';
 
-	try {
-		$mail = new PHPMailer\PHPMailer\PHPMailer(true);
-		$mail->isSMTP();
-		//$mail->SMTPDebug = 3;
-		$mail->Host = $GLOBALS['PHPMAILER-smtpHost'];
-		$mail->Port = $GLOBALS['PHPMAILER-smtpHostPort'];
-		$mail->SMTPSecure = $GLOBALS['PHPMAILER-smtpHostType'];
-		$mail->SMTPAuth = $GLOBALS['PHPMAILER-smtpHostAuth'];
-		$mail->Username = $GLOBALS['PHPMAILER-smtpHostUsername'];
-		$mail->Password = decrypt($GLOBALS['PHPMAILER-smtpHostPassword']);
-		$mail->setFrom($GLOBALS['PHPMAILER-smtpHostSenderEmail'], $GLOBALS['PHPMAILER-smtpHostSenderName']);
-		$mail->addReplyTo($GLOBALS['PHPMAILER-smtpHostSenderEmail'], $GLOBALS['PHPMAILER-smtpHostSenderName']);
-		$mail->isHTML(true);
-		if($to){ $mail->addAddress($to, $username); }
-		if($cc){ $mail->addCC($cc); }
-		if($bcc){
-			if(strpos($bcc , ',') === false){
-				$mail->addBCC($bcc);
-			}else{
-				$allEmails = explode(",",$bcc);
-				foreach($allEmails as $gotEmail){
-					$mail->addBCC($gotEmail);
-				}
-			}
-		}
-		$mail->Subject = $subject;
-		$mail->Body    = $body;
-		$mail->send();
-		//writeLog('success', 'Mail Function -  E-Mail Test Sent', $GLOBALS['organizrUser']['username']);
-		return true;
-	} catch (PHPMailer\PHPMailer\Exception $e) {
-		writeLog('error', 'Mail Function -  E-Mail Test Failed['.$mail->ErrorInfo.']', $GLOBALS['organizrUser']['username']);
-		return $e->errorMessage();
-	}
-	return false;
+    try {
+        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
+        $mail->isSMTP();
+        //$mail->SMTPDebug = 3;
+        $mail->Host = $GLOBALS['PHPMAILER-smtpHost'];
+        $mail->Port = $GLOBALS['PHPMAILER-smtpHostPort'];
+        $mail->SMTPSecure = $GLOBALS['PHPMAILER-smtpHostType'];
+        $mail->SMTPAuth = $GLOBALS['PHPMAILER-smtpHostAuth'];
+        $mail->Username = $GLOBALS['PHPMAILER-smtpHostUsername'];
+        $mail->Password = decrypt($GLOBALS['PHPMAILER-smtpHostPassword']);
+        $mail->setFrom($GLOBALS['PHPMAILER-smtpHostSenderEmail'], $GLOBALS['PHPMAILER-smtpHostSenderName']);
+        $mail->addReplyTo($GLOBALS['PHPMAILER-smtpHostSenderEmail'], $GLOBALS['PHPMAILER-smtpHostSenderName']);
+        $mail->isHTML(true);
+        if ($to) {
+            $mail->addAddress($to, $username);
+        }
+        if ($cc) {
+            $mail->addCC($cc);
+        }
+        if ($bcc) {
+            if (strpos($bcc, ',') === false) {
+                $mail->addBCC($bcc);
+            } else {
+                $allEmails = explode(",", $bcc);
+                foreach ($allEmails as $gotEmail) {
+                    $mail->addBCC($gotEmail);
+                }
+            }
+        }
+        $mail->Subject = $subject;
+        $mail->Body    = $body;
+        $mail->send();
+        //writeLog('success', 'Mail Function -  E-Mail Test Sent', $GLOBALS['organizrUser']['username']);
+        return true;
+    } catch (PHPMailer\PHPMailer\Exception $e) {
+        writeLog('error', 'Mail Function -  E-Mail Test Failed['.$mail->ErrorInfo.']', $GLOBALS['organizrUser']['username']);
+        return $e->errorMessage();
+    }
+    return false;
 }
 /* GET PHPMAILER SETTINGS */
-function phpmGetSettings(){
-	return array(
-		'Host' => array(
-			array(
-				'type' => 'input',
-				'name' => 'PHPMAILER-smtpHost',
-				'label' => 'SMTP Host',
-				'value' => $GLOBALS['PHPMAILER-smtpHost']
-			),
-			array(
-				'type' => 'input',
-				'name' => 'PHPMAILER-smtpHostPort',
-				'label' => 'SMTP Port',
-				'value' => $GLOBALS['PHPMAILER-smtpHostPort']
-			)
-		),
-		'Authentication' => array(
-			array(
-				'type' => 'input',
-				'name' => 'PHPMAILER-smtpHostUsername',
-				'label' => 'Username',
-				'value' => $GLOBALS['PHPMAILER-smtpHostUsername']
-			),
-			array(
-				'type' => 'password',
-				'name' => 'PHPMAILER-smtpHostPassword',
-				'label' => 'Password',
-				'value' => $GLOBALS['PHPMAILER-smtpHostPassword']
-			),
-			array(
-				'type' => 'switch',
-				'name' => 'PHPMAILER-smtpHostAuth',
-				'label' => 'Authentication',
-				'value' => $GLOBALS['PHPMAILER-smtpHostAuth']
-			),
-			array(
-				'type' => 'select',
-				'name' => 'PHPMAILER-smtpHostType',
-				'label' => 'Authentication Type',
-				'value' => $GLOBALS['PHPMAILER-smtpHostType'],
-				'options' => array(
-					array(
-						'name'=>'tls',
-						'value'=>'tls'
-					),
-					array(
-						'name'=>'ssl',
-						'value'=>'ssl'
-					),
-					array(
-						'name'=>'off',
-						'value'=>'false'
-					)
-				)
-			)
-		),
-		'Sender Information' => array(
-			array(
-				'type' => 'input',
-				'name' => 'PHPMAILER-smtpHostSenderName',
-				'label' => 'Sender Name',
-				'value' => $GLOBALS['PHPMAILER-smtpHostSenderName']
-			),
-			array(
-				'type' => 'input',
-				'name' => 'PHPMAILER-smtpHostSenderEmail',
-				'label' => 'Sender Email',
-				'value' => $GLOBALS['PHPMAILER-smtpHostSenderEmail'],
-				'placeholder' => 'i.e. same as username'
-			)
-		),
-		'Test & Options' => array(
-			array(
-				'type' => 'button',
-				'label' => 'Send Test',
-				'class' => 'phpmSendTestEmail',
-				'icon' => 'fa fa-paper-plane',
-				'text' => 'Send'
-			),
-			array(
-				'type' => 'input',
-				'name' => 'PHPMAILER-domain',
-				'label' => 'Domain Link Override',
-				'value' => $GLOBALS['PHPMAILER-domain'],
-				'placeholder' => 'https://domain.com/',
-			),
-			array(
-				'type' => 'select',
-				'name' => 'PHPMAILER-template',
-				'label' => 'Theme',
-				'value' => $GLOBALS['PHPMAILER-template'],
-				'options' => getTemplates()
-			),
-			array(
-				'type' => 'input',
-				'name' => 'PHPMAILER-logo',
-				'label' => 'WAN Logo URL',
-				'value' => $GLOBALS['PHPMAILER-logo'],
-				'placeholder' => 'Full URL',
-			),
-			array(
-				'type' => 'switch',
-				'name' => 'PHPMAILER-emailTemplateRegisterUserEnabled',
-				'label' => 'Send Welcome E-Mail',
-				'value' => $GLOBALS['PHPMAILER-emailTemplateRegisterUserEnabled'],
-			),
-		),
-		'Templates' => array(
-			array(
-				'type' => 'accordion',
-				'label' => 'Edit Template',
-				'id' => 'customEmailTemplates',
-				'override' => 12,
-				'options' => array(
-					array(
-						'id' => 'PHPMAILER-emailTemplateRegisterUserForm',
-						'header' => 'New Registration',
-						'body' => array(
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateRegisterUserSubject',
-								'smallLabel' => 'Subject',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateRegisterUserSubject'],
-							),
-							array(
-								'type' => 'textbox',
-								'name' => 'PHPMAILER-emailTemplateRegisterUser',
-								'smallLabel' => 'Body',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateRegisterUser'],
-								'attr' => 'rows="10"',
-							)
-						)
-					),
-					array(
-						'id' => 'PHPMAILER-emailTemplateResetPasswordForm',
-						'header' => 'Reset Password',
-						'body' => array(
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateResetPasswordSubject',
-								'smallLabel' => 'Subject',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateResetPasswordSubject'],
-							),
-							array(
-								'type' => 'textbox',
-								'name' => 'PHPMAILER-emailTemplateResetPassword',
-								'smallLabel' => 'Body',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateResetPassword'],
-								'attr' => 'rows="10"',
-							)
-						)
-					),
-					array(
-						'id' => 'PHPMAILER-emailTemplateInviteUserForm',
-						'header' => 'Invite User',
-						'body' => array(
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateInviteUserSubject',
-								'smallLabel' => 'Subject',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateInviteUserSubject'],
-							),
-							array(
-								'type' => 'textbox',
-								'name' => 'PHPMAILER-emailTemplateInviteUser',
-								'smallLabel' => 'Body',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateInviteUser'],
-								'attr' => 'rows="10"',
-							)
-						)
-					),
-					array(
-						'id' => 'PHPMAILER-emailTemplateCustom-include-OneForm',
-						'header' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-OneName'],
-						'body' => array(
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-OneName',
-								'smallLabel' => 'Name',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-OneName'],
-							),
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-OneSubject',
-								'smallLabel' => 'Subject',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-OneSubject'],
-							),
-							array(
-								'type' => 'textbox',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-One',
-								'smallLabel' => 'Body',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-One'],
-								'attr' => 'rows="10"',
-							)
-						)
-					),
-					array(
-						'id' => 'PHPMAILER-emailTemplateCustom-include-TwoForm',
-						'header' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-TwoName'],
-						'body' => array(
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-TwoName',
-								'smallLabel' => 'Name',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-TwoName'],
-							),
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-TwoSubject',
-								'smallLabel' => 'Subject',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-TwoSubject'],
-							),
-							array(
-								'type' => 'textbox',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-Two',
-								'smallLabel' => 'Body',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-Two'],
-								'attr' => 'rows="10"',
-							)
-						)
-					),
-					array(
-						'id' => 'PHPMAILER-emailTemplateCustom-include-ThreeForm',
-						'header' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-ThreeName'],
-						'body' => array(
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-ThreeName',
-								'smallLabel' => 'Name',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-ThreeName'],
-							),
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-ThreeSubject',
-								'smallLabel' => 'Subject',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-ThreeSubject'],
-							),
-							array(
-								'type' => 'textbox',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-Three',
-								'smallLabel' => 'Body',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-Three'],
-								'attr' => 'rows="10"',
-							)
-						)
-					),
-					array(
-						'id' => 'PHPMAILER-emailTemplateCustom-include-FourForm',
-						'header' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-FourName'],
-						'body' => array(
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-FourName',
-								'smallLabel' => 'Name',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-FourName'],
-							),
-							array(
-								'type' => 'input',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-FourSubject',
-								'smallLabel' => 'Subject',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-FourSubject'],
-							),
-							array(
-								'type' => 'textbox',
-								'name' => 'PHPMAILER-emailTemplateCustom-include-Four',
-								'smallLabel' => 'Body',
-								'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-Four'],
-								'attr' => 'rows="10"',
-							)
-						)
-					),
-				)
-			)
-		)
-	);
+function phpmGetSettings()
+{
+    return array(
+        'Host' => array(
+            array(
+                'type' => 'input',
+                'name' => 'PHPMAILER-smtpHost',
+                'label' => 'SMTP Host',
+                'value' => $GLOBALS['PHPMAILER-smtpHost']
+            ),
+            array(
+                'type' => 'input',
+                'name' => 'PHPMAILER-smtpHostPort',
+                'label' => 'SMTP Port',
+                'value' => $GLOBALS['PHPMAILER-smtpHostPort']
+            )
+        ),
+        'Authentication' => array(
+            array(
+                'type' => 'input',
+                'name' => 'PHPMAILER-smtpHostUsername',
+                'label' => 'Username',
+                'value' => $GLOBALS['PHPMAILER-smtpHostUsername']
+            ),
+            array(
+                'type' => 'password',
+                'name' => 'PHPMAILER-smtpHostPassword',
+                'label' => 'Password',
+                'value' => $GLOBALS['PHPMAILER-smtpHostPassword']
+            ),
+            array(
+                'type' => 'switch',
+                'name' => 'PHPMAILER-smtpHostAuth',
+                'label' => 'Authentication',
+                'value' => $GLOBALS['PHPMAILER-smtpHostAuth']
+            ),
+            array(
+                'type' => 'select',
+                'name' => 'PHPMAILER-smtpHostType',
+                'label' => 'Authentication Type',
+                'value' => $GLOBALS['PHPMAILER-smtpHostType'],
+                'options' => array(
+                    array(
+                        'name'=>'tls',
+                        'value'=>'tls'
+                    ),
+                    array(
+                        'name'=>'ssl',
+                        'value'=>'ssl'
+                    ),
+                    array(
+                        'name'=>'off',
+                        'value'=>'false'
+                    )
+                )
+            )
+        ),
+        'Sender Information' => array(
+            array(
+                'type' => 'input',
+                'name' => 'PHPMAILER-smtpHostSenderName',
+                'label' => 'Sender Name',
+                'value' => $GLOBALS['PHPMAILER-smtpHostSenderName']
+            ),
+            array(
+                'type' => 'input',
+                'name' => 'PHPMAILER-smtpHostSenderEmail',
+                'label' => 'Sender Email',
+                'value' => $GLOBALS['PHPMAILER-smtpHostSenderEmail'],
+                'placeholder' => 'i.e. same as username'
+            )
+        ),
+        'Test & Options' => array(
+            array(
+                'type' => 'button',
+                'label' => 'Send Test',
+                'class' => 'phpmSendTestEmail',
+                'icon' => 'fa fa-paper-plane',
+                'text' => 'Send'
+            ),
+            array(
+                'type' => 'input',
+                'name' => 'PHPMAILER-domain',
+                'label' => 'Domain Link Override',
+                'value' => $GLOBALS['PHPMAILER-domain'],
+                'placeholder' => 'https://domain.com/',
+            ),
+            array(
+                'type' => 'select',
+                'name' => 'PHPMAILER-template',
+                'label' => 'Theme',
+                'value' => $GLOBALS['PHPMAILER-template'],
+                'options' => getTemplates()
+            ),
+            array(
+                'type' => 'input',
+                'name' => 'PHPMAILER-logo',
+                'label' => 'WAN Logo URL',
+                'value' => $GLOBALS['PHPMAILER-logo'],
+                'placeholder' => 'Full URL',
+            ),
+            array(
+                'type' => 'switch',
+                'name' => 'PHPMAILER-emailTemplateRegisterUserEnabled',
+                'label' => 'Send Welcome E-Mail',
+                'value' => $GLOBALS['PHPMAILER-emailTemplateRegisterUserEnabled'],
+            ),
+        ),
+        'Templates' => array(
+            array(
+                'type' => 'accordion',
+                'label' => 'Edit Template',
+                'id' => 'customEmailTemplates',
+                'override' => 12,
+                'options' => array(
+                    array(
+                        'id' => 'PHPMAILER-emailTemplateRegisterUserForm',
+                        'header' => 'New Registration',
+                        'body' => array(
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateRegisterUserSubject',
+                                'smallLabel' => 'Subject',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateRegisterUserSubject'],
+                            ),
+                            array(
+                                'type' => 'textbox',
+                                'name' => 'PHPMAILER-emailTemplateRegisterUser',
+                                'smallLabel' => 'Body',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateRegisterUser'],
+                                'attr' => 'rows="10"',
+                            )
+                        )
+                    ),
+                    array(
+                        'id' => 'PHPMAILER-emailTemplateResetPasswordForm',
+                        'header' => 'Reset Password',
+                        'body' => array(
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateResetPasswordSubject',
+                                'smallLabel' => 'Subject',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateResetPasswordSubject'],
+                            ),
+                            array(
+                                'type' => 'textbox',
+                                'name' => 'PHPMAILER-emailTemplateResetPassword',
+                                'smallLabel' => 'Body',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateResetPassword'],
+                                'attr' => 'rows="10"',
+                            )
+                        )
+                    ),
+                    array(
+                        'id' => 'PHPMAILER-emailTemplateInviteUserForm',
+                        'header' => 'Invite User',
+                        'body' => array(
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateInviteUserSubject',
+                                'smallLabel' => 'Subject',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateInviteUserSubject'],
+                            ),
+                            array(
+                                'type' => 'textbox',
+                                'name' => 'PHPMAILER-emailTemplateInviteUser',
+                                'smallLabel' => 'Body',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateInviteUser'],
+                                'attr' => 'rows="10"',
+                            )
+                        )
+                    ),
+                    array(
+                        'id' => 'PHPMAILER-emailTemplateCustom-include-OneForm',
+                        'header' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-OneName'],
+                        'body' => array(
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-OneName',
+                                'smallLabel' => 'Name',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-OneName'],
+                            ),
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-OneSubject',
+                                'smallLabel' => 'Subject',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-OneSubject'],
+                            ),
+                            array(
+                                'type' => 'textbox',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-One',
+                                'smallLabel' => 'Body',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-One'],
+                                'attr' => 'rows="10"',
+                            )
+                        )
+                    ),
+                    array(
+                        'id' => 'PHPMAILER-emailTemplateCustom-include-TwoForm',
+                        'header' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-TwoName'],
+                        'body' => array(
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-TwoName',
+                                'smallLabel' => 'Name',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-TwoName'],
+                            ),
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-TwoSubject',
+                                'smallLabel' => 'Subject',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-TwoSubject'],
+                            ),
+                            array(
+                                'type' => 'textbox',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-Two',
+                                'smallLabel' => 'Body',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-Two'],
+                                'attr' => 'rows="10"',
+                            )
+                        )
+                    ),
+                    array(
+                        'id' => 'PHPMAILER-emailTemplateCustom-include-ThreeForm',
+                        'header' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-ThreeName'],
+                        'body' => array(
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-ThreeName',
+                                'smallLabel' => 'Name',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-ThreeName'],
+                            ),
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-ThreeSubject',
+                                'smallLabel' => 'Subject',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-ThreeSubject'],
+                            ),
+                            array(
+                                'type' => 'textbox',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-Three',
+                                'smallLabel' => 'Body',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-Three'],
+                                'attr' => 'rows="10"',
+                            )
+                        )
+                    ),
+                    array(
+                        'id' => 'PHPMAILER-emailTemplateCustom-include-FourForm',
+                        'header' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-FourName'],
+                        'body' => array(
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-FourName',
+                                'smallLabel' => 'Name',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-FourName'],
+                            ),
+                            array(
+                                'type' => 'input',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-FourSubject',
+                                'smallLabel' => 'Subject',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-FourSubject'],
+                            ),
+                            array(
+                                'type' => 'textbox',
+                                'name' => 'PHPMAILER-emailTemplateCustom-include-Four',
+                                'smallLabel' => 'Body',
+                                'value' => $GLOBALS['PHPMAILER-emailTemplateCustom-include-Four'],
+                                'attr' => 'rows="10"',
+                            )
+                        )
+                    ),
+                )
+            )
+        )
+    );
 }

+ 20 - 19
api/plugins/speedTest.php

@@ -3,18 +3,18 @@
 // PLUGIN INFORMATION
 $GLOBALS['plugins'][]['SpeedTest'] = array( // Plugin Name
     'name'=>'SpeedTest', // Plugin Name
-	'author'=>'CauseFX', // Who wrote the plugin
+    'author'=>'CauseFX', // Who wrote the plugin
     'category'=>'Utilities', // One to Two Word Description
     'link'=>'https://github.com/PHPMailer/PHPMailer', // Link to plugin info
-	'license'=>'personal,business', // License Type use , for multiple
+    'license'=>'personal,business', // License Type use , for multiple
     //'fileName'=>'php-mailer.php',
-	//'configFile'=>'php-mailer.php',
-	//'apiFile'=>'php-mailer.php',
-	'idPrefix'=>'SPEEDTEST', // html element id prefix
-	'configPrefix'=>'SPEEDTEST', // config file prefix for array items without the hypen
+    //'configFile'=>'php-mailer.php',
+    //'apiFile'=>'php-mailer.php',
+    'idPrefix'=>'SPEEDTEST', // html element id prefix
+    'configPrefix'=>'SPEEDTEST', // config file prefix for array items without the hypen
     'version'=>'1.0.0', // SemVer of plugin
     'image'=>'plugins/images/speedtest.png', // 1:1 non transparent image for plugin
-	'settings'=>true, // does plugin need a settings page? true or false
+    'settings'=>true, // does plugin need a settings page? true or false
     'homepage'=>false // Is plugin for use on homepage? true or false
 );
 // INCLUDE/REQUIRE FILES
@@ -22,16 +22,17 @@ $GLOBALS['plugins'][]['SpeedTest'] = array( // Plugin Name
 // PLUGIN FUNCTIONS
 
 /* GET PHPMAILER SETTINGS */
-function speedTestGetSettings(){
-	return array(
-		'Options' => array(
-			array(
-				'type' => 'select',
-				'name' => 'SPEEDTEST-Auth-include',
-				'label' => 'Minimum Authentication',
-				'value' => $GLOBALS['SPEEDTEST-Auth-include'],
-				'options' => groupSelect()
-			)
-		)
-	);
+function speedTestGetSettings()
+{
+    return array(
+        'Options' => array(
+            array(
+                'type' => 'select',
+                'name' => 'SPEEDTEST-Auth-include',
+                'label' => 'Minimum Authentication',
+                'value' => $GLOBALS['SPEEDTEST-Auth-include'],
+                'options' => groupSelect()
+            )
+        )
+    );
 }

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini