ソースを参照

update all plugin files

CauseFX 5 年 前
コミット
b6880c6456

+ 191 - 56
api/plugins/api/chat.php

@@ -1,59 +1,194 @@
 <?php
-if (isset($_POST['data']['plugin'])) {
-	switch ($_POST['data']['plugin']) {
-		case 'chat/settings/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = chatGetSettings();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		case 'chat/message':
-			if (qualifyRequest($GLOBALS['CHAT-Auth-include'])) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = sendChatMessage($_POST);
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		default:
-			//DO NOTHING!!!
-			break;
+/**
+ * @OA\Tag(
+ *     name="plugins-chat",
+ *     description="Pusher Chat Plugin"
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="getChatMessages",
+ *     type="object",
+ *     @OA\Property(
+ *      property="response",
+ *      type="object",
+ *      @OA\Property(
+ *          property="result",
+ *          description="success or error",
+ *          type="string",
+ *          example="success",
+ *      ),
+ *      @OA\Property(
+ *          property="message",
+ *          description="success or error message",
+ *          type="string",
+ *          example=null,
+ *      ),
+ *      @OA\Property(
+ *          property="data",
+ *          description="data from api",
+ *          type="array",
+ *          @OA\Items({
+ *          @OA\Property(
+ *              property="username",
+ *              type="string",
+ *              example="causefx",
+ *          ),
+ *          @OA\Property(
+ *              property="date",
+ *              type="string",
+ *              example="2018-09-01 02:02:24",
+ *          ),
+ *          @OA\Property(
+ *              property="gravatar",
+ *              type="string",
+ *              example="https://www.gravatar.com/avatar/a47c4a4b915ddf9601cd228f890bc366?s=100&d=mm",
+ *          ),
+ *          @OA\Property(
+ *              property="message",
+ *              type="string",
+ *              example="ok first message!",
+ *          ),
+ *          @OA\Property(
+ *              property="uid",
+ *              type="string",
+ *              example="f5287",
+ *          )
+ * })
+ *      ),
+ *  ),
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="submitMessageData",
+ *     type="object",
+ *     @OA\Property(
+ *      property="message",
+ *      type="string",
+ *      example="This is my message"
+ *  ),
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="submitMessage",
+ *     type="object",
+ *     @OA\Property(
+ *      property="response",
+ *      type="object",
+ *      @OA\Property(
+ *          property="result",
+ *          description="success or error",
+ *          type="string",
+ *          example="success",
+ *      ),
+ *      @OA\Property(
+ *          property="message",
+ *          description="success or error message",
+ *          type="string",
+ *          example="message has been accepted",
+ *      ),
+ *      @OA\Property(
+ *          property="data",
+ *          description="data from api",
+ *          type="string",
+ *          example=null,
+ *      ),
+ *  ),
+ * )
+ */
+$app->get('/plugins/chat/settings', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-chat"},
+	 *     path="/api/v2/plugins/chat/settings",
+	 *     summary="Get settings",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/pluginSettingsPage"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$Chat = new Chat();
+	if ($Chat->checkRoute($request)) {
+		if ($Chat->qualifyRequest(1, true)) {
+			$GLOBALS['api']['response']['data'] = $Chat->_chatPluginGetSettings();
+		}
 	}
-}
-if (isset($_GET['plugin']) && $_GET['plugin'] == 'chat' && isset($_GET['cmd'])) {
-	switch ($_GET['cmd']) {
-		case 'chat/settings/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = chatGetSettings();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		case 'chat/message':
-			if (qualifyRequest($GLOBALS['CHAT-Auth-include'])) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = getChatMessage();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		default:
-			//Do NOTHING!
-			break;
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->get('/plugins/chat/message', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-chat"},
+	 *     path="/api/v2/plugins/chat/message",
+	 *     summary="Get all messages",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/getChatMessages"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$Chat = new Chat();
+	if ($Chat->checkRoute($request)) {
+		if ($Chat->qualifyRequest($Chat->config['CHAT-Auth-include'], true)) {
+			$GLOBALS['api']['response']['data'] = $Chat->_chatPluginGetChatMessages();
+		}
 	}
-}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->post('/plugins/chat/message', function ($request, $response, $args) {
+	/**
+	 * @OA\Post(
+	 *     tags={"plugins-chat"},
+	 *     path="/api/v2/plugins/chat/message",
+	 *     summary="Submit a message",
+	 *     @OA\RequestBody(
+	 *      description="Success",
+	 *      required=true,
+	 *      @OA\JsonContent(ref="#/components/schemas/submitMessageData"),
+	 *      @OA\MediaType(
+	 *          mediaType="application/x-www-form-urlencoded",
+	 *          @OA\Schema(
+	 *              type="object",
+	 *              @OA\Property(
+	 *                  property="message",
+	 *                  description="message to send",
+	 *                  type="string",
+	 *              )
+	 *          )
+	 *      )
+	 *     ),
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/submitMessage"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$Chat = new Chat();
+	if ($Chat->checkRoute($request)) {
+		if ($Chat->qualifyRequest($Chat->config['CHAT-Auth-include'], true)) {
+			$Chat->_chatPluginSendChatMessage($Chat->apiData($request));
+		}
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});

+ 127 - 56
api/plugins/api/healthChecks.php

@@ -1,59 +1,130 @@
 <?php
-if (isset($_POST['data']['plugin'])) {
-	switch ($_POST['data']['plugin']) {
-		case 'HealthChecks/settings/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = healthCheckGetSettings();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		case 'HealthChecks/run':
-			if (qualifyRequest($GLOBALS['HEALTHCHECKS-Auth-include'])) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = healthCheckRun();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		default:
-			//DO NOTHING!!
-			break;
+/**
+ * @OA\Tag(
+ *     name="plugins-healthchecks",
+ *     description="Healthchecks.io Ping Plugin"
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="healthChecksRun",
+ *     type="object",
+ *     @OA\Property(
+ *      property="response",
+ *      type="object",
+ *      @OA\Property(
+ *          property="result",
+ *          description="success or error",
+ *          type="string",
+ *          example="success",
+ *      ),
+ *      @OA\Property(
+ *          property="message",
+ *          description="success or error message",
+ *          type="string",
+ *          example=null,
+ *      ),
+ *      @OA\Property(
+ *          property="data",
+ *          description="data from api",
+ *          type="array",
+ *          @OA\Items({
+ *          @OA\Property(
+ *              property="Service Name",
+ *              type="string",
+ *              example="Radarr",
+ *          ),
+ *          @OA\Property(
+ *              property="UUID",
+ *              type="string",
+ *              example="883f0097-8f4c-4ca5-a9cf-053cfab8e334",
+ *          ),
+ *          @OA\Property(
+ *              property="External URL",
+ *              type="string",
+ *              example="https://radarr.com",
+ *          ),
+ *          @OA\Property(
+ *              property="Internal URL",
+ *              type="string",
+ *              example="http://radarr:7878",
+ *          ),
+ *          @OA\Property(
+ *              property="Enabled",
+ *              type="string",
+ *              example="true",
+ *          ),
+ *          @OA\Property(
+ *              property="results",
+ *              type="array",
+ *              @OA\Items({
+ *                  @OA\Property(
+ *                      property="internal",
+ *                      type="string",
+ *                      example="Success",
+ *                  ),
+ *                  @OA\Property(
+ *                      property="external",
+ *                      type="string",
+ *                      example="Success",
+ *                  ),
+ *
+ *              }),
+ *          ),
+ * })
+ *      ),
+ *  ),
+ * )
+ */
+$app->get('/plugins/healthchecks/settings', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-healthchecks"},
+	 *     path="/api/v2/plugins/healthchecks/settings",
+	 *     summary="Get settings",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/pluginSettingsPage"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$HealthChecks = new HealthChecks();
+	if ($HealthChecks->checkRoute($request)) {
+		if ($HealthChecks->qualifyRequest(1, true)) {
+			$GLOBALS['api']['response']['data'] = $HealthChecks->_healthCheckPluginGetSettings();
+		}
 	}
-}
-if (isset($_GET['plugin']) && $_GET['plugin'] == 'HealthChecks' && isset($_GET['cmd'])) {
-	switch ($_GET['cmd']) {
-		case 'HealthChecks/settings/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = healthCheckGetSettings();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		case 'HealthChecks/run':
-			if (qualifyRequest($GLOBALS['HEALTHCHECKS-Auth-include'])) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = healthCheckRun();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		default:
-			//Do NOTHING!
-			break;
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->get('/plugins/healthchecks/run', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-healthchecks"},
+	 *     path="/api/v2/plugins/healthchecks/run",
+	 *     summary="Run Healthchecks.io plugin",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/healthChecksRun"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$HealthChecks = new HealthChecks();
+	if ($HealthChecks->checkRoute($request)) {
+		if ($HealthChecks->qualifyRequest($HealthChecks->config['HEALTHCHECKS-Auth-include'], true)) {
+			$HealthChecks->_healthCheckPluginRun();
+		}
 	}
-}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});

+ 379 - 39
api/plugins/api/invites.php

@@ -1,42 +1,382 @@
 <?php
-if (isset($_POST['data']['plugin'])) {
-	switch ($_POST['data']['plugin']) {
-		case 'Invites/settings/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = invitesGetSettings();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		case 'Invites/codes':
-			$result['status'] = 'success';
-			$result['statusText'] = 'success';
-			$result['data'] = inviteCodes($_POST);
-			break;
-		default:
-			//DO NOTHING!!
-			break;
+/**
+ * @OA\Tag(
+ *     name="plugins-invites",
+ *     description="Media Invite Plugin"
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="getInvites",
+ *     type="object",
+ *     @OA\Property(
+ *      property="response",
+ *      type="object",
+ *      @OA\Property(
+ *          property="result",
+ *          description="success or error",
+ *          type="string",
+ *          example="success",
+ *      ),
+ *      @OA\Property(
+ *          property="message",
+ *          description="success or error message",
+ *          type="string",
+ *          example=null,
+ *      ),
+ *      @OA\Property(
+ *          property="data",
+ *          description="data from api",
+ *          type="array",
+ *          @OA\Items({
+ *          @OA\Property(
+ *              property="id",
+ *              type="number",
+ *              example=1,
+ *          ),
+ *          @OA\Property(
+ *              property="code",
+ *              type="string",
+ *              example="NN9JH9",
+ *          ),
+ *          @OA\Property(
+ *              property="date",
+ *              type="string",
+ *              example="2018-09-01 02:02:24",
+ *          ),
+ *          @OA\Property(
+ *              property="email",
+ *              type="string",
+ *              example="causefX@organizr.app",
+ *          ),
+ *          @OA\Property(
+ *              property="username",
+ *              type="string",
+ *              example="causefx",
+ *          ),
+ *          @OA\Property(
+ *              property="dateused",
+ *              type="string",
+ *              example="2018-09-01 02:02:24",
+ *          ),
+ *          @OA\Property(
+ *              property="usedby",
+ *              type="string",
+ *              example="causefx",
+ *          ),
+ *          @OA\Property(
+ *              property="ip",
+ *              type="string",
+ *              example="10.0.0.0",
+ *          ),
+ *          @OA\Property(
+ *              property="valid",
+ *              type="string",
+ *              example="No",
+ *          ),
+ *          @OA\Property(
+ *              property="type",
+ *              type="string",
+ *              example="Plex",
+ *          )
+ * })
+ *      ),
+ *  ),
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="createInviteCode",
+ *     type="object",
+ *     @OA\Property(
+ *      property="response",
+ *      type="object",
+ *      @OA\Property(
+ *          property="result",
+ *          description="success or error",
+ *          type="string",
+ *          example="success",
+ *      ),
+ *      @OA\Property(
+ *          property="message",
+ *          description="success or error message",
+ *          type="string",
+ *          example="Invite Code: XYXYXY has been created",
+ *      ),
+ *      @OA\Property(
+ *          property="data",
+ *          description="data from api",
+ *          type="string",
+ *          example=null,
+ *      ),
+ *  ),
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="verifyInviteCode",
+ *     type="object",
+ *     @OA\Property(
+ *      property="response",
+ *      type="object",
+ *      @OA\Property(
+ *          property="result",
+ *          description="success or error",
+ *          type="string",
+ *          example="success",
+ *      ),
+ *      @OA\Property(
+ *          property="message",
+ *          description="success or error message",
+ *          type="string",
+ *          example="Code has been verified",
+ *      ),
+ *      @OA\Property(
+ *          property="data",
+ *          description="data from api",
+ *          type="string",
+ *          example=null,
+ *      ),
+ *  ),
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="useInviteCode",
+ *     type="object",
+ *     @OA\Property(
+ *      property="response",
+ *      type="object",
+ *      @OA\Property(
+ *          property="result",
+ *          description="success or error",
+ *          type="string",
+ *          example="success",
+ *      ),
+ *      @OA\Property(
+ *          property="message",
+ *          description="success or error message",
+ *          type="string",
+ *          example="Plex/Emby User now has access to system",
+ *      ),
+ *      @OA\Property(
+ *          property="data",
+ *          description="data from api",
+ *          type="string",
+ *          example=null,
+ *      ),
+ *  ),
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="deleteInviteCode",
+ *     type="object",
+ *     @OA\Property(
+ *      property="response",
+ *      type="object",
+ *      @OA\Property(
+ *          property="result",
+ *          description="success or error",
+ *          type="string",
+ *          example="success",
+ *      ),
+ *      @OA\Property(
+ *          property="message",
+ *          description="success or error message",
+ *          type="string",
+ *          example="Code has been deleted",
+ *      ),
+ *      @OA\Property(
+ *          property="data",
+ *          description="data from api",
+ *          type="string",
+ *          example=null,
+ *      ),
+ *  ),
+ * )
+ */
+$app->get('/plugins/invites/settings', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-invites"},
+	 *     path="/api/v2/plugins/invites/settings",
+	 *     summary="Get settings",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/pluginSettingsPage"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$Invites = new Invites();
+	if ($Invites->checkRoute($request)) {
+		if ($Invites->qualifyRequest(1, true)) {
+			$GLOBALS['api']['response']['data'] = $Invites->_invitesPluginGetSettings();
+		}
 	}
-}
-if (isset($_GET['plugin']) && $_GET['plugin'] == 'Invites' && isset($_GET['cmd'])) {
-	switch ($_GET['cmd']) {
-		case 'Invites/settings/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = invitesGetSettings();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		default:
-			//Do NOTHING!
-			break;
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->get('/plugins/invites', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-invites"},
+	 *     path="/api/v2/plugins/invites",
+	 *     summary="Get All Invites",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/getInvites"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$Invites = new Invites();
+	if ($Invites->checkRoute($request)) {
+		if ($Invites->qualifyRequest(1, true)) {
+			$GLOBALS['api']['response']['data'] = $Invites->_invitesPluginGetCodes();
+		}
 	}
-}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->post('/plugins/invites', function ($request, $response, $args) {
+	/**
+	 * @OA\Post(
+	 *     tags={"plugins-invites"},
+	 *     path="/api/v2/plugins/invites",
+	 *     summary="Create Invite Code",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/createInviteCode"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$Invites = new Invites();
+	if ($Invites->checkRoute($request)) {
+		if ($Invites->qualifyRequest(1, true)) {
+			$Invites->_invitesPluginCreateCode($Invites->apiData($request));
+		}
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->get('/plugins/invites/{code}', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-invites"},
+	 *     path="/api/v2/plugins/invites/{code}",
+	 *     summary="Verify Invite Code",
+	 *     @OA\Parameter(
+	 *      name="code",
+	 *      description="The Invite Code",
+	 *      @OA\Schema(
+	 *          type="integer",
+	 *          format="int64",
+	 *      ),
+	 *      in="path",
+	 *      required=true
+	 *      ),
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/verifyInviteCode"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized")
+	 * )
+	 */
+	$Invites = new Invites();
+	if ($Invites->checkRoute($request)) {
+		if ($Invites->qualifyRequest(999, true)) {
+			$Invites->_invitesPluginVerifyCode($args['code']);
+		}
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->post('/plugins/invites/{code}', function ($request, $response, $args) {
+	/**
+	 * @OA\Post(
+	 *     tags={"plugins-invites"},
+	 *     path="/api/v2/plugins/invites/{code}",
+	 *     summary="Use Invite Code",
+	 *     @OA\Parameter(
+	 *      name="code",
+	 *      description="The Invite Code",
+	 *      @OA\Schema(
+	 *          type="integer",
+	 *          format="int64",
+	 *      ),
+	 *      in="path",
+	 *      required=true
+	 *      ),
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/useInviteCode"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized")
+	 * )
+	 */
+	$Invites = new Invites();
+	if ($Invites->checkRoute($request)) {
+		if ($Invites->qualifyRequest(999, true)) {
+			$Invites->_invitesPluginUseCode($args['code'], $Invites->apiData($request));
+		}
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->delete('/plugins/invites/{code}', function ($request, $response, $args) {
+	/**
+	 * @OA\Delete(
+	 *     tags={"plugins-invites"},
+	 *     path="/api/v2/plugins/invites/{code}",
+	 *     summary="Delete Invite Code",
+	 *     @OA\Parameter(
+	 *      name="code",
+	 *      description="The Invite Code",
+	 *      @OA\Schema(
+	 *          type="integer",
+	 *          format="int64",
+	 *      ),
+	 *      in="path",
+	 *      required=true
+	 *      ),
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/deleteInviteCode"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$Invites = new Invites();
+	if ($Invites->checkRoute($request)) {
+		if ($Invites->qualifyRequest(1, true)) {
+			$Invites->_invitesPluginDeleteCode($args['code']);
+		}
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});

+ 135 - 67
api/plugins/api/php-mailer.php

@@ -1,70 +1,138 @@
 <?php
-if (isset($_POST['data']['plugin'])) {
-	switch ($_POST['data']['plugin']) {
-		case 'PHPMailer/settings/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = phpmGetSettings();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		case 'PHPMailer/send/test':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = phpmSendTestEmail();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		case 'PHPMailer/send/email':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = phpmAdminSendEmail();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		case 'PHPMailer/users/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = getEmails();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		default:
-			//DO NOTHING!!
-			break;
+/**
+ * @OA\Tag(
+ *     name="plugins-php-mailer",
+ *     description="PHP Mailer Plugin"
+ * )
+ */
+/**
+ * @OA\Schema(
+ *     schema="sendEmailData",
+ *     type="object",
+ *      @OA\Property(
+ *          property="bcc",
+ *          description="email of recipients (csv)",
+ *          type="string",
+ *          example="causefx@organizr.app,elmer@organizr.app",
+ *      ),
+ *      @OA\Property(
+ *          property="subject",
+ *          type="string",
+ *          example="Hey There Buddy?!",
+ *      ),
+ *      @OA\Property(
+ *          property="body",
+ *          type="string",
+ *          example="Hi! Boy, has it been a long time!  Have you seen rox in socks?",
+ *      ),
+ * )
+ */
+$app->get('/plugins/php-mailer/settings', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-php-mailer"},
+	 *     path="/api/v2/plugins/php-mailer/settings",
+	 *     summary="Get settings",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/pluginSettingsPage"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$PhpMailer = new PhpMailer();
+	if ($PhpMailer->checkRoute($request)) {
+		if ($PhpMailer->qualifyRequest(1, true)) {
+			$GLOBALS['api']['response']['data'] = $PhpMailer->_phpMailerPluginGetSettings();
+		}
 	}
-}
-if (isset($_GET['plugin']) && $_GET['plugin'] == 'PHPMailer' && isset($_GET['cmd'])) {
-	switch ($_GET['cmd']) {
-		case 'PHPMailer/settings/get':
-			if (qualifyRequest(1)) {
-				$result['status'] = 'success';
-				$result['statusText'] = 'success';
-				$result['data'] = phpmGetSettings();
-			} else {
-				$result['status'] = 'error';
-				$result['statusText'] = 'API/Token invalid or not set';
-				$result['data'] = null;
-			}
-			break;
-		default:
-			//Do NOTHING!
-			break;
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->get('/plugins/php-mailer/email/test', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-php-mailer"},
+	 *     path="/api/v2/plugins/php-mailer/email/test",
+	 *     summary="Send Test Email to Default Admin Email",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/successNullData"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$PhpMailer = new PhpMailer();
+	if ($PhpMailer->checkRoute($request)) {
+		if ($PhpMailer->qualifyRequest(1, true)) {
+			$PhpMailer->_phpMailerPluginSendTestEmail();
+		}
 	}
-}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->post('/plugins/php-mailer/email/send', function ($request, $response, $args) {
+	/**
+	 * @OA\Post(
+	 *     tags={"plugins-php-mailer"},
+	 *     path="/api/v2/plugins/php-mailer/email/send",
+	 *     summary="Send Email",
+	 *     @OA\RequestBody(
+	 *      description="Success",
+	 *      required=true,
+	 *      @OA\JsonContent(ref="#/components/schemas/sendEmailData"),
+	 *     ),
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/successNullData"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$PhpMailer = new PhpMailer();
+	if ($PhpMailer->checkRoute($request)) {
+		if ($PhpMailer->qualifyRequest(1, true)) {
+			$PhpMailer->_phpMailerPluginAdminSendEmail($PhpMailer->apiData($request));
+		}
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});
+$app->get('/plugins/php-mailer/email/list', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-php-mailer"},
+	 *     path="/api/v2/plugins/php-mailer/email/list",
+	 *     summary="Get List of User Emails",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/php-mailer-email-list"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$PhpMailer = new PhpMailer();
+	if ($PhpMailer->checkRoute($request)) {
+		if ($PhpMailer->qualifyRequest(1, true)) {
+			$GLOBALS['api']['response']['data'] = $PhpMailer->_phpMailerPluginGetEmails();
+		}
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});

+ 32 - 18
api/plugins/api/speedTest.php

@@ -1,19 +1,33 @@
 <?php
-if (isset($_POST['data']['plugin'])) {
-    switch ($_POST['data']['plugin']) {
-        case 'SpeedTest/settings/get':
-            if (qualifyRequest(1)) {
-                $result['status'] = 'success';
-                $result['statusText'] = 'success';
-                $result['data'] = speedTestGetSettings();
-            } else {
-                $result['status'] = 'error';
-                $result['statusText'] = 'API/Token invalid or not set';
-                $result['data'] = null;
-            }
-            break;
-        default:
-            //DO NOTHING!!
-            break;
-    }
-}
+/**
+ * @OA\Tag(
+ *     name="plugins-speedtest",
+ *     description="SpeedTest Plugin"
+ * )
+ */
+$app->get('/plugins/speedtest/settings', function ($request, $response, $args) {
+	/**
+	 * @OA\Get(
+	 *     tags={"plugins-speedtest"},
+	 *     path="/api/v2/plugins/speedtest/settings",
+	 *     summary="Get settings",
+	 *     @OA\Response(
+	 *      response="200",
+	 *      description="Success",
+	 *      @OA\JsonContent(ref="#/components/schemas/pluginSettingsPage"),
+	 *     ),
+	 *     @OA\Response(response="401",description="Unauthorized"),
+	 *     security={{ "api_key":{} }}
+	 * )
+	 */
+	$SpeedTest = new SpeedTest();
+	if ($SpeedTest->checkRoute($request)) {
+		if ($SpeedTest->qualifyRequest(1, true)) {
+			$GLOBALS['api']['response']['data'] = $SpeedTest->speedTestGetSettings();
+		}
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+});

+ 121 - 115
api/plugins/chat.php

@@ -6,9 +6,6 @@ $GLOBALS['plugins'][]['chat'] = array( // Plugin Name
 	'category' => 'Utilities', // One to Two Word Description
 	'link' => '', // Link to plugin info
 	'license' => 'personal,business', // License Type use , for multiple
-	//'fileName'=>'php-mailer.php',
-	//'configFile'=>'php-mailer.php',
-	//'apiFile'=>'php-mailer.php',
 	'idPrefix' => 'CHAT', // html element id prefix
 	'configPrefix' => 'CHAT', // config file prefix for array items without the hypen
 	'version' => '1.0.0', // SemVer of plugin
@@ -16,13 +13,13 @@ $GLOBALS['plugins'][]['chat'] = array( // Plugin Name
 	'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
-/* GET CHAT SETTINGS */
-function chatGetSettings()
+
+class Chat extends Organizr
 {
-	return array(
-		'custom' => '
+	public function _chatPluginGetSettings()
+	{
+		return array(
+			'custom' => '
 				<div class="row">
                     <div class="col-lg-12">
                         <div class="panel panel-info">
@@ -45,120 +42,129 @@ function chatGetSettings()
                     </div>
 				</div>
 				',
-		'Options' => array(
-			array(
-				'type' => 'select',
-				'name' => 'CHAT-Auth-include',
-				'label' => 'Minimum Authentication',
-				'value' => $GLOBALS['CHAT-Auth-include'],
-				'options' => groupSelect()
+			'Options' => array(
+				array(
+					'type' => 'select',
+					'name' => 'CHAT-Auth-include',
+					'label' => 'Minimum Authentication',
+					'value' => $this->config['CHAT-Auth-include'],
+					'options' => $this->groupSelect()
+				),
+				array(
+					'type' => 'number',
+					'name' => 'CHAT-messageLoadLimit',
+					'label' => '# of Previous Messages',
+					'value' => $this->config['CHAT-messageLoadLimit'],
+					'placeholder' => ''
+				),
+				array(
+					'type' => 'select',
+					'name' => 'CHAT-userRefreshTimeout',
+					'label' => 'Refresh Seconds',
+					'value' => $this->config['CHAT-userRefreshTimeout'],
+					'options' => $this->optionTime()
+				),
+				array(
+					'type' => 'select',
+					'name' => 'CHAT-newMessageSound-include',
+					'label' => 'Message Sound',
+					'value' => $this->config['CHAT-newMessageSound-include'],
+					'options' => $this->getSounds()
+				),
+				array(
+					'type' => 'switch',
+					'name' => 'CHAT-useSSL',
+					'label' => 'Use Pusher SSL',
+					'help' => 'If messages get stuck sending, please turn this option off.',
+					'value' => $this->config['CHAT-useSSL']
+				)
 			),
-			array(
-				'type' => 'number',
-				'name' => 'CHAT-messageLoadLimit',
-				'label' => '# of Previous Messages',
-				'value' => $GLOBALS['CHAT-messageLoadLimit'],
-				'placeholder' => ''
-			),
-			array(
-				'type' => 'select',
-				'name' => 'CHAT-userRefreshTimeout',
-				'label' => 'Refresh Seconds',
-				'value' => $GLOBALS['CHAT-userRefreshTimeout'],
-				'options' => optionTime()
-			),
-			array(
-				'type' => 'select',
-				'name' => 'CHAT-newMessageSound-include',
-				'label' => 'Message Sound',
-				'value' => $GLOBALS['CHAT-newMessageSound-include'],
-				'options' => getSounds()
-			),
-			array(
-				'type' => 'switch',
-				'name' => 'CHAT-useSSL',
-				'label' => 'Use Pusher SSL',
-				'help' => 'If messages get stuck sending, please turn this option off.',
-				'value' => $GLOBALS['CHAT-useSSL']
+			'Connection' => array(
+				array(
+					'type' => 'password-alt',
+					'name' => 'CHAT-authKey-include',
+					'label' => 'Auth Key',
+					'value' => $this->config['CHAT-authKey-include']
+				),
+				array(
+					'type' => 'password-alt',
+					'name' => 'CHAT-secret',
+					'label' => 'API Secret',
+					'value' => $this->config['CHAT-secret']
+				),
+				array(
+					'type' => 'input',
+					'name' => 'CHAT-appID-include',
+					'label' => 'App ID',
+					'value' => $this->config['CHAT-appID-include']
+				),
+				array(
+					'type' => 'input',
+					'name' => 'CHAT-cluster-include',
+					'label' => 'App Cluster',
+					'value' => $this->config['CHAT-cluster-include']
+				),
 			)
-		),
-		'Connection' => array(
-			array(
-				'type' => 'password-alt',
-				'name' => 'CHAT-authKey-include',
-				'label' => 'Auth Key',
-				'value' => $GLOBALS['CHAT-authKey-include']
-			),
-			array(
-				'type' => 'password-alt',
-				'name' => 'CHAT-secret',
-				'label' => 'API Secret',
-				'value' => $GLOBALS['CHAT-secret']
-			),
-			array(
-				'type' => 'input',
-				'name' => 'CHAT-appID-include',
-				'label' => 'App ID',
-				'value' => $GLOBALS['CHAT-appID-include']
-			),
-			array(
-				'type' => 'input',
-				'name' => 'CHAT-cluster-include',
-				'label' => 'App Cluster',
-				'value' => $GLOBALS['CHAT-cluster-include']
-			),
-		)
-	);
-}
-
-function sendChatMessage($array)
-{
-	$message = isset($array['data']['message']) ? $array['data']['message'] : null;
-	$message = htmlspecialchars($message, ENT_QUOTES);
-	$now = date("Y-m-d H:i:s");
-	$currentIP = userIP();
-	try {
-		$connect = new Dibi\Connection([
-			'driver' => 'sqlite3',
-			'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
-		]);
+		);
+	}
+	
+	public function _chatPluginSendChatMessage($array)
+	{
+		$message = isset($array['message']) ? $array['message'] : null;
+		if (!$message) {
+			$this->setAPIResponse('error', 'No message supplied', 409);
+			return false;
+		}
+		$message = htmlspecialchars($message, ENT_QUOTES);
+		$now = date("Y-m-d H:i:s");
+		$currentIP = $this->userIP();
 		$newMessage = [
-			'username' => $GLOBALS['organizrUser']['username'],
-			'gravatar' => $GLOBALS['organizrUser']['image'],
-			'uid' => $GLOBALS['organizrUser']['uid'],
+			'username' => $this->user['username'],
+			'gravatar' => $this->user['image'],
+			'uid' => $this->user['uid'],
 			'date' => $now,
 			'ip' => $currentIP,
 			'message' => $message
 		];
-		$connect->query('INSERT INTO [chatroom]', $newMessage);
-		$options = array(
-			'cluster' => $GLOBALS['CHAT-cluster-include'],
-			'useTLS' => $GLOBALS['CHAT-useSSL']
-		);
-		$pusher = new Pusher\Pusher(
-			$GLOBALS['CHAT-authKey-include'],
-			$GLOBALS['CHAT-secret'],
-			$GLOBALS['CHAT-appID-include'],
-			$options
-		);
-		$pusher->trigger('org_channel', 'my-event', $newMessage);
-		return true;
-	} catch (Dibi\Exception $e) {
-		return $e;
-	}
-}
-
-function getChatMessage()
-{
-	try {
-		$connect = new Dibi\Connection([
-			'driver' => 'sqlite3',
-			'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
-		]);
-		$all = $connect->fetchAll('SELECT `username`, `gravatar`, `uid`, `date`, `message` FROM chatroom LIMIT ' . $GLOBALS['CHAT-messageLoadLimit']);
-		return $all;
-	} catch (Dibi\Exception $e) {
+		$response = [
+			array(
+				'function' => 'query',
+				'query' => array(
+					'INSERT INTO [chatroom]',
+					$newMessage
+				)
+			),
+		];
+		$query = $this->processQueries($response);
+		if ($query) {
+			$options = array(
+				'cluster' => $GLOBALS['CHAT-cluster-include'],
+				'useTLS' => $GLOBALS['CHAT-useSSL']
+			);
+			$pusher = new Pusher\Pusher(
+				$GLOBALS['CHAT-authKey-include'],
+				$GLOBALS['CHAT-secret'],
+				$GLOBALS['CHAT-appID-include'],
+				$options
+			);
+			$pusher->trigger('org_channel', 'my-event', $newMessage);
+			$this->setAPIResponse('success', 'Chat message accepted', 200);
+			return true;
+		}
+		$this->setAPIResponse('error', 'Chat error occurred', 409);
 		return false;
 	}
 	
+	public function _chatPluginGetChatMessages()
+	{
+		$response = [
+			array(
+				'function' => 'fetchAll',
+				'query' => array(
+					'SELECT `username`, `gravatar`, `uid`, `date`, `message` FROM chatroom LIMIT ' . $this->config['CHAT-messageLoadLimit']
+				)
+			),
+		];
+		return $this->processQueries($response);
+	}
 }

+ 1 - 0
api/plugins/config/chat.php

@@ -9,5 +9,6 @@ return array(
 	'CHAT-messageLoadLimit' => '200',
 	'CHAT-userRefreshTimeout' => '60000',
 	'CHAT-newMessageSound-include' => 'plugins/sounds/default/newmessage.mp3',
+	'CHAT-newMessageSoundz-include' => 'plugins/sounds/default/newmessage.mp3',
 	'CHAT-useSSL' => false
 );

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

@@ -13,12 +13,12 @@ return array(
 	'PHPMAILER-domain' => '',
 	'PHPMAILER-template' => 'default',
 	'PHPMAILER-logo' => 'https://raw.githubusercontent.com/causefx/Organizr/v2-develop/plugins/images/organizr/logo-wide.png',
-	'PHPMAILER-emailTemplateResetPassword' => '
+	'PHPMAILER-emailTemplateReset' => '
 	<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-emailTemplateResetSubject' => 'Password Reset',
 	'PHPMAILER-emailTemplateInviteUser' => '
 	<h2>Hey there {user}!</h2><br />
 	Here is the invite code to join my cool media server: {inviteCode}<br/>

+ 107 - 100
api/plugins/healthChecks.php

@@ -13,117 +13,124 @@ $GLOBALS['plugins'][]['healthChecks'] = array( // Plugin Name
 	'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 healthCheckTest($url)
-{
-	$success = false;
-	$options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => true, 'redirects' => 1);
-	$headers = array('Token' => $GLOBALS['organizrAPI']);
-	$url = qualifyURL($url);
-	$response = Requests::get($url, $headers, $options);
-	if ($response->success) {
-		$success = true;
-	}
-	if ($response->status_code == 200) {
-		$success = true;
-	}
-	return $success;
-}
 
-function healthCheckUUID($uuid, $pass = false)
+class HealthChecks extends Organizr
 {
-	if (!$uuid || !$pass || $GLOBALS['HEALTHCHECKS-PingURL'] == '') {
-		return false;
+	public function _healthCheckPluginGetSettings()
+	{
+		return array(
+			'Options' => array(
+				array(
+					'type' => 'select',
+					'name' => 'HEALTHCHECKS-Auth-include',
+					'label' => 'Minimum Authentication',
+					'value' => $this->config['HEALTHCHECKS-Auth-include'],
+					'options' => $this->groupSelect()
+				),
+				array(
+					'type' => 'input',
+					'name' => 'HEALTHCHECKS-PingURL',
+					'label' => 'URL',
+					'value' => $this->config['HEALTHCHECKS-PingURL'],
+					'help' => 'URL for HealthChecks Ping',
+					'placeholder' => 'HealthChecks Ping URL'
+				),
+			),
+			'Services' => array(
+				array(
+					'type' => 'arrayMultiple',
+					'name' => 'HEALTHCHECKS-all-items',
+					'label' => 'Services',
+					'value' => $this->config['HEALTHCHECKS-all-items']
+				)
+			)
+		);
 	}
-	$url = qualifyURL($GLOBALS['HEALTHCHECKS-PingURL']);
-	$uuid = '/' . $uuid;
-	$path = !$pass ? '/fail' : '';
-	$response = Requests::get($url . $uuid . $path, [], []);
-	return $response;
-}
-
-function healthCheckRun()
-{
-	$continue = $GLOBALS['HEALTHCHECKS-all-items'] !== '' ? $GLOBALS['HEALTHCHECKS-all-items'] : false;
-	if ($continue && $GLOBALS['HEALTHCHECKS-enabled'] && !empty($GLOBALS['HEALTHCHECKS-PingURL']) && qualifyRequest($GLOBALS['HEALTHCHECKS-Auth-include'])) {
-		$allItems = [];
-		foreach ($GLOBALS['HEALTHCHECKS-all-items'] as $k => $v) {
-			
-			if ($k !== false) {
-				foreach ($v as $item) {
-					$allItems[$k][$item['label']] = $item['value'];
-				}
-			}
+	
+	public function _healthCheckPluginTest($url)
+	{
+		$success = false;
+		$options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => true, 'redirects' => 1);
+		$headers = array('Token' => $this->config['organizrAPI']);
+		$url = $this->qualifyURL($url);
+		$response = Requests::get($url, $headers, $options);
+		if ($response->success) {
+			$success = true;
 		}
-		foreach ($allItems as $k => $v) {
-			if ($v['Enabled'] == 'false') {
-				unset($allItems[$k]);
-			}
-			if (!$v['UUID']) {
-				unset($allItems[$k]);
-			}
+		if ($response->status_code == 200) {
+			$success = true;
 		}
-		foreach ($allItems as $k => $v) {
-			$testLocal = $v['Internal URL'] !== '' ?? false;
-			$testExternal = $v['External URL'] !== '' ?? false;
-			$testBoth = ($testLocal && $testExternal) ?? false;
-			$pass = false;
-			if ($testLocal) {
-				$allItems[$k]['results']['internal'] = (healthCheckTest($v['Internal URL'])) ? 'Success' : 'Error';
+		return $success;
+	}
+	
+	public function _healthCheckPluginUUID($uuid, $pass = false)
+	{
+		if (!$uuid || !$pass || $this->config['HEALTHCHECKS-PingURL'] == '') {
+			return false;
+		}
+		$url = $this->qualifyURL($this->config['HEALTHCHECKS-PingURL']);
+		$uuid = '/' . $uuid;
+		$path = !$pass ? '/fail' : '';
+		return Requests::get($url . $uuid . $path, [], []);
+	}
+	
+	public function _healthCheckPluginRun()
+	{
+		$continue = $this->config['HEALTHCHECKS-all-items'] !== '' ? $this->config['HEALTHCHECKS-all-items'] : false;
+		if (!$continue) {
+			$this->setAPIResponse('error', 'No items are setup', 409);
+		}
+		if ($continue && $this->config['HEALTHCHECKS-enabled'] && !empty($this->config['HEALTHCHECKS-PingURL']) && $this->qualifyRequest($this->config['HEALTHCHECKS-Auth-include'])) {
+			$allItems = [];
+			foreach ($this->config['HEALTHCHECKS-all-items'] as $k => $v) {
+				
+				if ($k !== false) {
+					foreach ($v as $item) {
+						$allItems[$k][$item['label']] = $item['value'];
+					}
+				}
 			}
-			if ($testExternal) {
-				$allItems[$k]['results']['external'] = (healthCheckTest($v['External URL'])) ? 'Success' : 'Error';
+			foreach ($allItems as $k => $v) {
+				if ($v['Enabled'] == false) {
+					unset($allItems[$k]);
+				}
+				if (!$v['UUID']) {
+					unset($allItems[$k]);
+				}
 			}
-			if ($testBoth) {
-				if ($allItems[$k]['results']['external'] == 'Success' && $allItems[$k]['results']['internal'] == 'Success') {
-					$pass = true;
+			foreach ($allItems as $k => $v) {
+				$testLocal = $v['Internal URL'] !== '' ?? false;
+				$testExternal = $v['External URL'] !== '' ?? false;
+				$testBoth = ($testLocal && $testExternal) ?? false;
+				$pass = false;
+				if ($testLocal) {
+					$allItems[$k]['results']['internal'] = ($this->_healthCheckPluginTest($v['Internal URL'])) ? 'Success' : 'Error';
 				}
-			} elseif ($testLocal) {
-				if ($allItems[$k]['results']['internal'] == 'Success') {
-					$pass = true;
+				if ($testExternal) {
+					if (($testBoth && $allItems[$k]['results']['internal'] == 'Error') || !$testBoth) {
+						$allItems[$k]['results']['external'] = ($this->_healthCheckPluginTest($v['External URL'])) ? 'Success' : 'Error';
+					} else {
+						$allItems[$k]['results']['external'] = 'Not needed';
+					}
 				}
-			} elseif ($testExternal) {
-				if ($allItems[$k]['results']['external'] == 'Success') {
-					$pass = true;
+				if ($testBoth) {
+					if ($allItems[$k]['results']['external'] == 'Success' || $allItems[$k]['results']['internal'] == 'Success') {
+						$pass = true;
+					}
+				} elseif ($testLocal) {
+					if ($allItems[$k]['results']['internal'] == 'Success') {
+						$pass = true;
+					}
+				} elseif ($testExternal) {
+					if ($allItems[$k]['results']['external'] == 'Success') {
+						$pass = true;
+					}
 				}
+				$this->_healthCheckPluginUUID($v['UUID'], 'true');
 			}
-			healthCheckUUID($v['UUID'], 'true');
+			$this->setAPIResponse('success', null, 200, $allItems);
+		} else {
+			$this->setAPIResponse('error', 'User does not have access', 401);
 		}
-		return $allItems;
-	} else {
-		'No Access';
 	}
 }
-
-/* GET HEALTHCHECK SETTINGS */
-function healthCheckGetSettings()
-{
-	return array(
-		'Options' => array(
-			array(
-				'type' => 'select',
-				'name' => 'HEALTHCHECKS-Auth-include',
-				'label' => 'Minimum Authentication',
-				'value' => $GLOBALS['HEALTHCHECKS-Auth-include'],
-				'options' => groupSelect()
-			),
-			array(
-				'type' => 'input',
-				'name' => 'HEALTHCHECKS-PingURL',
-				'label' => 'URL',
-				'value' => $GLOBALS['HEALTHCHECKS-PingURL'],
-				'help' => 'URL for HealthChecks Ping',
-				'placeholder' => 'HealthChecks Ping URL'
-			),
-		),
-		'Services' => array(
-			array(
-				'type' => 'arrayMultiple',
-				'name' => 'HEALTHCHECKS-all-items',
-				'label' => 'Services',
-				'value' => $GLOBALS['HEALTHCHECKS-all-items']
-			)
-		)
-	);
-}

+ 417 - 341
api/plugins/invites.php

@@ -4,11 +4,8 @@ $GLOBALS['plugins'][]['Invites'] = array( // Plugin Name
 	'name' => 'Invites', // Plugin Name
 	'author' => 'CauseFX', // Who wrote the plugin
 	'category' => 'Management', // One to Two Word Description
-	'link' => 'https://github.com/PHPMailer/PHPMailer', // Link to plugin info
+	'link' => '', // Link to plugin info
 	'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
 	'version' => '1.0.0', // SemVer of plugin
@@ -16,368 +13,447 @@ $GLOBALS['plugins'][]['Invites'] = array( // Plugin Name
 	'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('
-	                	UPDATE invites SET', [
-						'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;
-				}
-			} 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;
-				}
-			}
-	}
-}
 
-/* GET PHPMAILER SETTINGS */
-function invitesGetSettings()
+class Invites extends Organizr
 {
-	if ($GLOBALS['plexID'] !== '' && $GLOBALS['plexToken'] !== '' && $GLOBALS['INVITES-type-include'] == 'plex') {
-		$loop = libraryList($GLOBALS['INVITES-type-include'])['libraries'];
-		foreach ($loop as $key => $value) {
-			$libraryList[] = array(
-				'name' => $key,
-				'value' => $value
-			);
-		}
-	} else {
-		$libraryList = array(
+	public function _invitesPluginGetCodes()
+	{
+		$response = [
 			array(
-				'name' => 'Refresh page to update List',
-				'value' => '',
-				'disabled' => true,
-			),
-		);
+				'function' => 'fetchAll',
+				'query' => 'SELECT * FROM invites'
+			)
+		];
+		return $this->processQueries($response);
 	}
-	return array(
-		'Backend' => array(
+	
+	public function _invitesPluginCreateCode($array)
+	{
+		$code = ($array['code']) ?? null;
+		$username = ($array['username']) ?? null;
+		$email = ($array['email']) ?? null;
+		if (!$code) {
+			$this->setAPIResponse('error', 'Code not supplied', 409);
+			return false;
+		}
+		if (!$username) {
+			$this->setAPIResponse('error', 'Username not supplied', 409);
+			return false;
+		}
+		if (!$email) {
+			$this->setAPIResponse('error', 'Email not supplied', 409);
+			return false;
+		}
+		$newCode = [
+			'code' => $code,
+			'email' => $email,
+			'username' => $username,
+			'valid' => 'Yes',
+			'type' => $this->config['INVITES-type-include'],
+		];
+		$response = [
 			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',
-						'value' => 'emby'
-					)
+				'function' => 'query',
+				'query' => array(
+					'INSERT INTO [invites]',
+					$newCode
 				)
 			)
-		),
-		'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',
-				'class' => 'select2-multiple',
-				'id' => 'invite-select',
-				'name' => 'INVITES-plexLibraries',
-				'label' => 'Libraries',
-				'value' => $GLOBALS['INVITES-plexLibraries'],
-				'options' => $libraryList
-			),
-			array(
-				'type' => 'text',
-				'name' => 'INVITES-plex-tv-labels',
-				'label' => 'TV Labels (comma separated)',
-				'value' => $GLOBALS['INVITES-plex-tv-labels'],
-				'placeholder' => 'All'
-			),
-			array(
-				'type' => 'text',
-				'name' => 'INVITES-plex-movies-labels',
-				'label' => 'Movies Labels (comma separated)',
-				'value' => $GLOBALS['INVITES-plex-movies-labels'],
-				'placeholder' => 'All'
-			),
-			array(
-				'type' => 'text',
-				'name' => 'INVITES-plex-music-labels',
-				'label' => 'Music Labels (comma separated)',
-				'value' => $GLOBALS['INVITES-plex-music-labels'],
-				'placeholder' => 'All'
-			),
-		),
-		'Emby Settings' => array(
-			array(
-				'type' => 'password-alt',
-				'name' => 'embyToken',
-				'label' => 'Emby API key',
-				'value' => $GLOBALS['embyToken'],
-				'placeholder' => 'enter key from emby'
-			),
+		];
+		$query = $this->processQueries($response);
+		if ($query) {
+			$this->writeLog('success', 'Invite Management Function -  Added Invite [' . $code . ']', $this->user['username']);
+			if ($this->config['PHPMAILER-enabled']) {
+				$PhpMailer = new PhpMailer();
+				$emailTemplate = array(
+					'type' => 'invite',
+					'body' => $this->config['PHPMAILER-emailTemplateInviteUser'],
+					'subject' => $this->config['PHPMAILER-emailTemplateInviteUserSubject'],
+					'user' => $username,
+					'password' => null,
+					'inviteCode' => $code,
+				);
+				$emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
+				$sendEmail = array(
+					'to' => $email,
+					'subject' => $emailTemplate['subject'],
+					'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
+				);
+				$PhpMailer->_phpMailerPluginSendEmail($sendEmail);
+			}
+			$this->setAPIResponse('success', 'Invite Code: ' . $code . ' has been created', 200);
+			return true;
+		} else {
+			return false;
+		}
+		
+	}
+	
+	public function _invitesPluginVerifyCode($code)
+	{
+		$response = [
 			array(
-				'type' => 'text',
-				'name' => 'embyURL',
-				'label' => 'Emby server adress',
-				'value' => $GLOBALS['embyURL'],
-				'placeholder' => 'localhost:8086'
-			),
+				'function' => 'fetchAll',
+				'query' => array(
+					'SELECT * FROM invites WHERE valid = "Yes" AND code = ? COLLATE NOCASE',
+					$code
+				)
+			)
+		];
+		if ($this->processQueries($response)) {
+			$this->setAPIResponse('success', 'Code has been verified', 200);
+			return true;
+		} else {
+			$this->setAPIResponse('error', 'Code is invalid', 401);
+			return false;
+		}
+	}
+	
+	public function _invitesPluginDeleteCode($code)
+	{
+		$response = [
 			array(
-				'type' => 'text',
-				'name' => 'INVITES-EmbyTemplate',
-				'label' => 'Emby User to be used as template for new users',
-				'value' => $GLOBALS['INVITES-EmbyTemplate'],
-				'placeholder' => 'AdamSmith'
+				'function' => 'fetchAll',
+				'query' => 'SELECT * FROM invites WHERE code = ? COLLATE NOCASE',
+				$code
 			)
-		),
-		'FYI' => array(
+		];
+		$info = $this->processQueries($response);
+		if (!$info) {
+			$this->setAPIResponse('error', 'Code not found', 404);
+			return false;
+		}
+		$response = [
 			array(
-				'type' => 'html',
-				'label' => 'Note',
-				'html' => 'After enabling for the first time, please reload the page - Menu is located under User menu on top right'
+				'function' => 'query',
+				'query' => array(
+					'DELETE FROM invites WHERE code = ? COLLATE NOCASE',
+					$code
+				)
 			)
-		)
-	);
-}
-
-function inviteAction($username, $action = null, $type = null)
-{
-	if ($action == null) {
-		return false;
+		];
+		$this->setAPIResponse('success', 'Code has been deleted', 200);
+		return $this->processQueries($response);
+		
 	}
-	switch ($type) {
-		case 'plex':
-			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 {
-					$libraries = '';
+	
+	public function _invitesPluginUseCode($code, $array)
+	{
+		$code = ($code) ?? null;
+		$usedBy = ($array['usedby']) ?? null;
+		$now = date("Y-m-d H:i:s");
+		$currentIP = $this->userIP();
+		if ($this->_invitesPluginVerifyCode($code)) {
+			$updateCode = [
+				'valid' => 'No',
+				'usedby' => $usedBy,
+				'dateused' => $now,
+				'ip' => $currentIP
+			];
+			$response = [
+				array(
+					'function' => 'query',
+					'query' => array(
+						'UPDATE invites SET',
+						$updateCode,
+						'WHERE code=? COLLATE NOCASE',
+						$code
+					)
+				)
+			];
+			$query = $this->processQueries($response);
+			$this->writeLog('success', 'Invite Management Function -  Invite Used [' . $code . ']', 'SYSTEM');
+			return $this->_invitesPluginAction($usedBy, 'share', $this->config['INVITES-type-include']);
+		} else {
+			return false;
+		}
+	}
+	
+	public function _invitesPluginLibraryList($type = null)
+	{
+		switch ($type) {
+			case 'plex':
+				if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
+					$url = 'https://plex.tv/api/servers/' . $this->config['plexID'];
+					try {
+						$headers = array(
+							"Accept" => "application/json",
+							"X-Plex-Token" => $this->config['plexToken']
+						);
+						$response = Requests::get($url, $headers, array());
+						libxml_use_internal_errors(true);
+						if ($response->success) {
+							$libraryList = array();
+							$plex = simplexml_load_string($response->body);
+							foreach ($plex->Server->Section as $child) {
+								$libraryList['libraries'][(string)$child['title']] = (string)$child['id'];
+							}
+							$libraryList = array_change_key_case($libraryList, CASE_LOWER);
+							return $libraryList;
+						}
+					} catch (Requests_Exception $e) {
+						$this->writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+						return false;
+					};
 				}
-				if ($GLOBALS['INVITES-plex-tv-labels'] !== "") {
-					$tv_labels = "label=" . $GLOBALS['INVITES-plex-tv-labels'];
-				} else { $tv_labels = ""; }
-				if ($GLOBALS['INVITES-plex-movies-labels'] !== "") {
-					$movies_labels = "label=" . $GLOBALS['INVITES-plex-movies-labels'];
-				} else { $movies_labels = ""; }
-				if ($GLOBALS['INVITES-plex-music-labels'] !== "") {
-					$music_labels = "label=" . $GLOBALS['INVITES-plex-music-labels'];
-				} else { $music_labels = ""; }
-				
-				$headers = array(
-					"Accept" => "application/json",
-					"Content-Type" => "application/json",
-					"X-Plex-Token" => $GLOBALS['plexToken']
+				break;
+			default:
+				# code...
+				break;
+		}
+		return false;
+	}
+	
+	public function _invitesPluginGetSettings()
+	{
+		if ($this->config['plexID'] !== '' && $this->config['plexToken'] !== '' && $this->config['INVITES-type-include'] == 'plex') {
+			$loop = $this->_invitesPluginLibraryList($this->config['INVITES-type-include'])['libraries'];
+			foreach ($loop as $key => $value) {
+				$libraryList[] = array(
+					'name' => $key,
+					'value' => $value
 				);
-				$data = array(
-					"server_id" => $GLOBALS['plexID'],
-					"shared_server" => array(
-						"library_section_ids" => $libraries,
-						"invited_email" => $username
-					),
-					"sharing_settings" => array(
-						"filterTelevision" => $tv_labels,
-						"filterMovies" => $movies_labels,
-						"filterMusic" => $music_labels
+			}
+		} 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' => $this->config['INVITES-type-include'],
+					'options' => array(
+						array(
+							'name' => 'N/A',
+							'value' => 'n/a'
+						),
+						array(
+							'name' => 'Plex',
+							'value' => 'plex'
+						),
+						array(
+							'name' => 'Emby',
+							'value' => 'emby'
+						)
 					)
-				);
-				try {
-					switch ($action) {
-						case 'share':
-							$response = Requests::post($url, $headers, json_encode($data), array());
-							break;
-						case 'unshare':
-							$id = (is_numeric($username) ? $username : convertPlexName($username, "id"));
-							$url = $url . $id;
-							$response = Requests::delete($url, $headers, array());
-							break;
-						default:
-							return false;
-							break;
+				)
+			),
+			'Plex Settings' => array(
+				array(
+					'type' => 'password-alt',
+					'name' => 'plexToken',
+					'label' => 'Plex Token',
+					'value' => $this->config['plexToken'],
+					'placeholder' => 'Use Get Token Button'
+				),
+				array(
+					'type' => 'password-alt',
+					'name' => 'plexID',
+					'label' => 'Plex Machine',
+					'value' => $this->config['plexID'],
+					'placeholder' => 'Use Get Plex Machine Button'
+				),
+				array(
+					'type' => 'select2',
+					'class' => 'select2-multiple',
+					'id' => 'invite-select',
+					'name' => 'INVITES-plexLibraries',
+					'label' => 'Libraries',
+					'value' => $this->config['INVITES-plexLibraries'],
+					'options' => $libraryList
+				),
+				array(
+					'type' => 'text',
+					'name' => 'INVITES-plex-tv-labels',
+					'label' => 'TV Labels (comma separated)',
+					'value' => $this->config['INVITES-plex-tv-labels'],
+					'placeholder' => 'All'
+				),
+				array(
+					'type' => 'text',
+					'name' => 'INVITES-plex-movies-labels',
+					'label' => 'Movies Labels (comma separated)',
+					'value' => $this->config['INVITES-plex-movies-labels'],
+					'placeholder' => 'All'
+				),
+				array(
+					'type' => 'text',
+					'name' => 'INVITES-plex-music-labels',
+					'label' => 'Music Labels (comma separated)',
+					'value' => $this->config['INVITES-plex-music-labels'],
+					'placeholder' => 'All'
+				),
+			),
+			'Emby Settings' => array(
+				array(
+					'type' => 'password-alt',
+					'name' => 'embyToken',
+					'label' => 'Emby API key',
+					'value' => $this->config['embyToken'],
+					'placeholder' => 'enter key from emby'
+				),
+				array(
+					'type' => 'text',
+					'name' => 'embyURL',
+					'label' => 'Emby server adress',
+					'value' => $this->config['embyURL'],
+					'placeholder' => 'localhost:8086'
+				),
+				array(
+					'type' => 'text',
+					'name' => 'INVITES-EmbyTemplate',
+					'label' => 'Emby User to be used as template for new users',
+					'value' => $this->config['INVITES-EmbyTemplate'],
+					'placeholder' => 'AdamSmith'
+				)
+			),
+			'FYI' => array(
+				array(
+					'type' => 'html',
+					'label' => 'Note',
+					'html' => 'After enabling for the first time, please reload the page - Menu is located under User menu on top right'
+				)
+			)
+		);
+	}
+	
+	public function _invitesPluginAction($username, $action = null, $type = null)
+	{
+		if ($action == null) {
+			$this->setAPIResponse('error', 'No Action supplied', 409);
+			return false;
+		}
+		switch ($type) {
+			case 'plex':
+				if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
+					$url = "https://plex.tv/api/servers/" . $this->config['plexID'] . "/shared_servers/";
+					if ($this->config['INVITES-plexLibraries'] !== "") {
+						$libraries = explode(',', $this->config['INVITES-plexLibraries']);
+					} else {
+						$libraries = '';
 					}
-					if ($response->success) {
-						writeLog('success', 'Plex Invite Function - Plex User now has access to system', $username);
-						return true;
+					if ($this->config['INVITES-plex-tv-labels'] !== "") {
+						$tv_labels = "label=" . $this->config['INVITES-plex-tv-labels'];
 					} else {
-						switch ($response->status_code) {
-							case 400:
-								writeLog('error', 'Plex Invite Function - Plex User already has access', $username);
-								return false;
-								break;
-							case 401:
-								writeLog('error', 'Plex Invite Function - Incorrect Token', 'SYSTEM');
-								return false;
+						$tv_labels = "";
+					}
+					if ($this->config['INVITES-plex-movies-labels'] !== "") {
+						$movies_labels = "label=" . $this->config['INVITES-plex-movies-labels'];
+					} else {
+						$movies_labels = "";
+					}
+					if ($this->config['INVITES-plex-music-labels'] !== "") {
+						$music_labels = "label=" . $this->config['INVITES-plex-music-labels'];
+					} else {
+						$music_labels = "";
+					}
+					$headers = array(
+						"Accept" => "application/json",
+						"Content-Type" => "application/json",
+						"X-Plex-Token" => $this->config['plexToken']
+					);
+					$data = array(
+						"server_id" => $this->config['plexID'],
+						"shared_server" => array(
+							"library_section_ids" => $libraries,
+							"invited_email" => $username
+						),
+						"sharing_settings" => array(
+							"filterTelevision" => $tv_labels,
+							"filterMovies" => $movies_labels,
+							"filterMusic" => $music_labels
+						)
+					);
+					try {
+						switch ($action) {
+							case 'share':
+								$response = Requests::post($url, $headers, json_encode($data), array());
 								break;
-							case 404:
-								writeLog('error', 'Plex Invite Function - Libraries not setup correct [' . $GLOBALS['INVITES-plexLibraries'] . ']', 'SYSTEM');
-								return false;
+							case 'unshare':
+								$id = (is_numeric($username) ? $username : $this->_invitesPluginConvertPlexName($username, "id"));
+								$url = $url . $id;
+								$response = Requests::delete($url, $headers, array());
 								break;
 							default:
-								writeLog('error', 'Plex Invite Function - An error occurred [' . $response->status_code . ']', $username);
+								$this->setAPIResponse('error', 'No Action supplied', 409);
 								return false;
-								break;
 						}
-					}
+						if ($response->success) {
+							$this->writeLog('success', 'Plex Invite Function - Plex User now has access to system', $username);
+							$this->setAPIResponse('success', 'Plex User now has access to system', 200);
+							return true;
+						} else {
+							switch ($response->status_code) {
+								case 400:
+									$this->writeLog('error', 'Plex Invite Function - Plex User already has access', $username);
+									$this->setAPIResponse('error', 'Plex User already has access', 409);
+									return false;
+								case 401:
+									$this->writeLog('error', 'Plex Invite Function - Incorrect Token', 'SYSTEM');
+									$this->setAPIResponse('error', 'Incorrect Token', 409);
+									return false;
+								case 404:
+									$this->writeLog('error', 'Plex Invite Function - Libraries not setup correct [' . $this->config['INVITES-plexLibraries'] . ']', 'SYSTEM');
+									$this->setAPIResponse('error', 'Libraries not setup correct', 409);
+									return false;
+								default:
+									$this->writeLog('error', 'Plex Invite Function - An error occurred [' . $response->status_code . ']', $username);
+									$this->setAPIResponse('error', 'An Error Occurred', 409);
+									return false;
+							}
+						}
+					} catch (Requests_Exception $e) {
+						$this->writeLog('error', 'Plex Invite Function - Error: ' . $e->getMessage(), 'SYSTEM');
+						$this->setAPIResponse('error', $e->getMessage(), 409);
+						return false;
+					};
+				} else {
+					$this->writeLog('error', 'Plex Invite Function - Plex Token/ID not set', 'SYSTEM');
+					$this->setAPIResponse('error', 'Plex Token/ID not set', 409);
+					return false;
+				}
+				break;
+			case 'emby':
+				try {
+					#add emby user to system
+					$this->setAPIResponse('success', 'User now has access to system', 200);
+					return true;
 				} catch (Requests_Exception $e) {
-					writeLog('error', 'Plex Invite Function - Error: ' . $e->getMessage(), 'SYSTEM');
+					$this->writeLog('error', 'Emby Invite Function - Error: ' . $e->getMessage(), 'SYSTEM');
+					$this->setAPIResponse('error', $e->getMessage(), 409);
 					return false;
-				};
-			} else {
-				writeLog('error', 'Plex Invite Function - Plex Token/ID not set', 'SYSTEM');
-				return false;
-			}
-			break;
-		case 'emby':
-			try {
-				#add emby user to sytem
-				return true;
-			} catch (Requests_Exception $e) {
-				writeLog('error', 'Emby Invite Function - Error: ' . $e->getMessage(), 'SYSTEM');
+				}
+			default:
 				return false;
-			}
-			break;
-		default:
-			return false;
-			break;
+		}
+		return false;
+	}
+	
+	public function _invitesPluginConvertPlexName($user, $type)
+	{
+		$array = $this->userList('plex');
+		switch ($type) {
+			case "username":
+			case "u":
+				$plexUser = array_search($user, $array['users']);
+				break;
+			case "id":
+				if (array_key_exists(strtolower($user), $array['users'])) {
+					$plexUser = $array['users'][strtolower($user)];
+				}
+				break;
+			default:
+				$plexUser = false;
+		}
+		return (!empty($plexUser) ? $plexUser : null);
 	}
-	return false;
+	
 }

+ 7 - 14
api/plugins/js/chat.js

@@ -65,8 +65,8 @@ function chatLaunch(){
                     });
                 // check if the user is subscribed to the above channel
                 channel.bind('pusher:subscription_succeeded', function(members) {
-                    console.log('Chat Websocket Connected!');
-                    console.log('Connecting to Organizr Chat DB');
+	                organizrConsole('Plugin Function','Chat Websocket Connected!');
+	                organizrConsole('Plugin Function','Connecting to Organizr Chat DB');
                     getMessagesAndUsers(activeInfo.settings.homepage.refresh["CHAT-userRefreshTimeout"], true);
                 });
                 /*jslint browser: true*/
@@ -97,12 +97,9 @@ function chatLaunch(){
     }
 }
 $(document).on('click', '#CHAT-settings-button', function() {
-    var post = {
-        plugin:'chat/settings/get', // used for switch case in your API call
-    };
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
+	organizrAPI2('GET','api/v2/plugins/chat/settings').success(function(data) {
+        var response = data.response;
         $('#CHAT-settings-items').html(buildFormGroup(response.data));
     }).fail(function(xhr) {
         console.error("Organizr Function: API Connection Failed");
@@ -123,11 +120,7 @@ $('body').on('click', '.custom-send-button', function(e) {
     var message = $('.chat-input-send').val();
     // Validate Name field
     if (message !== '') {
-        var post = {
-            plugin:'chat/message',
-            message:message
-        };
-        organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
+        organizrAPI2('POST','api/v2/plugins/chat/message',{ message : message }).success(function(data) {
             // Nada yet
         }).fail(function(xhr) {
             console.error("Organizr Function: API Connection Failed");
@@ -187,8 +180,8 @@ function chatEntry(){
 }
 function getMessagesAndUsers(timeout, initial = false){
     var timeout = (typeof timeout !== 'undefined') ? timeout : activeInfo.settings.homepage.refresh["CHAT-userRefreshTimeout"];
-    organizrAPI('GET','api/?v1/plugin&plugin=chat&cmd=chat/message').success(function(data) {
-        var response = JSON.parse(data);
+    organizrAPI2('GET','api/v2/plugins/chat/message').success(function(data) {
+        var response = data.response;
         if(initial == true){
             $.each(response.data, function (i, v){
                 $('.chat-list').append(formatMessage(v));

+ 3 - 24
api/plugins/js/healthChecks.js

@@ -1,22 +1,4 @@
-/* PHP MAILER JS FILE */
-/*
-$(document).on('click', '#PHPMAILER-settings-button', function() {
-	var post = {
-        plugin:'PHPMailer/settings/get', // used for switch case in your API call
-        api:'api/?v1/plugin', // API Endpoint will always be this for custom plugin API calls
-        name:$(this).attr('data-plugin-name'),
-        configName:$(this).attr('data-config-name'),
-        messageTitle:'', // Send succees message title (top line)
-        messageBody:'Disabled '+$(this).attr('data-plugin-name'), // Send succees message body (bottom line)
-        error:'Organizr Function: API Connection Failed' // conole error message
-    };
-	var callbacks = $.Callbacks(); // init callbacks var
-    //callbacks.add(  ); // add function to callback to be fired after API call
-    //settingsAPI(post,callbacks); // exec API call
-    //ajaxloader(".content-wrap","in");
-    //setTimeout(function(){ buildPlugins();ajaxloader(); }, 3000);
-});
-*/
+/* HEALTHCHECKS.IO JS FILE */
 
 // FUNCTIONS
 
@@ -25,12 +7,9 @@ $(document).on('click', '#PHPMAILER-settings-button', function() {
 // CHANGE CUSTOMIZE Options
 //
 $(document).on('click', '#HEALTHCHECKS-settings-button', function() {
-    var post = {
-        plugin:'HealthChecks/settings/get', // used for switch case in your API call
-    };
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
+    organizrAPI2('GET','api/v2/plugins/healthchecks/settings').success(function(data) {
+        var response = data.response;
         $('#HEALTHCHECKS-settings-items').html(buildFormGroup(response.data));
         var elAddButtonStart = $('#HEALTHCHECKS-settings-page [id*="Services"] .row.start');
         var testone = $('#HEALTHCHECKS-settings-page [id*="Services"] .row.m-b-40').first('span')

+ 33 - 111
api/plugins/js/invites.js

@@ -1,23 +1,4 @@
-/* PHP MAILER JS FILE */
-/*
-$(document).on('click', '#PHPMAILER-settings-button', function() {
-	var post = {
-        plugin:'PHPMailer/settings/get', // used for switch case in your API call
-        api:'api/?v1/plugin', // API Endpoint will always be this for custom plugin API calls
-        name:$(this).attr('data-plugin-name'),
-        configName:$(this).attr('data-config-name'),
-        messageTitle:'', // Send succees message title (top line)
-        messageBody:'Disabled '+$(this).attr('data-plugin-name'), // Send succees message body (bottom line)
-        error:'Organizr Function: API Connection Failed' // conole error message
-    };
-	var callbacks = $.Callbacks(); // init callbacks var
-    //callbacks.add(  ); // add function to callback to be fired after API call
-    //settingsAPI(post,callbacks); // exec API call
-    //ajaxloader(".content-wrap","in");
-    //setTimeout(function(){ buildPlugins();ajaxloader(); }, 3000);
-});
-*/
-
+/* INVITES JS FILE */
 // FUNCTIONS
 inviteLaunch()
 function inviteLaunch(){
@@ -92,19 +73,19 @@ function joinPlex(){
         message('Invite Error',' Please Enter Email',activeInfo.settings.notifications.position,'#FFF','warning','5000');
     }else if(password.val() == ''){
         password.focus();
-        message('Invite Error',' Please Enter Passowrd',activeInfo.settings.notifications.position,'#FFF','warning','5000');
+        message('Invite Error',' Please Enter Password',activeInfo.settings.notifications.position,'#FFF','warning','5000');
     }
     if(email.val() !== '' && username.val() !== '' && password.val() !== ''){
-        organizrAPI('POST','api/?v1/plex/join',{username:username.val(), email:email.val(), password:password.val()}).success(function(data) {
-    		var response = JSON.parse(data);
-            if(response.data === true){
+        organizrAPI2('POST','api/v2/plex/register',{username:username.val(), email:email.val(), password:password.val()}).success(function(data) {
+    		var response = data.response;
+            if(response.result === 'success'){
                 $('.invite-step-3-plex-no').toggleClass('hidden');
                 $('.invite-step-3-plex-yes').toggleClass('hidden');
                 message('Invite Function',' User Created',activeInfo.settings.notifications.position,'#FFF','success','5000');
                 $('#inviteUsernameInvite').val(username.val());
                 hasPlexUsername();
             }else{
-                message('Invite Error',' '+response.data,activeInfo.settings.notifications.position,'#FFF','warning','5000');
+                message('Invite Error',' '+response.message,activeInfo.settings.notifications.position,'#FFF','warning','5000');
             }
     	}).fail(function(xhr) {
     		console.error("Organizr Function: API Connection Failed");
@@ -124,19 +105,19 @@ function joinEmby(){
         message('Invite Error',' Please Enter Email',activeInfo.settings.notifications.position,'#FFF','warning','5000');
     }else if(password.val() == ''){
         password.focus();
-        message('Invite Error',' Please Enter Passowrd',activeInfo.settings.notifications.position,'#FFF','warning','5000');
+        message('Invite Error',' Please Enter Password',activeInfo.settings.notifications.position,'#FFF','warning','5000');
     }
     if(email.val() !== '' && username.val() !== '' && password.val() !== ''){
-        organizrAPI('POST','api/?v1/emby/join',{username:username.val(), email:email.val(), password:password.val()}).success(function(data) {
-    		var response = JSON.parse(data);
-            if(response.data === true){
+        organizrAPI2('POST','api/v2/emby/register',{username:username.val(), email:email.val(), password:password.val()}).success(function(data) {
+    		var response = data.response;
+            if(response.result === 'success'){
                 $('.invite-step-3-emby-no').toggleClass('hidden');
                 $('.invite-step-3-emby-yes').toggleClass('hidden');
                 message('Invite Function',' User Created',activeInfo.settings.notifications.position,'#FFF','success','5000');
                 $('#inviteUsernameInviteEmby').val(username.val());
                 hasEmbyUsername();
             }else{
-                message('Invite Error',' '+response.data,activeInfo.settings.notifications.position,'#FFF','warning','5000');
+                message('Invite Error',' '+response.message,activeInfo.settings.notifications.position,'#FFF','warning','5000');
             }
     	}).fail(function(xhr) {
     		console.error("Organizr Function: API Connection Failed");
@@ -176,22 +157,19 @@ function hasPlexUsername(){
         message('Invite Error',' Please Enter Username',activeInfo.settings.notifications.position,'#FFF','warning','5000');
     }else{
         var post = {
-            plugin:'Invites/codes',
-            action:'use',
-            code:code,
             usedby:username.val()
         };
         ajaxloader(".content-wrap","in");
-        organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-            var response = JSON.parse(data);
-            if(response.data === true){
+        organizrAPI2('POST','api/v2/plugins/invites/' + code,post).success(function(data) {
+            var response = data.response;
+            if(response.result === 'success'){
                 $('.invite-step-3-plex-yes').toggleClass('hidden');
                 $('.invite-step-4-plex-accept').toggleClass('hidden');
                 if(local('get', 'invite')){
             		local('remove', 'invite');
             	}
             }else{
-                message('Invite Error',' Code Incorrect',activeInfo.settings.notifications.position,'#FFF','warning','5000');
+                message('Invite Error',response.message,activeInfo.settings.notifications.position,'#FFF','warning','5000');
             }
             ajaxloader();;
         }).fail(function(xhr) {
@@ -208,22 +186,19 @@ function hasEmbyUsername(){
         message('Invite Error',' Please Enter Username',activeInfo.settings.notifications.position,'#FFF','warning','5000');
     }else{
         var post = {
-            plugin:'Invites/codes',
-            action:'use',
-            code:code,
             usedby:username.val()
         };
         ajaxloader(".content-wrap","in");
-        organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-            var response = JSON.parse(data);
-            if(response.data === true){
+        organizrAPI2('POST','api/v2/plugins/invites/' + code,post).success(function(data) {
+	        var response = data.response;
+	        if(response.result === 'success'){
                 $('.invite-step-3-emby-yes').toggleClass('hidden');
                 $('.invite-step-4-emby-accept').toggleClass('hidden');
                 if(local('get', 'invite')){
             		local('remove', 'invite');
             	}
             }else{
-                message('Invite Error',' Code Incorrect',activeInfo.settings.notifications.position,'#FFF','warning','5000');
+                message('Invite Error',response.message,activeInfo.settings.notifications.position,'#FFF','warning','5000');
             }
             ajaxloader();;
         }).fail(function(xhr) {
@@ -234,19 +209,14 @@ function hasEmbyUsername(){
 }
 function verifyInvite(){
     var code = $('#inviteCodeInput').val().toUpperCase();
-    var post = {
-        plugin:'Invites/codes',
-        action:'check',
-        code:code
-    };
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
-        if(response.data === true){
+    organizrAPI2('GET','api/v2/plugins/invites/'+code).success(function(data) {
+        var response = data.response;
+        if(response.result === 'success'){
             $('.invite-step-1').toggleClass('hidden');
             $('.invite-step-2').toggleClass('hidden');
         }else{
-            message('Invite Error',' Code Incorrect',activeInfo.settings.notifications.position,'#FFF','warning','5000');
+            message('Invite Error',response.message,activeInfo.settings.notifications.position,'#FFF','warning','5000');
         }
         if(local('get', 'invite')){
             local('remove', 'invite');
@@ -286,15 +256,13 @@ function createNewInvite(){
 
     if(email.val() !== '' && username.val() !== ''){
         var post = {
-            plugin:'Invites/codes',
-            action:'create',
             code:createRandomString(6).toUpperCase(),
             email:email.val(),
             username:username.val(),
         };
         ajaxloader(".content-wrap","in");
-        organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-            var response = JSON.parse(data);
+        organizrAPI2('POST','api/v2/plugins/invites',post).success(function(data) {
+            var response = data.response;
             $.magnificPopup.close();
             ajaxloader();
             message('Invite',' Invite Created',activeInfo.settings.notifications.position,'#FFF','success','5000');
@@ -306,15 +274,10 @@ function createNewInvite(){
     }
 
 }
-function deleteInvite(id){
-    var post = {
-        plugin:'Invites/codes',
-        action:'delete',
-        id:id,
-    };
+function deleteInvite(code, id){
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
+    organizrAPI2('DELETE','api/v2/plugins/invites/' + code).success(function(data) {
+        var response = data.response;
         $('#inviteItem-'+id).remove();
         //$.magnificPopup.close();
         ajaxloader();
@@ -347,7 +310,7 @@ function buildInvites(array){
             <td>`+v.usedby+`</td>
             <td>`+v.ip+`</td>
             <td>`+v.valid+`</td>
-            <td><button type="button" class="btn btn-danger btn-outline btn-circle btn-lg m-r-5" onclick="deleteInvite('`+v.id+`');"><i class="ti-trash"></i></button></td>
+            <td><button type="button" class="btn btn-danger btn-outline btn-circle btn-lg m-r-5" onclick="deleteInvite('`+v.code+`','`+v.id+`');"><i class="ti-trash"></i></button></td>
         </tr>
         `;
     });
@@ -356,13 +319,9 @@ function buildInvites(array){
 $(document).on('click', '.inviteModal', function() {
     var htmlDOM = '';
     if (activeInfo.user.loggedin === true && activeInfo.user.groupID <= 1) {
-        var post = {
-            plugin:'Invites/codes',
-            action:'get',
-        };
         ajaxloader(".content-wrap","in");
-        organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-            var response = JSON.parse(data);
+        organizrAPI2('GET','api/v2/plugins/invites').success(function(data) {
+            var response = data.response;
             var htmlDOM = '';
             htmlDOM = `
             <div class="col-md-12">
@@ -496,47 +455,10 @@ $(document).on('click', '.inviteModal', function() {
     }
 });
 
-// CHANGE CUSTOMIZE Options
-$(document).on('change asColorPicker::close', '#INVITES-settings-page1 :input', function(e) {
-    var input = $(this);
-    switch ($(this).attr('type')) {
-        case 'switch':
-        case 'checkbox':
-            var value = $(this).prop("checked") ? true : false;
-            break;
-        default:
-            var value = $(this).val().toString();
-    }
-	var post = {
-        api:'api/?v1/update/config',
-        name:$(this).attr("name"),
-        type:$(this).attr("data-type"),
-        value:value,
-        messageTitle:'',
-        messageBody:'Updated Value for '+$(this).parent().parent().find('label').text(),
-        error:'Organizr Function: API Connection Failed'
-    };
-	var callbacks = $.Callbacks();
-    //callbacks.add( buildCustomizeAppearance );
-    settingsAPI(post,callbacks);
-    //disable button then renable
-    $('#INVITES-settings-page :input').prop('disabled', 'true');
-    setTimeout(
-        function(){
-            $('#INVITES-settings-page :input').prop('disabled', null);
-            input.emulateTab();
-        },
-        2000
-    );
-
-});
 $(document).on('click', '#INVITES-settings-button', function() {
-    var post = {
-        plugin:'Invites/settings/get', // used for switch case in your API call
-    };
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
+    organizrAPI2('GET','api/v2/plugins/invites/settings').success(function(data) {
+        var response = data.response;
         $('#INVITES-settings-items').html(buildFormGroup(response.data));
         $('.selectpicker').selectpicker();
     }).fail(function(xhr) {

+ 20 - 79
api/plugins/js/php-mailer.js

@@ -1,22 +1,4 @@
 /* PHP MAILER JS FILE */
-/*
-$(document).on('click', '#PHPMAILER-settings-button', function() {
-	var post = {
-        plugin:'PHPMailer/settings/get', // used for switch case in your API call
-        api:'api/?v1/plugin', // API Endpoint will always be this for custom plugin API calls
-        name:$(this).attr('data-plugin-name'),
-        configName:$(this).attr('data-config-name'),
-        messageTitle:'', // Send succees message title (top line)
-        messageBody:'Disabled '+$(this).attr('data-plugin-name'), // Send succees message body (bottom line)
-        error:'Organizr Function: API Connection Failed' // conole error message
-    };
-	var callbacks = $.Callbacks(); // init callbacks var
-    //callbacks.add(  ); // add function to callback to be fired after API call
-    //settingsAPI(post,callbacks); // exec API call
-    //ajaxloader(".content-wrap","in");
-    //setTimeout(function(){ buildPlugins();ajaxloader(); }, 3000);
-});
-*/
 
 // FUNCTIONS
 phpmLaunch();
@@ -53,22 +35,23 @@ function sendMail(){
         messageSingle('','Please Enter Subject',activeInfo.settings.notifications.position,'#FFF','error','5000');
     }else if(body == ''){
         messageSingle('','Please Enter Body',activeInfo.settings.notifications.position,'#FFF','error','5000');
+    }else{
+	    messageSingle('','Sending Message',activeInfo.settings.notifications.position,'#FFF','success','5000');
     }
     if(to !== '' && subject !== '' && body !== ''){
         var post = {
-            plugin:'PHPMailer/send/email', // used for switch case in your API call
             bcc:to,
             subject:subject,
             body:body
         };
         ajaxloader(".content-wrap","in");
-        organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-            var response = JSON.parse(data);
-            if(response.data == true){
+        organizrAPI2('POST','api/v2/plugins/php-mailer/email/send',post).success(function(data) {
+            var response = data.response;
+            if(response.result == 'success'){
                 $.magnificPopup.close();
                 messageSingle('',window.lang.translate('Email Sent Successful'),activeInfo.settings.notifications.position,'#FFF','success','5000');
             }else{
-                messageSingle('',response.data,activeInfo.settings.notifications.position,'#FFF','error','5000');
+                messageSingle('',response.message,activeInfo.settings.notifications.position,'#FFF','error','5000');
             }
         }).fail(function(xhr) {
             console.error("Organizr Function: API Connection Failed");
@@ -209,12 +192,9 @@ $(document).on("change", "#email-user-list", function () {
     $('#sendEmailToInput').val($('#email-user-list').val());
 });
 $(document).on('click', '.loadUserList', function() {
-    var post = {
-        plugin:'PHPMailer/users/get', // used for switch case in your API call
-    };
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
+    organizrAPI2('GET','api/v2/plugins/php-mailer/email/list').success(function(data) {
+        var response = data.response;
         $('#user-list-div').html(buildUserList(response.data));
         $('#email-user-list').multiSelect();
     }).fail(function(xhr) {
@@ -251,47 +231,10 @@ function addForgotPassword(){
         }
     }
 }
-// CHANGE CUSTOMIZE Options
-$(document).on('change asColorPicker::close', '#PHPMAILER-settings-page1 :input', function(e) {
-    var input = $(this);
-    switch ($(this).attr('type')) {
-        case 'switch':
-        case 'checkbox':
-            var value = $(this).prop("checked") ? true : false;
-            break;
-        default:
-            var value = $(this).val();
-    }
-	var post = {
-        api:'api/?v1/update/config',
-        name:$(this).attr("name"),
-        type:$(this).attr("data-type"),
-        value:value,
-        messageTitle:'',
-        messageBody:'Updated Value for '+$(this).parent().parent().find('label').text(),
-        error:'Organizr Function: API Connection Failed'
-    };
-	var callbacks = $.Callbacks();
-    //callbacks.add( buildCustomizeAppearance );
-    settingsAPI(post,callbacks);
-    //disable button then renable
-    $('#PHPMAILER-settings-page :input').prop('disabled', 'true');
-    setTimeout(
-        function(){
-            $('#PHPMAILER-settings-page :input').prop('disabled', null);
-            input.emulateTab();
-        },
-        2000
-    );
-
-});
 $(document).on('click', '#PHPMAILER-settings-button', function() {
-    var post = {
-        plugin:'PHPMailer/settings/get', // used for switch case in your API call
-    };
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
+    organizrAPI2('GET','api/v2/plugins/php-mailer/settings').success(function(data) {
+        var response = data.response;
         $('#PHPMAILER-settings-items').html(buildFormGroup(response.data));
     }).fail(function(xhr) {
         console.error("Organizr Function: API Connection Failed");
@@ -301,21 +244,19 @@ $(document).on('click', '#PHPMAILER-settings-button', function() {
 // SEND TEST EMAIL
 $(document).on('click', '.phpmSendTestEmail', function() {
     messageSingle('',window.lang.translate('Sending Test E-Mail'),activeInfo.settings.notifications.position,'#FFF','info','5000');
-    var post = {
-        plugin:'PHPMailer/send/test', // used for switch case in your API call
-    };
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
-        if(response.data == true){
-            messageSingle('',window.lang.translate('Email Test Successful'),activeInfo.settings.notifications.position,'#FFF','success','5000');
-        }else if(response.data.indexOf('|||DEBUG|||') == 0) {
-            messageSingle('',window.lang.translate('Press F11 to check Console for output'),activeInfo.settings.notifications.position,'#FFF','warning','20000');
-            console.warn(response.data);
+    organizrAPI2('GET','api/v2/plugins/php-mailer/email/test').success(function(data) {
+        var response = data.response;
+        if(response.message !== null && response.message.indexOf('|||DEBUG|||') == 0){
+            messageSingle('',window.lang.translate('Press F11 to check Console for output'),activeInfo.settings.notifications.position,'#FFF','warning','5000');
+	        console.warn(response.message);
+        }else if(response.result == 'success') {
+            messageSingle('',window.lang.translate('Email Test Successful'),activeInfo.settings.notifications.position,'#FFF','success','20000');
         }else{
-            messageSingle('',response.data,activeInfo.settings.notifications.position,'#FFF','error','5000');
+            messageSingle('',response.message,activeInfo.settings.notifications.position,'#FFF','error','5000');
         }
-    }).fail(function(xhr) {
+    }).fail(function(xhr, data) {
+    	console.log(data)
         console.error("Organizr Function: API Connection Failed");
     });
     ajaxloader();

+ 3 - 58
api/plugins/js/speedTest.js

@@ -1,22 +1,4 @@
-/* PHP MAILER JS FILE */
-/*
-$(document).on('click', '#PHPMAILER-settings-button', function() {
-	var post = {
-        plugin:'PHPMailer/settings/get', // used for switch case in your API call
-        api:'api/?v1/plugin', // API Endpoint will always be this for custom plugin API calls
-        name:$(this).attr('data-plugin-name'),
-        configName:$(this).attr('data-config-name'),
-        messageTitle:'', // Send succees message title (top line)
-        messageBody:'Disabled '+$(this).attr('data-plugin-name'), // Send succees message body (bottom line)
-        error:'Organizr Function: API Connection Failed' // conole error message
-    };
-	var callbacks = $.Callbacks(); // init callbacks var
-    //callbacks.add(  ); // add function to callback to be fired after API call
-    //settingsAPI(post,callbacks); // exec API call
-    //ajaxloader(".content-wrap","in");
-    //setTimeout(function(){ buildPlugins();ajaxloader(); }, 3000);
-});
-*/
+/* SPEEDTEST JS FILE */
 function clamp(num, min, max) {
   return num <= min ? min : num >= max ? max : num;
 }
@@ -143,47 +125,10 @@ function speedTestLaunch(){
     }
 }
 
-// CHANGE CUSTOMIZE Options
-$(document).on('change asColorPicker::close', '#SPEEDTEST-settings-page1 :input', function(e) {
-    var input = $(this);
-    switch ($(this).attr('type')) {
-        case 'switch':
-        case 'checkbox':
-            var value = $(this).prop("checked") ? true : false;
-            break;
-        default:
-            var value = $(this).val().toString();
-    }
-	var post = {
-        api:'api/?v1/update/config',
-        name:$(this).attr("name"),
-        type:$(this).attr("data-type"),
-        value:value,
-        messageTitle:'',
-        messageBody:'Updated Value for '+$(this).parent().parent().find('label').text(),
-        error:'Organizr Function: API Connection Failed'
-    };
-	var callbacks = $.Callbacks();
-    //callbacks.add( buildCustomizeAppearance );
-    settingsAPI(post,callbacks);
-    //disable button then renable
-    $('#SPEEDTEST-settings-page :input').prop('disabled', 'true');
-    setTimeout(
-        function(){
-            $('#SPEEDTEST-settings-page :input').prop('disabled', null);
-            input.emulateTab();
-        },
-        2000
-    );
-
-});
 $(document).on('click', '#SPEEDTEST-settings-button', function() {
-    var post = {
-        plugin:'SpeedTest/settings/get', // used for switch case in your API call
-    };
     ajaxloader(".content-wrap","in");
-    organizrAPI('POST','api/?v1/plugin',post).success(function(data) {
-        var response = JSON.parse(data);
+    organizrAPI2('GET','api/v2/plugins/speedtest/settings').success(function(data) {
+        var response = data.response;
         $('#SPEEDTEST-settings-items').html(buildFormGroup(response.data));
     }).fail(function(xhr) {
         console.error("Organizr Function: API Connection Failed");

+ 4 - 4
api/plugins/misc/emailTemplates/default.php

@@ -10,7 +10,7 @@ switch ($extra) {
                             <tbody>
                                 <tr>
                                     <td align="center" valign="middle" class="mcnButtonContent" style="font-family: Helvetica; font-size: 18px; padding: 18px;">
-                                        <a class="mcnButton " title="Button Text" href="' . getServerPath(true) . '?invite=' . $email['inviteCode'] . '" target="_self" style="font-weight: bold;letter-spacing: -0.5px;line-height: 100%;text-align: center;text-decoration: none;color: #FFFFFF;">Use Invite Code</a>
+                                        <a class="mcnButton " title="Button Text" href="' . $this->getServerPath(true) . '?invite=' . $email['inviteCode'] . '" target="_self" style="font-weight: bold;letter-spacing: -0.5px;line-height: 100%;text-align: center;text-decoration: none;color: #FFFFFF;">Use Invite Code</a>
                                     </td>
                                 </tr>
                             </tbody>
@@ -31,7 +31,7 @@ switch ($extra) {
                             <tbody>
                                 <tr>
                                     <td align="center" valign="middle" class="mcnButtonContent" style="font-family: Helvetica; font-size: 18px; padding: 18px;">
-                                        <a class="mcnButton " title="Reset Password" href="' . getServerPath(true) . '" target="_self" style="font-weight: bold;letter-spacing: -0.5px;line-height: 100%;text-align: center;text-decoration: none;color: #FFFFFF;">Goto My Site</a>
+                                        <a class="mcnButton " title="Reset Password" href="' . $this->getServerPath(true) . '" target="_self" style="font-weight: bold;letter-spacing: -0.5px;line-height: 100%;text-align: center;text-decoration: none;color: #FFFFFF;">Goto My Site</a>
                                     </td>
                                 </tr>
                             </tbody>
@@ -68,7 +68,7 @@ $info = '
                                     <tbody>
                                         <tr>
                                             <td valign="top" class="mcnTextContent" style="padding: 18px;">
-                                                <h3 style="text-align:center;">' . getServerPath(true) . '</h3>
+                                                <h3 style="text-align:center;">' . $this->getServerPath(true) . '</h3>
                                             </td>
                                         </tr>
                                     </tbody>
@@ -850,7 +850,7 @@ $email = '
                                                                     <tr>
                                                                         <td class="mcnImageContent" valign="top" style="padding-right: 9px; padding-left: 9px; padding-top: 0; padding-bottom: 0; text-align:center;">
 
-                                                                            <img align="center" alt="" src="' . $GLOBALS['PHPMAILER-logo'] . '" width="564" style="max-width:700px; padding-bottom: 0; display: inline !important; vertical-align: bottom;" class="mcnImage">
+                                                                            <img align="center" alt="" src="' . $this->config['PHPMAILER-logo'] . '" width="564" style="max-width:700px; padding-bottom: 0; display: inline !important; vertical-align: bottom;" class="mcnImage">
 
                                                                         </td>
                                                                     </tr>

+ 2 - 2
api/plugins/misc/emailTemplates/gray.php

@@ -11,7 +11,7 @@ switch ($extra) {
 								<hr style="margin-top: 10px; height: 1px; overflow: hidden; border: 0; border-bottom: 1px solid #e9e9e9;">
 							</td>
 							<td style="font-family: \'Helvetica\', Arial, sans-serif; color: #73747C; padding: 0; text-align: left;" width="175">
-								<a class="button orange nowrap" href="' . getServerPath(true) . '?invite=' . $email['inviteCode'] . '" rel="noopener noreferrer" style="text-decoration:none;color:#ffffff;white-space:nowrap;display:inline-block;padding:6px 15px 6px 15px;font-size:16px;border-radius:3px;background-color:#E74D39;margin:0 15px;">Use Invite Code</a>
+								<a class="button orange nowrap" href="' . $this->getServerPath(true) . '?invite=' . $email['inviteCode'] . '" rel="noopener noreferrer" style="text-decoration:none;color:#ffffff;white-space:nowrap;display:inline-block;padding:6px 15px 6px 15px;font-size:16px;border-radius:3px;background-color:#E74D39;margin:0 15px;">Use Invite Code</a>
 							</td>
 							<td style="font-family: \'Helvetica\', Arial, sans-serif; color: #73747C; padding: 0; text-align: left;" width="50%">
 								<hr style="margin-top: 10px; height: 1px; overflow: hidden; border: 0; border-bottom: 1px solid #e9e9e9;">
@@ -34,7 +34,7 @@ switch ($extra) {
 								<hr style="margin-top: 10px; height: 1px; overflow: hidden; border: 0; border-bottom: 1px solid #e9e9e9;">
 							</td>
 							<td style="font-family: \'Helvetica\', Arial, sans-serif; color: #73747C; padding: 0; text-align: left;" width="175">
-								<a class="button orange nowrap" href="' . getServerPath(true) . '" rel="noopener noreferrer" style="text-decoration:none;color:#ffffff;white-space:nowrap;display:inline-block;padding:6px 15px 6px 15px;font-size:16px;border-radius:3px;background-color:#E74D39;margin:0 15px;">Goto My Site</a>
+								<a class="button orange nowrap" href="' . $this->getServerPath(true) . '" rel="noopener noreferrer" style="text-decoration:none;color:#ffffff;white-space:nowrap;display:inline-block;padding:6px 15px 6px 15px;font-size:16px;border-radius:3px;background-color:#E74D39;margin:0 15px;">Goto My Site</a>
 							</td>
 							<td style="font-family: \'Helvetica\', Arial, sans-serif; color: #73747C; padding: 0; text-align: left;" width="50%">
 								<hr style="margin-top: 10px; height: 1px; overflow: hidden; border: 0; border-bottom: 1px solid #e9e9e9;">

+ 16 - 16
api/plugins/misc/emailTemplates/light.php

@@ -1,24 +1,24 @@
 <?php
 switch ($extra) {
-    case 'invite':
-        $button = '
+	case 'invite':
+		$button = '
 		<center>
-			<a href="'.getServerPath(true).'?invite='.$email['inviteCode'].'" style="display: inline-block; padding: 11px 30px; margin: 20px 0px 30px; font-size: 15px; color: #fff; background: #1e88e5; border-radius: 60px; text-decoration:none;">Use Invite Code</a>
+			<a href="' . $this->getServerPath(true) . '?invite=' . $email['inviteCode'] . '" style="display: inline-block; padding: 11px 30px; margin: 20px 0px 30px; font-size: 15px; color: #fff; background: #1e88e5; border-radius: 60px; text-decoration:none;">Use Invite Code</a>
 		</center>
         ';
-        break;
-    case 'reset':
-        $button = '
+		break;
+	case 'reset':
+		$button = '
 		<center>
-			<a href="'.getServerPath(true).'" style="display: inline-block; padding: 11px 30px; margin: 20px 0px 30px; font-size: 15px; color: #fff; background: #1e88e5; border-radius: 60px; text-decoration:none;">Goto My Site</a>
+			<a href="' . $this->getServerPath(true) . '" style="display: inline-block; padding: 11px 30px; margin: 20px 0px 30px; font-size: 15px; color: #fff; background: #1e88e5; border-radius: 60px; text-decoration:none;">Goto My Site</a>
 		</center>
         ';
-        break;
-    default:
-        $button = null;
-        break;
+		break;
+	default:
+		$button = null;
+		break;
 }
- $email = '
+$email = '
  <!DOCTYPE html>
  <html>
  <head>
@@ -33,14 +33,14 @@ switch ($extra) {
  				<tbody>
  					<tr>
  						<td align="center" style="vertical-align: top; padding-bottom:30px;"><a href="javascript:void(0)" target="_blank"><br>
- 						<img alt="admin Responsive web app kit" src="'.$GLOBALS['PHPMAILER-logo'].'" style="border:none;width: 100%;"></a></td>
+ 						<img alt="admin Responsive web app kit" src="' . $this->config['PHPMAILER-logo'] . '" style="border:none;width: 100%;"></a></td>
  					</tr>
  				</tbody>
  			</table>
  			<table border="0" cellpadding="0" cellspacing="0" style="width: 100%;">
  				<tbody>
  					<tr>
- 						<td style="background: #1e88e5;padding:20px;color:#fff;text-align:center;">'.$subject.'</td>
+ 						<td style="background: #1e88e5;padding:20px;color:#fff;text-align:center;">' . $subject . '</td>
  					</tr>
  				</tbody>
  			</table>
@@ -49,8 +49,8 @@ switch ($extra) {
  					<tbody>
  						<tr>
  							<td>
- 								<p>'.$body.'</p>
- 								'.$button.'
+ 								<p>' . $body . '</p>
+ 								' . $button . '
  							</td>
  						</tr>
  					</tbody>

+ 3 - 3
api/plugins/misc/emailTemplates/plehex.php

@@ -5,7 +5,7 @@ switch ($extra) {
 		<tr>
 			<td align="center" valign="top">
 				<div>
-					<a href="' . getServerPath(true) . '?invite=' . $email['inviteCode'] . '" rel="noopener noreferrer" style="background-color: #e5a00d; border: 2px solid #E5A00D; border-radius: 100px; color: #ffffff; display: inline-block; font-family: \'Roboto\', Helvetica, Arial, sans-serif; font-size: 13px; font-weight: bold; line-height: 44px; text-align: center; text-decoration: none; width: 260px; -webkit-text-size-adjust: none; mso-hide: all;">Use Invite Code</a>
+					<a href="' . $this->getServerPath(true) . '?invite=' . $email['inviteCode'] . '" rel="noopener noreferrer" style="background-color: #e5a00d; border: 2px solid #E5A00D; border-radius: 100px; color: #ffffff; display: inline-block; font-family: \'Roboto\', Helvetica, Arial, sans-serif; font-size: 13px; font-weight: bold; line-height: 44px; text-align: center; text-decoration: none; width: 260px; -webkit-text-size-adjust: none; mso-hide: all;">Use Invite Code</a>
 				</div>
 			</td>
 		</tr>
@@ -19,7 +19,7 @@ switch ($extra) {
 		<tr>
 			<td align="center" valign="top">
 				<div>
-					<a href="' . getServerPath(true) . '" rel="noopener noreferrer" style="background-color: #e5a00d; border: 2px solid #E5A00D; border-radius: 100px; color: #ffffff; display: inline-block; font-family: \'Roboto\', Helvetica, Arial, sans-serif; font-size: 13px; font-weight: bold; line-height: 44px; text-align: center; text-decoration: none; width: 260px; -webkit-text-size-adjust: none; mso-hide: all;">Goto My Site</a>
+					<a href="' . $this->getServerPath(true) . '" rel="noopener noreferrer" style="background-color: #e5a00d; border: 2px solid #E5A00D; border-radius: 100px; color: #ffffff; display: inline-block; font-family: \'Roboto\', Helvetica, Arial, sans-serif; font-size: 13px; font-weight: bold; line-height: 44px; text-align: center; text-decoration: none; width: 260px; -webkit-text-size-adjust: none; mso-hide: all;">Goto My Site</a>
 				</div>
 			</td>
 		</tr>
@@ -127,7 +127,7 @@ $email = '
 						<tbody>
 							<tr>
 								<td align="center" class="header" valign="top">
-									<a href="' . getServerPath(true) . '" rel="noopener noreferrer"><img border="0" src="' . $GLOBALS['PHPMAILER-logo'] . '" style="display: block;" width="50%"></a>
+									<a href="' . $this->getServerPath(true) . '" rel="noopener noreferrer"><img border="0" src="' . $this->config['PHPMAILER-logo'] . '" style="display: block;" width="50%"></a>
 								</td>
 							</tr>
 						</tbody>

+ 491 - 465
api/plugins/php-mailer.php

@@ -1,5 +1,4 @@
 <?php
-/** @noinspection PhpUnusedLocalVariableInspection */
 // PLUGIN INFORMATION
 $GLOBALS['plugins'][]['PHP Mailer'] = array( // Plugin Name
 	'name' => 'PHP Mailer', // Plugin Name
@@ -7,9 +6,6 @@ $GLOBALS['plugins'][]['PHP Mailer'] = array( // Plugin Name
 	'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
-	//'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 hyphen
 	'version' => '1.0.0', // SemVer of plugin
@@ -17,496 +13,526 @@ $GLOBALS['plugins'][]['PHP Mailer'] = array( // Plugin Name
 	'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()
+
+class PhpMailer extends Organizr
 {
-	if ($GLOBALS['authBackend']) {
-		if ($GLOBALS['authBackend'] == 'plex') {
-			$type = 'plex';
+	public function _phpMailerPluginGetEmails()
+	{
+		$type = null;
+		if ($this->config['authBackend']) {
+			if ($this->config['authBackend'] == 'plex') {
+				$type = 'plex';
+			}
+		}
+		if ($type == 'plex') {
+			$emails = array_merge($this->userList('plex')['both'], $this->_phpMailerPluginGetOrgUsers());
+		} elseif ($type == 'emby') {
+			$emails = $this->_phpMailerPluginGetOrgUsers();
+		} else {
+			$emails = $this->_phpMailerPluginGetOrgUsers();
 		}
-	} else {
-		$type = 'none';
+		return $emails;
 	}
-	if ($type == 'plex') {
-		$emails = array_merge(userList('plex')['both'], getOrgUsers());
-	} elseif ($type == 'emby') {
-		$emails = getOrgUsers();
-	} else {
-		$emails = getOrgUsers();
+	
+	public function _phpMailerPluginGetOrgUsers()
+	{
+		$return = null;
+		$result = $this->getAllUsers(true);
+		if (is_array($result) || is_object($result)) {
+			foreach ($result['users'] as $k => $v) {
+				$return[$v['username']] = $v['email'];
+			}
+			return ($return) ?? false;
+		}
 	}
-	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))
-		);
+	
+	public function _phpMailerPluginGetTemplates()
+	{
+		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;
 	}
-	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 phpmBuildEmail($email)
-{
-	/** @noinspection PhpUnusedLocalVariableInspection */
-	$subject = (isset($email['subject'])) ? $email['subject'] : 'Message from Server';
-	$body = (isset($email['body'])) ? $email['body'] : 'Message Error Occurred';
-	$type = (isset($email['type'])) ? $email['type'] : 'No Type';
-	switch ($type) {
-		case 'invite':
-			$extra = 'invite';
-			break;
-		case 'reset':
-			$extra = 'reset';
-			break;
-		default:
-			$extra = null;
-			break;
+	
+	public function _phpMailerPluginEmailTemplate($emailTemplate)
+	{
+		$variables = [
+			'{user}' => $emailTemplate['user'],
+			'{domain}' => $this->getServerPath(true),
+			'{password}' => $emailTemplate['password'],
+			'{inviteCode}' => $emailTemplate['inviteCode'],
+			'{fullDomain}' => $this->getServerPath(true),
+			'{title}' => $this->config['title'],
+		];
+		$emailTemplate['body'] = strtr($emailTemplate['body'], $variables);
+		$emailTemplate['subject'] = strtr($emailTemplate['subject'], $variables);
+		return $emailTemplate;
 	}
-	include('misc/emailTemplates/' . $GLOBALS['PHPMAILER-template'] . '.php');
-	return $email;
-}
-
-function phpmAdminSendEmail()
-{
-	if ($GLOBALS['PHPMAILER-enabled']) {
+	
+	public function _phpMailerPluginBuildEmail($email)
+	{
+		/** @noinspection PhpUnusedLocalVariableInspection */
+		$subject = (isset($email['subject'])) ? $email['subject'] : 'Message from Server';
+		$body = (isset($email['body'])) ? $email['body'] : 'Message Error Occurred';
+		$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/' . $this->config['PHPMAILER-template'] . '.php');
+		return $email;
+	}
+	
+	public function _phpMailerPluginAdminSendEmail($array)
+	{
+		if ($this->config['PHPMAILER-enabled']) {
+			$emailTemplate = array(
+				'type' => 'admin',
+				'body' => $array['body'],
+				'subject' => $array['subject'],
+				'user' => null,
+				'password' => null,
+				'inviteCode' => null,
+			);
+			$emailTemplate = $this->_phpMailerPluginEmailTemplate($emailTemplate);
+			$sendEmail = array(
+				'bcc' => $array['bcc'],
+				'subject' => $emailTemplate['subject'],
+				'body' => $this->_phpMailerPluginBuildEmail($emailTemplate),
+			);
+			$response = $this->_phpMailerPluginSendEmail($sendEmail);
+			if ($response == true) {
+				$msg = ($this->config['PHPMAILER-debugTesting']) ? $this->config['phpmOriginalDebug'] : 'Email sent';
+				$this->setAPIResponse('success', $msg, 200);
+			} else {
+				$this->setAPIResponse('error', $response, 409);
+				return false;
+			}
+			return true;
+		} else {
+			$this->setAPIResponse('error', 'PHP-Mailer is not enabled', 409);
+			return false;
+		}
+		return false;
+	}
+	
+	public function _phpMailerPluginGetDebug($str, $level)
+	{
+		$this->config['phpmOriginalDebug'] = $this->config['phpmOriginalDebug'] . $str;
+		return $this->config['phpmOriginalDebug'];
+	}
+	
+	public function _phpMailerPluginSendTestEmail()
+	{
 		$emailTemplate = array(
-			'type' => 'admin',
-			'body' => $_POST['data']['body'],
-			'subject' => $_POST['data']['subject'],
+			'type' => 'test',
+			'body' => 'This is just a test email.',
+			'subject' => 'Test E-Mail',
 			'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 phpmGetDebug($str, $level){
-	$GLOBALS['phpmOriginalDebug'] = $GLOBALS['phpmOriginalDebug'] . $str;
-	return $GLOBALS['phpmOriginalDebug'];
-}
-function phpmSendTestEmail()
-{
-	$emailTemplate = array(
-		'type' => 'test',
-		'body' => 'This is just a test email.',
-		'subject' => 'Test E-Mail',
-		'user' => null,
-		'password' => null,
-		'inviteCode' => null,
-	);
-	$emailTemplate = phpmEmailTemplate($emailTemplate);
-	$GLOBALS['phpmOriginalDebug'] = '|||DEBUG|||';
-	try {
-		$mail = new PHPMailer\PHPMailer\PHPMailer(true);
-		$mail->SMTPDebug = 2;
-		$mail->isSMTP();
-		$mail->Debugoutput = function($str, $level) {phpmGetDebug($str, $level);};
-		$mail->Host = $GLOBALS['PHPMAILER-smtpHost'];
-		$mail->Port = $GLOBALS['PHPMAILER-smtpHostPort'];
-		if ($GLOBALS['PHPMAILER-smtpHostType'] !== 'n/a') {
-			$mail->SMTPSecure = $GLOBALS['PHPMAILER-smtpHostType'];
+		$emailTemplate = $this->_phpMailerPluginEmailTemplate($emailTemplate);
+		$this->config['phpmOriginalDebug'] = '|||DEBUG|||';
+		try {
+			$mail = new PHPMailer\PHPMailer\PHPMailer(true);
+			$mail->SMTPDebug = 2;
+			$mail->isSMTP();
+			$mail->Debugoutput = function ($str, $level) {
+				$this->_phpMailerPluginGetDebug($str, $level);
+			};
+			$mail->Host = $this->config['PHPMAILER-smtpHost'];
+			$mail->Port = $this->config['PHPMAILER-smtpHostPort'];
+			if ($this->config['PHPMAILER-smtpHostType'] !== 'n/a') {
+				$mail->SMTPSecure = $this->config['PHPMAILER-smtpHostType'];
+			}
+			$mail->SMTPAuth = $this->config['PHPMAILER-smtpHostAuth'];
+			$mail->Username = $this->config['PHPMAILER-smtpHostUsername'];
+			$mail->Password = $this->decrypt($this->config['PHPMAILER-smtpHostPassword']);
+			$mail->SMTPOptions = array(
+				'ssl' => [
+					'verify_peer' => $this->config['PHPMAILER-verifyCert'],
+					'verify_depth' => 3,
+					'allow_self_signed' => true,
+					'peer_name' => $this->config['PHPMAILER-smtpHost'],
+					'cafile' => $this->getCert(),
+				],
+			);
+			$mail->setFrom($this->config['PHPMAILER-smtpHostSenderEmail'], $this->config['PHPMAILER-smtpHostSenderName']);
+			$mail->addReplyTo($this->config['PHPMAILER-smtpHostSenderEmail'], $this->config['PHPMAILER-smtpHostSenderName']);
+			$mail->isHTML(true);
+			$mail->addAddress($this->user['email'], $this->user['username']);
+			$mail->Subject = $emailTemplate['subject'];
+			$mail->Body = $this->_phpMailerPluginBuildEmail($emailTemplate);
+			$mail->send();
+			$this->writeLog('success', 'Mail Function -  E-Mail Test Sent', $this->user['username']);
+			$msg = ($this->config['PHPMAILER-debugTesting']) ? $this->config['phpmOriginalDebug'] : 'Email sent';
+			$this->setAPIResponse('success', $msg, 200);
+			return true;
+		} catch (PHPMailer\PHPMailer\Exception $e) {
+			$this->writeLog('error', 'Mail Function -  E-Mail Test Failed[' . $mail->ErrorInfo . ']', $this->user['username']);
+			$this->setAPIResponse('error', $e->getMessage(), 500);
+			return false;
 		}
-		$mail->SMTPAuth = $GLOBALS['PHPMAILER-smtpHostAuth'];
-		$mail->Username = $GLOBALS['PHPMAILER-smtpHostUsername'];
-		$mail->Password = decrypt($GLOBALS['PHPMAILER-smtpHostPassword']);
-		$mail->SMTPOptions = array(
-			'ssl' => [
-				'verify_peer' => $GLOBALS['PHPMAILER-verifyCert'],
-				'verify_depth' => 3,
-				'allow_self_signed' => true,
-				'peer_name' => $GLOBALS['PHPMAILER-smtpHost'],
-				'cafile' => getCert(),
-			],
-		);
-		$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 = $emailTemplate['subject'];
-		$mail->Body = phpmBuildEmail($emailTemplate);
-		$mail->send();
-		writeLog('success', 'Mail Function -  E-Mail Test Sent', $GLOBALS['organizrUser']['username']);
-		return ($GLOBALS['PHPMAILER-debugTesting']) ? $GLOBALS['phpmOriginalDebug'] : true;
-	} catch (PHPMailer\PHPMailer\Exception $e) {
-		writeLog('error', 'Mail Function -  E-Mail Test Failed[' . $mail->ErrorInfo . ']', $GLOBALS['organizrUser']['username']);
-		return ($GLOBALS['PHPMAILER-debugTesting']) ? $GLOBALS['phpmOriginalDebug'] : $e->errorMessage();
+		return false;
 	}
-	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';
-	try {
-		$mail = new PHPMailer\PHPMailer\PHPMailer(true);
-		$mail->isSMTP();
-		//$mail->SMTPDebug = 3;
-		$mail->Host = $GLOBALS['PHPMAILER-smtpHost'];
-		$mail->Port = $GLOBALS['PHPMAILER-smtpHostPort'];
-		if ($GLOBALS['PHPMAILER-smtpHostType'] !== 'n/a') {
-			$mail->SMTPSecure = $GLOBALS['PHPMAILER-smtpHostType'];
-		}
-		$mail->SMTPAuth = $GLOBALS['PHPMAILER-smtpHostAuth'];
-		$mail->Username = $GLOBALS['PHPMAILER-smtpHostUsername'];
-		$mail->Password = decrypt($GLOBALS['PHPMAILER-smtpHostPassword']);
-		$mail->SMTPOptions = array(
-			'ssl' => [
-				'verify_peer' => $GLOBALS['PHPMAILER-verifyCert'],
-				'verify_depth' => 3,
-				'allow_self_signed' => true,
-				'peer_name' => $GLOBALS['PHPMAILER-smtpHost'],
-				'cafile' => getCert(),
-			],
-		);
-		$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);
+	
+	public function _phpMailerPluginSendEmail($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 = $this->config['PHPMAILER-smtpHost'];
+			$mail->Port = $this->config['PHPMAILER-smtpHostPort'];
+			if ($this->config['PHPMAILER-smtpHostType'] !== 'n/a') {
+				$mail->SMTPSecure = $this->config['PHPMAILER-smtpHostType'];
+			}
+			$mail->SMTPAuth = $this->config['PHPMAILER-smtpHostAuth'];
+			$mail->Username = $this->config['PHPMAILER-smtpHostUsername'];
+			$mail->Password = $this->decrypt($this->config['PHPMAILER-smtpHostPassword']);
+			$mail->SMTPOptions = array(
+				'ssl' => [
+					'verify_peer' => $this->config['PHPMAILER-verifyCert'],
+					'verify_depth' => 3,
+					'allow_self_signed' => true,
+					'peer_name' => $this->config['PHPMAILER-smtpHost'],
+					'cafile' => $this->getCert(),
+				],
+			);
+			$mail->setFrom($this->config['PHPMAILER-smtpHostSenderEmail'], $this->config['PHPMAILER-smtpHostSenderName']);
+			$mail->addReplyTo($this->config['PHPMAILER-smtpHostSenderEmail'], $this->config['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();
+			return true;
+		} catch (PHPMailer\PHPMailer\Exception $e) {
+			$this->writeLog('error', 'Mail Function -  E-Mail Test Failed[' . $mail->ErrorInfo . ']', $this->user['username']);
+			return $e->errorMessage();
 		}
-		$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' => 'n/a'
-					)
+	
+	/* GET PHPMAILER SETTINGS */
+	public function _phpMailerPluginGetSettings()
+	{
+		return array(
+			'Host' => array(
+				array(
+					'type' => 'input',
+					'name' => 'PHPMAILER-smtpHost',
+					'label' => 'SMTP Host',
+					'value' => $this->config['PHPMAILER-smtpHost']
+				),
+				array(
+					'type' => 'input',
+					'name' => 'PHPMAILER-smtpHostPort',
+					'label' => 'SMTP Port',
+					'value' => $this->config['PHPMAILER-smtpHostPort']
 				)
 			),
-			array(
-				'type' => 'switch',
-				'name' => 'PHPMAILER-verifyCert',
-				'label' => 'Verify Certificate',
-				'value' => $GLOBALS['PHPMAILER-verifyCert']
-			),
-		),
-		'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' => 'switch',
-				'name' => 'PHPMAILER-debugTesting',
-				'label' => 'Enable Debug Output on Email Test',
-				'value' => $GLOBALS['PHPMAILER-debugTesting'],
-			),
-			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()
+			'Authentication' => array(
+				array(
+					'type' => 'input',
+					'name' => 'PHPMAILER-smtpHostUsername',
+					'label' => 'Username',
+					'value' => $this->config['PHPMAILER-smtpHostUsername']
+				),
+				array(
+					'type' => 'password',
+					'name' => 'PHPMAILER-smtpHostPassword',
+					'label' => 'Password',
+					'value' => $this->config['PHPMAILER-smtpHostPassword']
+				),
+				array(
+					'type' => 'switch',
+					'name' => 'PHPMAILER-smtpHostAuth',
+					'label' => 'Authentication',
+					'value' => $this->config['PHPMAILER-smtpHostAuth']
+				),
+				array(
+					'type' => 'select',
+					'name' => 'PHPMAILER-smtpHostType',
+					'label' => 'Authentication Type',
+					'value' => $this->config['PHPMAILER-smtpHostType'],
+					'options' => array(
+						array(
+							'name' => 'tls',
+							'value' => 'tls'
+						),
+						array(
+							'name' => 'ssl',
+							'value' => 'ssl'
+						),
+						array(
+							'name' => 'off',
+							'value' => 'n/a'
+						)
+					)
+				),
+				array(
+					'type' => 'switch',
+					'name' => 'PHPMAILER-verifyCert',
+					'label' => 'Verify Certificate',
+					'value' => $this->config['PHPMAILER-verifyCert']
+				),
 			),
-			array(
-				'type' => 'input',
-				'name' => 'PHPMAILER-logo',
-				'label' => 'WAN Logo URL',
-				'value' => $GLOBALS['PHPMAILER-logo'],
-				'placeholder' => 'Full URL',
+			'Sender Information' => array(
+				array(
+					'type' => 'input',
+					'name' => 'PHPMAILER-smtpHostSenderName',
+					'label' => 'Sender Name',
+					'value' => $this->config['PHPMAILER-smtpHostSenderName']
+				),
+				array(
+					'type' => 'input',
+					'name' => 'PHPMAILER-smtpHostSenderEmail',
+					'label' => 'Sender Email',
+					'value' => $this->config['PHPMAILER-smtpHostSenderEmail'],
+					'placeholder' => 'i.e. same as username'
+				)
 			),
-			array(
-				'type' => 'switch',
-				'name' => 'PHPMAILER-emailTemplateRegisterUserEnabled',
-				'label' => 'Send Welcome E-Mail',
-				'value' => $GLOBALS['PHPMAILER-emailTemplateRegisterUserEnabled'],
+			'Test & Options' => array(
+				array(
+					'type' => 'button',
+					'label' => 'Send Test',
+					'class' => 'phpmSendTestEmail',
+					'icon' => 'fa fa-paper-plane',
+					'text' => 'Send'
+				),
+				array(
+					'type' => 'switch',
+					'name' => 'PHPMAILER-debugTesting',
+					'label' => 'Enable Debug Output on Email Test',
+					'value' => $this->config['PHPMAILER-debugTesting'],
+				),
+				array(
+					'type' => 'input',
+					'name' => 'PHPMAILER-domain',
+					'label' => 'Domain Link Override',
+					'value' => $this->config['PHPMAILER-domain'],
+					'placeholder' => 'https://domain.com/',
+				),
+				array(
+					'type' => 'select',
+					'name' => 'PHPMAILER-template',
+					'label' => 'Theme',
+					'value' => $this->config['PHPMAILER-template'],
+					'options' => $this->_phpMailerPluginGetTemplates()
+				),
+				array(
+					'type' => 'input',
+					'name' => 'PHPMAILER-logo',
+					'label' => 'WAN Logo URL',
+					'value' => $this->config['PHPMAILER-logo'],
+					'placeholder' => 'Full URL',
+				),
+				array(
+					'type' => 'switch',
+					'name' => 'PHPMAILER-emailTemplateRegisterUserEnabled',
+					'label' => 'Send Welcome E-Mail',
+					'value' => $this->config['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"',
+			'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' => $this->config['PHPMAILER-emailTemplateRegisterUserSubject'],
+								),
+								array(
+									'type' => 'textbox',
+									'name' => 'PHPMAILER-emailTemplateRegisterUser',
+									'smallLabel' => 'Body',
+									'value' => $this->config['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-emailTemplateResetPasswordForm',
+							'header' => 'Reset Password',
+							'body' => array(
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateResetSubject',
+									'smallLabel' => 'Subject',
+									'value' => $this->config['PHPMAILER-emailTemplateResetSubject'],
+								),
+								array(
+									'type' => 'textbox',
+									'name' => 'PHPMAILER-emailTemplateReset',
+									'smallLabel' => 'Body',
+									'value' => $this->config['PHPMAILER-emailTemplateReset'],
+									'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-emailTemplateInviteUserForm',
+							'header' => 'Invite User',
+							'body' => array(
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateInviteUserSubject',
+									'smallLabel' => 'Subject',
+									'value' => $this->config['PHPMAILER-emailTemplateInviteUserSubject'],
+								),
+								array(
+									'type' => 'textbox',
+									'name' => 'PHPMAILER-emailTemplateInviteUser',
+									'smallLabel' => 'Body',
+									'value' => $this->config['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-OneForm',
+							'header' => $this->config['PHPMAILER-emailTemplateCustom-include-OneName'],
+							'body' => array(
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-OneName',
+									'smallLabel' => 'Name',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-OneName'],
+								),
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-OneSubject',
+									'smallLabel' => 'Subject',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-OneSubject'],
+								),
+								array(
+									'type' => 'textbox',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-One',
+									'smallLabel' => 'Body',
+									'value' => $this->config['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-TwoForm',
+							'header' => $this->config['PHPMAILER-emailTemplateCustom-include-TwoName'],
+							'body' => array(
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-TwoName',
+									'smallLabel' => 'Name',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-TwoName'],
+								),
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-TwoSubject',
+									'smallLabel' => 'Subject',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-TwoSubject'],
+								),
+								array(
+									'type' => 'textbox',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-Two',
+									'smallLabel' => 'Body',
+									'value' => $this->config['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-ThreeForm',
+							'header' => $this->config['PHPMAILER-emailTemplateCustom-include-ThreeName'],
+							'body' => array(
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-ThreeName',
+									'smallLabel' => 'Name',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-ThreeName'],
+								),
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-ThreeSubject',
+									'smallLabel' => 'Subject',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-ThreeSubject'],
+								),
+								array(
+									'type' => 'textbox',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-Three',
+									'smallLabel' => 'Body',
+									'value' => $this->config['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"',
+						),
+						array(
+							'id' => 'PHPMAILER-emailTemplateCustom-include-FourForm',
+							'header' => $this->config['PHPMAILER-emailTemplateCustom-include-FourName'],
+							'body' => array(
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-FourName',
+									'smallLabel' => 'Name',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-FourName'],
+								),
+								array(
+									'type' => 'input',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-FourSubject',
+									'smallLabel' => 'Subject',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-FourSubject'],
+								),
+								array(
+									'type' => 'textbox',
+									'name' => 'PHPMAILER-emailTemplateCustom-include-Four',
+									'smallLabel' => 'Body',
+									'value' => $this->config['PHPMAILER-emailTemplateCustom-include-Four'],
+									'attr' => 'rows="10"',
+								)
 							)
-						)
-					),
+						),
+					)
 				)
 			)
-		)
-	);
+		);
+	}
 }

+ 26 - 31
api/plugins/speedTest.php

@@ -1,38 +1,33 @@
 <?php
-
 // PLUGIN INFORMATION
 $GLOBALS['plugins'][]['SpeedTest'] = array( // Plugin Name
-    'name'=>'SpeedTest', // Plugin Name
-    '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
-    //'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
-    '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
-    'homepage'=>false // Is plugin for use on homepage? true or false
+	'name' => 'SpeedTest', // Plugin Name
+	'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
+	'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
+	'homepage' => false // Is plugin for use on homepage? true or false
 );
-// INCLUDE/REQUIRE FILES
-
-// PLUGIN FUNCTIONS
 
-/* GET PHPMAILER SETTINGS */
-function speedTestGetSettings()
+class SpeedTest extends Organizr
 {
-    return array(
-        'Options' => array(
-            array(
-                'type' => 'select',
-                'name' => 'SPEEDTEST-Auth-include',
-                'label' => 'Minimum Authentication',
-                'value' => $GLOBALS['SPEEDTEST-Auth-include'],
-                'options' => groupSelect()
-            )
-        )
-    );
+	public function speedTestGetSettings()
+	{
+		return array(
+			'Options' => array(
+				array(
+					'type' => 'select',
+					'name' => 'SPEEDTEST-Auth-include',
+					'label' => 'Minimum Authentication',
+					'value' => $this->config['SPEEDTEST-Auth-include'],
+					'options' => $this->groupSelect()
+				)
+			)
+		);
+	}
 }