diff --git a/docker/Config.php b/docker/Config.php index 0d85ae593b..a3f668238d 100644 --- a/docker/Config.php +++ b/docker/Config.php @@ -13,7 +13,7 @@ $sUSER = 'churchcrm'; $sPASSWORD = 'changeme'; $sDATABASE = 'churchcrm'; -#$TwoFASecretKey = 'ChangeThisToASecureRandomStringBeforeUse'; +//$TwoFASecretKey = 'ChangeThisToASecureRandomStringBeforeUse'; // Root path of your ChurchCRM installation ( THIS MUST BE SET CORRECTLY! ) // @@ -29,7 +29,7 @@ // Set $bLockURL=TRUE to enforce https access by specifying exactly // which URL's your users may use to log into ChurchCRM. -$bLockURL = FALSE; +$bLockURL = false; // URL[0] is the URL that you prefer most users use when they // log in. These are case sensitive. @@ -60,5 +60,4 @@ // // Absolute path must be specified since this file is called // from scripts located in other directories -require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'LoadConfigs.php'); -?> +require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'LoadConfigs.php'; diff --git a/locale/extract-db-locale-terms.php b/locale/extract-db-locale-terms.php index 821ad4c627..77cce97755 100644 --- a/locale/extract-db-locale-terms.php +++ b/locale/extract-db-locale-terms.php @@ -4,29 +4,28 @@ echo "========== Building locale from DB started === \n"; echo "=============================================== \n\n"; -$filename = "../BuildConfig.json"; +$filename = '../BuildConfig.json'; if (file_exists($filename)) { - $buildConfig = file_get_contents($filename); $config = json_decode($buildConfig, true); - if (empty($config["Env"]["local"]["database"])) { + if (empty($config['Env']['local']['database'])) { echo "ERROR: The file $filename does not have local db env, check ".$filename.".example for schema\n"; } else { - $localDBEnv = $config["Env"]["local"]["database"]; + $localDBEnv = $config['Env']['local']['database']; - $db_server = $localDBEnv["server"]; - $db_port = $localDBEnv["port"]; + $db_server = $localDBEnv['server']; + $db_port = $localDBEnv['port']; - $db_name = $localDBEnv["database"]; - $db_username = $localDBEnv["user"]; - $db_password = $localDBEnv["password"]; + $db_name = $localDBEnv['database']; + $db_username = $localDBEnv['user']; + $db_password = $localDBEnv['password']; $stringsDir = 'db-strings'; $stringFiles = []; - $db = new PDO('mysql:host=' . $db_server . ':' . $db_port . ';dbname=' . $db_name . ';charset=utf8mb4', $db_username, $db_password); + $db = new PDO('mysql:host='.$db_server.':'.$db_port.';dbname='.$db_name.';charset=utf8mb4', $db_username, $db_password); $query = 'select DISTINCT ucfg_tooltip as term, "" as translation, "userconfig_ucfg" as cntx from userconfig_ucfg union all select DISTINCT qry_Name as term, "" as translation, "query_qry" as cntx from query_qry @@ -42,42 +41,41 @@ echo "DB read complete \n"; foreach ($db->query($query) as $row) { - $stringFile = $stringsDir . '/' . $row['cntx'] . '.php'; + $stringFile = $stringsDir.'/'.$row['cntx'].'.php'; if (!file_exists($stringFile)) { file_put_contents($stringFile, "", FILE_APPEND); } - $stringFile = $stringsDir . '/settings-countries.php'; + $stringFile = $stringsDir.'/settings-countries.php'; require '../src/ChurchCRM/data/Countries.php'; require '../src/ChurchCRM/data/Country.php'; file_put_contents($stringFile, "", FILE_APPEND); - $stringFile = $stringsDir . '/settings-locales.php'; + $stringFile = $stringsDir.'/settings-locales.php'; file_put_contents($stringFile, " $value) { - file_put_contents($stringFile, 'gettext("' . $key . "\");\r\n", FILE_APPEND); + file_put_contents($stringFile, 'gettext("'.$key."\");\r\n", FILE_APPEND); } file_put_contents($stringFile, "\r\n?>", FILE_APPEND); - echo $stringFile . " updated"; + echo $stringFile.' updated'; } } else { echo "ERROR: The file $filename does not exist \n"; - } echo "\n\n=============================================== \n"; echo "========== Building locale from DB end === \n"; diff --git a/scripts/restore-db.php b/scripts/restore-db.php index 777ad7e3b5..f9f1ad5fd8 100644 --- a/scripts/restore-db.php +++ b/scripts/restore-db.php @@ -1,42 +1,42 @@ select_db($sDATABASE); - echo "Connected to database\n"; - echo "Deleting all tables\n"; + $mysqli = new mysqli($sSERVERNAME, $sUSER, $sPASSWORD, $sDATABASE, $dbPort); + if (mysqli_connect_errno()) { + throw new \Exception('Failed to connect to MySQL: '.mysqli_connect_error()); + } + $mysqli->select_db($sDATABASE); + echo "Connected to database\n"; + echo "Deleting all tables\n"; - if ($result = $mysqli->query("SHOW TABLES")) - { - while($row = $result->fetch_array(MYSQLI_NUM)) - { - $mysqli->query('DROP TABLE IF EXISTS '.$row[0]); - } - } - // this is a bit hacky, but anything left in TABLES here must be a view - if ($result = $mysqli->query("SHOW TABLES")) - { - while($row = $result->fetch_array(MYSQLI_NUM)) - { - $mysqli->query('DROP VIEW IF EXISTS '.$row[0]); - } - } - $mysqli->query('SET foreign_key_checks = 1'); - echo "Tables deleted\n"; - if ($restoreDemoDb) { - echo "restoring demo db\n"; - SQLUtils::sqlImport(dirname(__FILE__)."/../demo/ChurchCRM-Database.sql", $mysqli); - echo "Demo db restored\n\n"; - } + if ($result = $mysqli->query('SHOW TABLES')) { + while ($row = $result->fetch_array(MYSQLI_NUM)) { + $mysqli->query('DROP TABLE IF EXISTS '.$row[0]); + } + } + // this is a bit hacky, but anything left in TABLES here must be a view + if ($result = $mysqli->query('SHOW TABLES')) { + while ($row = $result->fetch_array(MYSQLI_NUM)) { + $mysqli->query('DROP VIEW IF EXISTS '.$row[0]); + } + } + $mysqli->query('SET foreign_key_checks = 1'); + echo "Tables deleted\n"; + if ($restoreDemoDb) { + echo "restoring demo db\n"; + SQLUtils::sqlImport(dirname(__FILE__).'/../demo/ChurchCRM-Database.sql', $mysqli); + echo "Demo db restored\n\n"; + } +} catch (\Exception $e) { + echo "Error restoring database: $e"; } -catch (\Exception $e) { - echo "Error restoring database: $e"; -} \ No newline at end of file diff --git a/scripts/update-demo-site.php b/scripts/update-demo-site.php index 0619dbeffb..786a234c4a 100644 --- a/scripts/update-demo-site.php +++ b/scripts/update-demo-site.php @@ -1,37 +1,39 @@ curl_file_create($uploadFile), - 'branch' => $currentBranch, - 'commitHash' => $commitHash, - 'demoKey' => GetDemoKey() - )); + [ + 'fileupload' => curl_file_create($uploadFile), + 'branch' => $currentBranch, + 'commitHash' => $commitHash, + 'demoKey' => GetDemoKey(), + ] +); // output the response curl_setopt($request, CURLOPT_RETURNTRANSFER, true); @@ -55,4 +58,4 @@ function GetBranchName() { print_r($result); // close the session -curl_close($request); \ No newline at end of file +curl_close($request); diff --git a/src/CSVCreateFile.php b/src/CSVCreateFile.php index 241e2d9845..b31c06b601 100644 --- a/src/CSVCreateFile.php +++ b/src/CSVCreateFile.php @@ -14,14 +14,14 @@ require 'Include/Functions.php'; use ChurchCRM\dto\Cart; +use ChurchCRM\dto\Classification; use ChurchCRM\dto\SystemConfig; +use ChurchCRM\FamilyQuery; use ChurchCRM\Utils\InputUtils; use ChurchCRM\Utils\MiscUtils; -use ChurchCRM\dto\Classification; use ChurchCRM\Utils\RedirectUtils; -use ChurchCRM\FamilyQuery; -$delimiter = SystemConfig::getValue("sCSVExportDelimiter"); +$delimiter = SystemConfig::getValue('sCSVExportDelimiter'); // Turn ON output buffering ob_start(); @@ -46,7 +46,7 @@ } //Get membership classes -$memberClass = array(0); +$memberClass = [0]; foreach (Classification::getAll() as $Member) { $memberClass[] = $Member->getOptionName(); } @@ -210,7 +210,7 @@ Cart::AddPerson($per_ID); } //// TODO: do this in API - RedirectUtils::Redirect("v2/cart"); + RedirectUtils::Redirect('v2/cart'); } else { // Build the complete SQL statement @@ -226,90 +226,90 @@ $rsLabelsToWrite = RunQuery($sSQL); //Produce Header Based on Selected Fields - $headerString = '"'.InputUtils::translate_special_charset("Family").' ID "'.$delimiter; + $headerString = '"'.InputUtils::translate_special_charset('Family').' ID "'.$delimiter; if ($sFormat == 'rollup') { - $headerString .= '"'.InputUtils::translate_special_charset("Name").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Name').'"'.$delimiter; // Add Salutation for family here... - $headerString .= '"'.InputUtils::translate_special_charset("Salutation").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Salutation').'"'.$delimiter; } else { - $headerString .= '"'.InputUtils::translate_special_charset("Person").' Id"'.$delimiter; - $headerString .= '"'.InputUtils::translate_special_charset("Last Name").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Person').' Id"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Last Name').'"'.$delimiter; if (!empty($_POST['Title'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Title").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Title').'"'.$delimiter; } if (!empty($_POST['FirstName'])) { - $headerString .= '"'.InputUtils::translate_special_charset("First Name").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('First Name').'"'.$delimiter; } if (!empty($_POST['Suffix'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Suffix").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Suffix').'"'.$delimiter; } if (!empty($_POST['MiddleName'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Middle Name").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Middle Name').'"'.$delimiter; } } if (!empty($_POST['Address1'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Address 1").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Address 1').'"'.$delimiter; } if (!empty($_POST['Address2'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Address 2").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Address 2').'"'.$delimiter; } if (!empty($_POST['City'])) { - $headerString .= '"'.InputUtils::translate_special_charset("City").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('City').'"'.$delimiter; } if (!empty($_POST['State'])) { - $headerString .= '"'.InputUtils::translate_special_charset("State").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('State').'"'.$delimiter; } if (!empty($_POST['Zip'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Zip").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Zip').'"'.$delimiter; } if (!empty($_POST['Country'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Country").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Country').'"'.$delimiter; } if (!empty($_POST['HomePhone'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Home Phone").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Home Phone').'"'.$delimiter; } if (!empty($_POST['WorkPhone'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Work Phone").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Work Phone').'"'.$delimiter; } if (!empty($_POST['CellPhone'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Cell Phone").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Cell Phone').'"'.$delimiter; } if (!empty($_POST['Email'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Email").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Email').'"'.$delimiter; } if (!empty($_POST['WorkEmail'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Work Email").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Work Email').'"'.$delimiter; } if (!empty($_POST['Envelope'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Envelope Number").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Envelope Number').'"'.$delimiter; } if (!empty($_POST['MembershipDate'])) { - $headerString .= '"'.InputUtils::translate_special_charset("MembershipDate").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('MembershipDate').'"'.$delimiter; } if ($sFormat == 'default') { if (!empty($_POST['BirthdayDate'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Birth Date").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Birth Date').'"'.$delimiter; } if (!empty($_POST['Age'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Age").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Age').'"'.$delimiter; } if (!empty($_POST['PrintMembershipStatus'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Classification").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Classification').'"'.$delimiter; } if (!empty($_POST['PrintFamilyRole'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Family Role").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Family Role').'"'.$delimiter; } if (!empty($_POST['PrintGender'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Gender").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Gender').'"'.$delimiter; } } else { if (!empty($_POST['Birthday Date'])) { - $headerString .= '"'.InputUtils::translate_special_charset("AnnivDate").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('AnnivDate').'"'.$delimiter; } if (!empty($_POST['Age'])) { - $headerString .= '"'.InputUtils::translate_special_charset("Anniv").'"'.$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset('Anniv').'"'.$delimiter; } } @@ -320,15 +320,15 @@ extract($aRow); if (isset($_POST["$custom_Field"])) { $bUsedCustomFields = true; - $headerString .= "\"".InputUtils::translate_special_charset($custom_Name)."\"".$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset($custom_Name).'"'.$delimiter; } } while ($aFamRow = mysqli_fetch_array($rsFamCustomFields)) { extract($aFamRow); - if (($aSecurityType[$fam_custom_FieldSec] == 'bAll') || ($_SESSION[$aSecurityType[$fam_custom_FieldSec]])) { + if (($aSecurityType[$fam_custom_FieldSec] == 'bAll') || $_SESSION[$aSecurityType[$fam_custom_FieldSec]]) { if (isset($_POST["$fam_custom_Field"])) { $bUsedCustomFields = true; - $headerString .= "\"".InputUtils::translate_special_charset($fam_custom_Name)."\"".$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset($fam_custom_Name).'"'.$delimiter; } } } @@ -337,10 +337,10 @@ if ($sFormat == 'rollup') { while ($aFamRow = mysqli_fetch_array($rsFamCustomFields)) { extract($aFamRow); - if (($aSecurityType[$fam_custom_FieldSec] == 'bAll') || ($_SESSION[$aSecurityType[$fam_custom_FieldSec]])) { + if (($aSecurityType[$fam_custom_FieldSec] == 'bAll') || $_SESSION[$aSecurityType[$fam_custom_FieldSec]]) { if (isset($_POST["$fam_custom_Field"])) { $bUsedCustomFields = true; - $headerString .= "\"".InputUtils::translate_special_charset($fam_custom_Name)."\"".$delimiter; + $headerString .= '"'.InputUtils::translate_special_charset($fam_custom_Name).'"'.$delimiter; } } } @@ -349,15 +349,14 @@ $headerString = mb_substr($headerString, 0, -1); $headerString .= "\n"; - header('Content-type: text/x-csv;charset='.SystemConfig::getValue("sCSVExportCharset")); - header('Content-Disposition: attachment; filename=churchcrm-export-'.date(SystemConfig::getValue("sDateFilenameFormat")).'.csv'); + header('Content-type: text/x-csv;charset='.SystemConfig::getValue('sCSVExportCharset')); + header('Content-Disposition: attachment; filename=churchcrm-export-'.date(SystemConfig::getValue('sDateFilenameFormat')).'.csv'); //add BOM to fix UTF-8 in Excel 2016 but not under, so the problem is solved with the sCSVExportCharset variable - if (SystemConfig::getValue("sCSVExportCharset") == "UTF-8") { + if (SystemConfig::getValue('sCSVExportCharset') == 'UTF-8') { echo "\xEF\xBB\xBF"; } - echo $headerString; while ($aRow = mysqli_fetch_array($rsLabelsToWrite)) { @@ -434,7 +433,7 @@ // ** should move this to the WHERE clause if (!($bSkipNoEnvelope && (strlen($fam_Envelope) == 0))) { // If we are doing family roll-up, we use a single, formatted name field - $sString = '"'.($fam_ID? $fam_ID : ""); + $sString = '"'.($fam_ID ? $fam_ID : ''); if ($sFormat == 'default') { $sString .= '"'.$delimiter.'"'.$per_ID; $sString .= '"'.$delimiter.'"'.$per_LastName; diff --git a/src/ChurchCRM/ArrayUtils.php b/src/ChurchCRM/ArrayUtils.php index 216e996d7b..2e6e605769 100644 --- a/src/ChurchCRM/ArrayUtils.php +++ b/src/ChurchCRM/ArrayUtils.php @@ -1,19 +1,18 @@ GetCurrentUser(); - if (empty($currentUser)) { - throw new \Exception("No current user provided by current authentication provider: " . get_class(self::GetAuthenticationProvider())); + public static function GetCurrentUser(): User + { + try { + $currentUser = self::GetAuthenticationProvider()->GetCurrentUser(); + if (empty($currentUser)) { + throw new \Exception('No current user provided by current authentication provider: '.get_class(self::GetAuthenticationProvider())); + } + + return $currentUser; + } catch (\Exception $e) { + LoggerUtils::getAppLogger()->debug('Failed to get current user: '.$e); + + throw $e; } - return $currentUser; - } - catch (\Exception $e){ - LoggerUtils::getAppLogger()->debug("Failed to get current user: " . $e); - throw $e; - } } - public static function EndSession($preventRedirect=false) { - $currentSessionUserName = "Unknown"; - try { - if (self::GetCurrentUser() != null) { - $currentSessionUserName = self::GetCurrentUser()->getName(); + public static function EndSession($preventRedirect = false) + { + $currentSessionUserName = 'Unknown'; + + try { + if (self::GetCurrentUser() != null) { + $currentSessionUserName = self::GetCurrentUser()->getName(); + } + } catch(\Exception $e) { + //unable to get name of user logging out. Don't really care. } - } - catch(\Exception $e) { - //unable to get name of user logging out. Don't really care. - } - try { - $result = self::GetAuthenticationProvider()->EndSession(); - $_COOKIE = []; - $_SESSION = []; - session_destroy(); - Bootstrapper::initSession(); - LoggerUtils::getAuthLogger()->info("Ended Local session for user " . $currentSessionUserName); - } - catch(\Exception $e) { - LoggerUtils::getAuthLogger()->warning("Error destroying session: " . $e); - } - finally { - if(!$preventRedirect) { - RedirectUtils::Redirect(self::GetSessionBeginURL()); + + try { + $result = self::GetAuthenticationProvider()->EndSession(); + $_COOKIE = []; + $_SESSION = []; + session_destroy(); + Bootstrapper::initSession(); + LoggerUtils::getAuthLogger()->info('Ended Local session for user '.$currentSessionUserName); + } catch(\Exception $e) { + LoggerUtils::getAuthLogger()->warning('Error destroying session: '.$e); + } finally { + if (!$preventRedirect) { + RedirectUtils::Redirect(self::GetSessionBeginURL()); + } } - } } - public static function Authenticate(AuthenticationRequest $AuthenticationRequest) { - switch (get_class($AuthenticationRequest)){ - case "ChurchCRM\Authentication\Requests\APITokenAuthenticationRequest": - $AuthenticationProvider = new APITokenAuthentication(); - self::SetAuthenticationProvider($AuthenticationProvider); - break; - case "ChurchCRM\Authentication\Requests\LocalUsernamePasswordRequest": - $AuthenticationProvider = new LocalAuthentication(); - self::SetAuthenticationProvider($AuthenticationProvider); - break; - case "ChurchCRM\Authentication\Requests\LocalTwoFactorTokenRequest": - try { - self::GetAuthenticationProvider(); - } - catch (\Exception $e) - { - LoggerUtils::getAppLogger()->warning("Tried to supply two factor authentication code, but didn't have an existing session. This shouldn't ever happen"); - } + public static function Authenticate(AuthenticationRequest $AuthenticationRequest) + { + switch (get_class($AuthenticationRequest)) { + case "ChurchCRM\Authentication\Requests\APITokenAuthenticationRequest": + $AuthenticationProvider = new APITokenAuthentication(); + self::SetAuthenticationProvider($AuthenticationProvider); + break; + case "ChurchCRM\Authentication\Requests\LocalUsernamePasswordRequest": + $AuthenticationProvider = new LocalAuthentication(); + self::SetAuthenticationProvider($AuthenticationProvider); + break; + case "ChurchCRM\Authentication\Requests\LocalTwoFactorTokenRequest": + try { + self::GetAuthenticationProvider(); + } catch (\Exception $e) { + LoggerUtils::getAppLogger()->warning("Tried to supply two factor authentication code, but didn't have an existing session. This shouldn't ever happen"); + } break; - default: - LoggerUtils::getAppLogger()->critical("Unknown AuthenticationRequest type supplied"); - break; - } + default: + LoggerUtils::getAppLogger()->critical('Unknown AuthenticationRequest type supplied'); + break; + } - $result = self::GetAuthenticationProvider()->Authenticate($AuthenticationRequest); + $result = self::GetAuthenticationProvider()->Authenticate($AuthenticationRequest); - if (null !== $result->nextStepURL){ - LoggerUtils::getAuthLogger()->debug("Authentication requires additional step: " . $result->nextStepURL); - RedirectUtils::Redirect($result->nextStepURL); - } + if (null !== $result->nextStepURL) { + LoggerUtils::getAuthLogger()->debug('Authentication requires additional step: '.$result->nextStepURL); + RedirectUtils::Redirect($result->nextStepURL); + } - if ($result->isAuthenticated && ! $result->preventRedirect) { - $redirectLocation = array_key_exists("location", $_SESSION) ? $_SESSION['location'] : 'Menu.php'; - NotificationService::updateNotifications(); - LoggerUtils::getAuthLogger()->debug("Authentication Successful; redirecting to: " . $redirectLocation); - RedirectUtils::Redirect($redirectLocation); + if ($result->isAuthenticated && !$result->preventRedirect) { + $redirectLocation = array_key_exists('location', $_SESSION) ? $_SESSION['location'] : 'Menu.php'; + NotificationService::updateNotifications(); + LoggerUtils::getAuthLogger()->debug('Authentication Successful; redirecting to: '.$redirectLocation); + RedirectUtils::Redirect($redirectLocation); + } - } - return $result; + return $result; } - public static function ValidateUserSessionIsActive($updateLastOperationTimestamp = true) { - try { - $result = self::GetAuthenticationProvider()->ValidateUserSessionIsActive($updateLastOperationTimestamp); - return $result->isAuthenticated; - } - catch (\Exception $error){ - LoggerUtils::getAuthLogger()->debug("Error determining session authentication status." . $error); - return false; - } + public static function ValidateUserSessionIsActive($updateLastOperationTimestamp = true) + { + try { + $result = self::GetAuthenticationProvider()->ValidateUserSessionIsActive($updateLastOperationTimestamp); + + return $result->isAuthenticated; + } catch (\Exception $error) { + LoggerUtils::getAuthLogger()->debug('Error determining session authentication status.'.$error); + + return false; + } } - public static function EnsureAuthentication() { - // This function differs from the sematinc `ValidateUserSessionIsActive` in that it will - // take corrective action to redirect the user to an appropriate login location - // if the current session is not actually authenticated - - try { - $result = self::GetAuthenticationProvider()->ValidateUserSessionIsActive(true); - // Auth providers will always include a `nextStepURL` if authentication fails. - // Sometimes other actions may require a `nextStepURL` that should be enforced with - // an authentication request (2FA, Expired Password, etc). - if (!$result->isAuthenticated){ - LoggerUtils::getAuthLogger()->debug("Session not authenticated. Redirecting to login page"); - RedirectUtils::Redirect(self::GetSessionBeginURL()); - }elseif(null !== $result->nextStepURL){ - LoggerUtils::getAuthLogger()->debug("Session authenticated, but redirect requested by authentication provider."); - RedirectUtils::Redirect($result->nextStepURL); + public static function EnsureAuthentication() + { + // This function differs from the sematinc `ValidateUserSessionIsActive` in that it will + // take corrective action to redirect the user to an appropriate login location + // if the current session is not actually authenticated + + try { + $result = self::GetAuthenticationProvider()->ValidateUserSessionIsActive(true); + // Auth providers will always include a `nextStepURL` if authentication fails. + // Sometimes other actions may require a `nextStepURL` that should be enforced with + // an authentication request (2FA, Expired Password, etc). + if (!$result->isAuthenticated) { + LoggerUtils::getAuthLogger()->debug('Session not authenticated. Redirecting to login page'); + RedirectUtils::Redirect(self::GetSessionBeginURL()); + } elseif (null !== $result->nextStepURL) { + LoggerUtils::getAuthLogger()->debug('Session authenticated, but redirect requested by authentication provider.'); + RedirectUtils::Redirect($result->nextStepURL); + } + LoggerUtils::getAuthLogger()->debug('Session valid'); + } catch (\Throwable $error) { + LoggerUtils::getAuthLogger()->debug('Error determining session authentication status. Redirecting to login page. '.$error); + RedirectUtils::Redirect(self::GetSessionBeginURL()); } - LoggerUtils::getAuthLogger()->debug("Session valid"); - } catch (\Throwable $error){ - LoggerUtils::getAuthLogger()->debug("Error determining session authentication status. Redirecting to login page. " . $error); - RedirectUtils::Redirect(self::GetSessionBeginURL()); - } } - public static function GetSessionBeginURL() { - return SystemURLs::getRootPath() . "/session/begin"; + public static function GetSessionBeginURL() + { + return SystemURLs::getRootPath().'/session/begin'; } - public static function GetForgotPasswordURL() { - // this assumes we're using local authentication - // TODO: when we implement other authentication providers (SAML/etc) - // this URL will need to be configuable by the system administrator - // since they likely will not want users attempting to reset ChurchCRM passwords - // but rather redirect users to some other password reset mechanism. - return SystemURLs::getRootPath() . "/session/forgot-password/reset-request"; + public static function GetForgotPasswordURL() + { + // this assumes we're using local authentication + // TODO: when we implement other authentication providers (SAML/etc) + // this URL will need to be configuable by the system administrator + // since they likely will not want users attempting to reset ChurchCRM passwords + // but rather redirect users to some other password reset mechanism. + return SystemURLs::getRootPath().'/session/forgot-password/reset-request'; } - } } diff --git a/src/ChurchCRM/Authentication/AuthenticationProviders/APITokenAuthentication.php b/src/ChurchCRM/Authentication/AuthenticationProviders/APITokenAuthentication.php index 9cec09695f..5c8542a1bf 100644 --- a/src/ChurchCRM/Authentication/AuthenticationProviders/APITokenAuthentication.php +++ b/src/ChurchCRM/Authentication/AuthenticationProviders/APITokenAuthentication.php @@ -1,60 +1,62 @@ currentUser; + } - public function GetCurrentUser() - { - return $this->currentUser; + public function Authenticate(AuthenticationRequest $AuthenticationRequest) + { + if (!$AuthenticationRequest instanceof APITokenAuthenticationRequest) { + throw new \Exception('Unable to process request as APITokenAuthenticationRequest'); } - - public function Authenticate(AuthenticationRequest $AuthenticationRequest) { - if (! $AuthenticationRequest instanceof APITokenAuthenticationRequest ) { - throw new \Exception ("Unable to process request as APITokenAuthenticationRequest"); - } - $authenticationResult = new AuthenticationResult(); - $authenticationResult->isAuthenticated = false; - $authenticationResult->preventRedirect = true; - $this->currentUser = UserQuery::create()->findOneByApiKey($AuthenticationRequest->APIToken); - - if (!empty($this->currentUser)) { - LoggerUtils::getAuthLogger()->debug(gettext("User authenticated via API Key: ") . $this->currentUser->getName()); - $authenticationResult->isAuthenticated = true; - } else { - LoggerUtils::getAuthLogger()->warning(gettext("Unsuccessful API Key authentication attempt")); - } - return $authenticationResult; + $authenticationResult = new AuthenticationResult(); + $authenticationResult->isAuthenticated = false; + $authenticationResult->preventRedirect = true; + $this->currentUser = UserQuery::create()->findOneByApiKey($AuthenticationRequest->APIToken); + + if (!empty($this->currentUser)) { + LoggerUtils::getAuthLogger()->debug(gettext('User authenticated via API Key: ').$this->currentUser->getName()); + $authenticationResult->isAuthenticated = true; + } else { + LoggerUtils::getAuthLogger()->warning(gettext('Unsuccessful API Key authentication attempt')); } - public function ValidateUserSessionIsActive($updateLastOperationTimestamp) : AuthenticationResult - { - // APITokens are sessionless, so just always say false. - $authenticationResult = new AuthenticationResult(); - $authenticationResult->isAuthenticated = false; - return $authenticationResult; - } + return $authenticationResult; + } - public function EndSession() { - $this->currentUser = null; - } + public function ValidateUserSessionIsActive($updateLastOperationTimestamp): AuthenticationResult + { + // APITokens are sessionless, so just always say false. + $authenticationResult = new AuthenticationResult(); + $authenticationResult->isAuthenticated = false; - public function GetPasswordChangeURL() { - throw new NotImplementedException(); - } + return $authenticationResult; } + public function EndSession() + { + $this->currentUser = null; + } + + public function GetPasswordChangeURL() + { + throw new NotImplementedException(); + } } diff --git a/src/ChurchCRM/Authentication/AuthenticationProviders/IAuthenticationProvider.php b/src/ChurchCRM/Authentication/AuthenticationProviders/IAuthenticationProvider.php index d242d6267f..623bae9267 100644 --- a/src/ChurchCRM/Authentication/AuthenticationProviders/IAuthenticationProvider.php +++ b/src/ChurchCRM/Authentication/AuthenticationProviders/IAuthenticationProvider.php @@ -1,12 +1,18 @@ getQRCodeUrl( - SystemConfig::getValue("s2FAApplicationName"), - $username, - $secret - ); - $qrCode = new QrCode($g2faUrl ); - $qrCode->setSize(300); - return $qrCode; + public static function GetTwoFactorQRCode($username, $secret): QrCode + { + $google2fa = new Google2FA(); + $g2faUrl = $google2fa->getQRCodeUrl( + SystemConfig::getValue('s2FAApplicationName'), + $username, + $secret + ); + $qrCode = new QrCode($g2faUrl); + $qrCode->setSize(300); + + return $qrCode; } - public function __construct() { + public function __construct() + { } public function GetCurrentUser() { - return $this->currentUser; + return $this->currentUser; } - public function EndSession() { - - if (!empty($this->currentUser)) { - //$this->currentUser->setDefaultFY($_SESSION['idefaultFY']); - $this->currentUser->setCurrentDeposit($_SESSION['iCurrentDeposit']); - $this->currentUser->save(); - $this->currentUser = null; - } - } + public function EndSession() + { + if (!empty($this->currentUser)) { + //$this->currentUser->setDefaultFY($_SESSION['idefaultFY']); + $this->currentUser->setCurrentDeposit($_SESSION['iCurrentDeposit']); + $this->currentUser->save(); + $this->currentUser = null; + } + } - private function prepareSuccessfulLoginOperations() { - // Set the LastLogin and Increment the LoginCount - $date = new DateTime('now', new DateTimeZone(SystemConfig::getValue('sTimeZone'))); - $this->currentUser->setLastLogin($date->format('Y-m-d H:i:s')); - $this->currentUser->setLoginCount($this->currentUser->getLoginCount() + 1); - $this->currentUser->setFailedLogins(0); - $this->currentUser->save(); + private function prepareSuccessfulLoginOperations() + { + // Set the LastLogin and Increment the LoginCount + $date = new DateTime('now', new DateTimeZone(SystemConfig::getValue('sTimeZone'))); + $this->currentUser->setLastLogin($date->format('Y-m-d H:i:s')); + $this->currentUser->setLoginCount($this->currentUser->getLoginCount() + 1); + $this->currentUser->setFailedLogins(0); + $this->currentUser->save(); - $_SESSION['bManageGroups'] = $this->currentUser->isManageGroupsEnabled(); - $_SESSION['bFinance'] = $this->currentUser->isFinanceEnabled(); + $_SESSION['bManageGroups'] = $this->currentUser->isManageGroupsEnabled(); + $_SESSION['bFinance'] = $this->currentUser->isFinanceEnabled(); - // Create the Cart - $_SESSION['aPeopleCart'] = []; + // Create the Cart + $_SESSION['aPeopleCart'] = []; - // Create the variable for the Global Message - $_SESSION['sGlobalMessage'] = ''; + // Create the variable for the Global Message + $_SESSION['sGlobalMessage'] = ''; - // Initialize the last operation time - $this->tLastOperationTimestamp = time(); + // Initialize the last operation time + $this->tLastOperationTimestamp = time(); - $_SESSION['bHasMagicQuotes'] = 0; + $_SESSION['bHasMagicQuotes'] = 0; - // Pledge and payment preferences - //$_SESSION['idefaultFY'] = CurrentFY(); // Improve the chance of getting the correct fiscal year assigned to new transactions - $_SESSION['iCurrentDeposit'] = $this->currentUser->getCurrentDeposit(); + // Pledge and payment preferences + //$_SESSION['idefaultFY'] = CurrentFY(); // Improve the chance of getting the correct fiscal year assigned to new transactions + $_SESSION['iCurrentDeposit'] = $this->currentUser->getCurrentDeposit(); } - public function Authenticate(AuthenticationRequest $AuthenticationRequest) { + public function Authenticate(AuthenticationRequest $AuthenticationRequest) + { + if (!($AuthenticationRequest instanceof LocalUsernamePasswordRequest || $AuthenticationRequest instanceof LocalTwoFactorTokenRequest)) { + throw new \Exception('Unable to process request as LocalUsernamePasswordRequest or LocalTwoFactorTokenRequest'); + } - if (!($AuthenticationRequest instanceof LocalUsernamePasswordRequest || $AuthenticationRequest instanceof LocalTwoFactorTokenRequest)) { - throw new \Exception ("Unable to process request as LocalUsernamePasswordRequest or LocalTwoFactorTokenRequest"); + $authenticationResult = new AuthenticationResult(); + + if ($AuthenticationRequest instanceof LocalUsernamePasswordRequest) { + LoggerUtils::getAuthLogger()->debug('Processing local login for'.$AuthenticationRequest->username); + // Get the information for the selected user + $this->currentUser = UserQuery::create()->findOneByUserName($AuthenticationRequest->username); + if ($this->currentUser == null) { + // Set the error text + $authenticationResult->isAuthenticated = false; + $authenticationResult->message = gettext('Invalid login or password'); + + return $authenticationResult; + } // Block the login if a maximum login failure count has been reached + elseif ($this->currentUser->isLocked()) { + $authenticationResult->isAuthenticated = false; + $authenticationResult->message = gettext('Too many failed logins: your account has been locked. Please contact an administrator.'); + LoggerUtils::getAuthLogger()->warning('Authentication attempt for locked account: '.$this->currentUser->getUserName()); + + return $authenticationResult; + } // Does the password match? + elseif (!$this->currentUser->isPasswordValid($AuthenticationRequest->password)) { + // Increment the FailedLogins + $this->currentUser->setFailedLogins($this->currentUser->getFailedLogins() + 1); + $this->currentUser->save(); + if (!empty($this->currentUser->getEmail()) && $this->currentUser->isLocked()) { + LoggerUtils::getAuthLogger()->warning('Too many failed logins for: '.$this->currentUser->getUserName().'. The account has been locked'); + $lockedEmail = new LockedEmail($this->currentUser); + $lockedEmail->send(); + } + $authenticationResult->isAuthenticated = false; + $authenticationResult->message = gettext('Invalid login or password'); + LoggerUtils::getAuthLogger()->warning('Invalid login attempt for: '.$this->currentUser->getUserName()); + + return $authenticationResult; + } elseif (SystemConfig::getBooleanValue('bEnable2FA') && $this->currentUser->is2FactorAuthEnabled()) { + // Only redirect the user to the 2FA sign-ing page if it's + // enabled both at system AND user level. + $authenticationResult->isAuthenticated = false; + $authenticationResult->nextStepURL = SystemURLs::getRootPath().'/session/two-factor'; + $this->bPendingTwoFactorAuth = true; + LoggerUtils::getAuthLogger()->info('User partially authenticated, pending 2FA: '.$this->currentUser->getUserName()); + + return $authenticationResult; + } elseif (SystemConfig::getBooleanValue('bRequire2FA') && !$this->currentUser->is2FactorAuthEnabled()) { + $authenticationResult->isAuthenticated = false; + $authenticationResult->message = gettext('Invalid login or password'); + LoggerUtils::getAuthLogger()->warning('User attempted login with valid credentials, but missing mandatory 2FA enrollment. Denying access for user: '.$this->currentUser->getUserName()); + + return $authenticationResult; + } else { + $this->prepareSuccessfulLoginOperations(); + $authenticationResult->isAuthenticated = true; + LoggerUtils::getAuthLogger()->info('User successfully logged in without 2FA: '.$this->currentUser->getUserName()); + + return $authenticationResult; + } + } elseif ($AuthenticationRequest instanceof LocalTwoFactorTokenRequest && $this->bPendingTwoFactorAuth) { + if ($this->currentUser->isTwoFACodeValid($AuthenticationRequest->TwoFACode)) { + $this->prepareSuccessfulLoginOperations(); + $authenticationResult->isAuthenticated = true; + $this->bPendingTwoFactorAuth = false; + LoggerUtils::getAuthLogger()->info('User successfully logged in with 2FA: '.$this->currentUser->getUserName()); + + return $authenticationResult; + } elseif ($this->currentUser->isTwoFaRecoveryCodeValid($AuthenticationRequest->TwoFACode)) { + $this->prepareSuccessfulLoginOperations(); + $authenticationResult->isAuthenticated = true; + $this->bPendingTwoFactorAuth = false; + LoggerUtils::getAuthLogger()->info('User successfully logged in with 2FA Recovery Code: '.$this->currentUser->getUserName()); + + return $authenticationResult; + } else { + LoggerUtils::getAuthLogger()->info('Invalid 2FA code provided by partially authenticated user: '.$this->currentUser->getUserName()); + $authenticationResult->isAuthenticated = false; + $authenticationResult->nextStepURL = SystemURLs::getRootPath().'/session/two-factor'; + + return $authenticationResult; + } + } } + public function ValidateUserSessionIsActive($updateLastOperationTimestamp): AuthenticationResult + { + $authenticationResult = new AuthenticationResult(); + + // First check to see if a `user` key exists on the session. + if (null == $this->currentUser) { + $authenticationResult->isAuthenticated = false; + LoggerUtils::getAuthLogger()->debug('No active user session.'); - $authenticationResult = new AuthenticationResult(); - - if ($AuthenticationRequest instanceof LocalUsernamePasswordRequest) { - LoggerUtils::getAuthLogger()->debug("Processing local login for" . $AuthenticationRequest->username); - // Get the information for the selected user - $this->currentUser = UserQuery::create()->findOneByUserName($AuthenticationRequest->username); - if ($this->currentUser == null) { - // Set the error text - $authenticationResult->isAuthenticated = false; - $authenticationResult->message = gettext('Invalid login or password'); - return $authenticationResult; - } // Block the login if a maximum login failure count has been reached - elseif ($this->currentUser->isLocked()) { - $authenticationResult->isAuthenticated = false; - $authenticationResult->message = gettext('Too many failed logins: your account has been locked. Please contact an administrator.'); - LoggerUtils::getAuthLogger()->warning("Authentication attempt for locked account: " . $this->currentUser->getUserName()); - return $authenticationResult; - } // Does the password match? - elseif (!$this->currentUser->isPasswordValid($AuthenticationRequest->password)) { - // Increment the FailedLogins - $this->currentUser->setFailedLogins($this->currentUser->getFailedLogins() + 1); - $this->currentUser->save(); - if (!empty($this->currentUser->getEmail()) && $this->currentUser->isLocked()) { - LoggerUtils::getAuthLogger()->warning("Too many failed logins for: " . $this->currentUser->getUserName() . ". The account has been locked"); - $lockedEmail = new LockedEmail($this->currentUser); - $lockedEmail->send(); - } - $authenticationResult->isAuthenticated = false; - $authenticationResult->message = gettext('Invalid login or password'); - LoggerUtils::getAuthLogger()->warning("Invalid login attempt for: " . $this->currentUser->getUserName()); - return $authenticationResult; - } elseif(SystemConfig::getBooleanValue("bEnable2FA") && $this->currentUser->is2FactorAuthEnabled()) { - // Only redirect the user to the 2FA sign-ing page if it's - // enabled both at system AND user level. - $authenticationResult->isAuthenticated = false; - $authenticationResult->nextStepURL = SystemURLs::getRootPath()."/session/two-factor"; - $this->bPendingTwoFactorAuth = true; - LoggerUtils::getAuthLogger()->info("User partially authenticated, pending 2FA: " . $this->currentUser->getUserName()); - return $authenticationResult; - } elseif(SystemConfig::getBooleanValue("bRequire2FA") && ! $this->currentUser->is2FactorAuthEnabled()) { - $authenticationResult->isAuthenticated = false; - $authenticationResult->message = gettext('Invalid login or password'); - LoggerUtils::getAuthLogger()->warning("User attempted login with valid credentials, but missing mandatory 2FA enrollment. Denying access for user: " . $this->currentUser->getUserName()); - return $authenticationResult; - } else { - $this->prepareSuccessfulLoginOperations(); - $authenticationResult->isAuthenticated = true; - LoggerUtils::getAuthLogger()->info("User successfully logged in without 2FA: " . $this->currentUser->getUserName()); return $authenticationResult; - } } - elseif($AuthenticationRequest instanceof LocalTwoFactorTokenRequest && $this->bPendingTwoFactorAuth) { - if ($this->currentUser->isTwoFACodeValid($AuthenticationRequest->TwoFACode)) { - $this->prepareSuccessfulLoginOperations(); - $authenticationResult->isAuthenticated = true; - $this->bPendingTwoFactorAuth = false; - LoggerUtils::getAuthLogger()->info("User successfully logged in with 2FA: " . $this->currentUser->getUserName()); - return $authenticationResult; - } - elseif($this->currentUser->isTwoFaRecoveryCodeValid($AuthenticationRequest->TwoFACode)){ - $this->prepareSuccessfulLoginOperations(); - $authenticationResult->isAuthenticated = true; - $this->bPendingTwoFactorAuth = false; - LoggerUtils::getAuthLogger()->info("User successfully logged in with 2FA Recovery Code: " . $this->currentUser->getUserName()); - return $authenticationResult; - } - else { - LoggerUtils::getAuthLogger()->info("Invalid 2FA code provided by partially authenticated user: " . $this->currentUser->getUserName()); + LoggerUtils::getAuthLogger()->debug('Processing session for user: '.$this->currentUser->getName()); + + // Next, make sure the user in the sesion still exists in the database. + try { + $this->currentUser->reload(); + } catch (\Exception $exc) { + LoggerUtils::getAuthLogger()->debug('User with active session no longer exists in the database. Expiring session'); + AuthenticationManager::EndSession(); $authenticationResult->isAuthenticated = false; - $authenticationResult->nextStepURL = SystemURLs::getRootPath()."/session/two-factor"; + return $authenticationResult; - } } - } - public function ValidateUserSessionIsActive($updateLastOperationTimestamp) : AuthenticationResult - { + // Next, check for login timeout. If login has expired, redirect to login page + if (SystemConfig::getValue('iSessionTimeout') > 0) { + if ((time() - $this->tLastOperationTimestamp) > SystemConfig::getValue('iSessionTimeout')) { + LoggerUtils::getAuthLogger()->debug('User session timed out'); + $authenticationResult->isAuthenticated = false; - $authenticationResult = new AuthenticationResult(); + return $authenticationResult; + } elseif ($updateLastOperationTimestamp) { + $this->tLastOperationTimestamp = time(); + } + } - // First check to see if a `user` key exists on the session. - if (null == $this->currentUser) { - $authenticationResult->isAuthenticated = false; - LoggerUtils::getAuthLogger()->debug("No active user session."); - return $authenticationResult; - } - LoggerUtils::getAuthLogger()->debug("Processing session for user: " . $this->currentUser->getName()); - - // Next, make sure the user in the sesion still exists in the database. - try { - $this->currentUser->reload(); - } catch (\Exception $exc) { - LoggerUtils::getAuthLogger()->debug("User with active session no longer exists in the database. Expiring session"); - AuthenticationManager::EndSession(); - $authenticationResult->isAuthenticated = false; - return $authenticationResult; - } - - // Next, check for login timeout. If login has expired, redirect to login page - if (SystemConfig::getValue('iSessionTimeout') > 0) { - if ((time() - $this->tLastOperationTimestamp) > SystemConfig::getValue('iSessionTimeout')) { - LoggerUtils::getAuthLogger()->debug("User session timed out"); - $authenticationResult->isAuthenticated = false; - return $authenticationResult; - } else if( $updateLastOperationTimestamp ) { - $this->tLastOperationTimestamp = time(); + // Next, if this user needs to change password, send to that page + // but don't redirect them if they're already on the password change page + $IsUserOnPasswordChangePageNow = $_SERVER['REQUEST_URI'] == $this->GetPasswordChangeURL(); + if ($this->currentUser->getNeedPasswordChange() && !$IsUserOnPasswordChangePageNow) { + LoggerUtils::getAuthLogger()->info('User needs password change; redirecting to password change'); + $authenticationResult->isAuthenticated = false; + $authenticationResult->nextStepURL = $this->GetPasswordChangeURL(); } - } - - // Next, if this user needs to change password, send to that page - // but don't redirect them if they're already on the password change page - $IsUserOnPasswordChangePageNow = $_SERVER["REQUEST_URI"] == $this->GetPasswordChangeURL(); - if ($this->currentUser->getNeedPasswordChange() && ! $IsUserOnPasswordChangePageNow ) { - LoggerUtils::getAuthLogger()->info("User needs password change; redirecting to password change"); - $authenticationResult->isAuthenticated = false; - $authenticationResult->nextStepURL = $this->GetPasswordChangeURL(); - } - - - // Finally, if the above tests pass, this user "is authenticated" - $authenticationResult->isAuthenticated = true; - LoggerUtils::getAuthLogger()->debug("Session validated for user: " . $this->currentUser->getName()); - return $authenticationResult; + + // Finally, if the above tests pass, this user "is authenticated" + $authenticationResult->isAuthenticated = true; + LoggerUtils::getAuthLogger()->debug('Session validated for user: '.$this->currentUser->getName()); + + return $authenticationResult; } - } } diff --git a/src/ChurchCRM/Authentication/AuthenticationResult.php b/src/ChurchCRM/Authentication/AuthenticationResult.php index e89b4d0995..4f0818702e 100644 --- a/src/ChurchCRM/Authentication/AuthenticationResult.php +++ b/src/ChurchCRM/Authentication/AuthenticationResult.php @@ -1,12 +1,11 @@ AffectedPassword = $OldOrNew; - } - public $AffectedPassword; +namespace ChurchCRM\Authentication\Exceptions; + +class PasswordChangeException extends \Exception +{ + public function __construct($OldOrNew, $PasswordChangeProblem) + { + parent::__construct($PasswordChangeProblem); + $this->AffectedPassword = $OldOrNew; } -} \ No newline at end of file + public $AffectedPassword; +} diff --git a/src/ChurchCRM/Authentication/Requests/APITokenAuthenticationRequest.php b/src/ChurchCRM/Authentication/Requests/APITokenAuthenticationRequest.php index 5d38570708..dedef7bbfe 100644 --- a/src/ChurchCRM/Authentication/Requests/APITokenAuthenticationRequest.php +++ b/src/ChurchCRM/Authentication/Requests/APITokenAuthenticationRequest.php @@ -1,12 +1,12 @@ APIToken = $APIToken; - } - public $APIToken; +class APITokenAuthenticationRequest extends AuthenticationRequest +{ + public function __construct($APIToken) + { + $this->APIToken = $APIToken; } - + public $APIToken; } diff --git a/src/ChurchCRM/Authentication/Requests/AuthenticationRequest.php b/src/ChurchCRM/Authentication/Requests/AuthenticationRequest.php index 47c48f8d13..f79c77afee 100644 --- a/src/ChurchCRM/Authentication/Requests/AuthenticationRequest.php +++ b/src/ChurchCRM/Authentication/Requests/AuthenticationRequest.php @@ -1,11 +1,10 @@ TwoFACode = $TwoFACode; - } - - } +class LocalTwoFactorTokenRequest extends AuthenticationRequest +{ + public $TwoFACode; + public function __construct($TwoFACode) + { + $this->TwoFACode = $TwoFACode; + } } diff --git a/src/ChurchCRM/Authentication/Requests/LocalUsernamePasswordRequest.php b/src/ChurchCRM/Authentication/Requests/LocalUsernamePasswordRequest.php index 44cd51db04..223e0c9d36 100644 --- a/src/ChurchCRM/Authentication/Requests/LocalUsernamePasswordRequest.php +++ b/src/ChurchCRM/Authentication/Requests/LocalUsernamePasswordRequest.php @@ -1,16 +1,15 @@ username = $username; - $this->password = $password; - } - - } +class LocalUsernamePasswordRequest extends AuthenticationRequest +{ + public $username; + public $password; + public function __construct($username, $password) + { + $this->username = $username; + $this->password = $password; + } } diff --git a/src/ChurchCRM/BackupManager.php b/src/ChurchCRM/BackupManager.php index a9cb88c4bc..2be7f928a4 100644 --- a/src/ChurchCRM/BackupManager.php +++ b/src/ChurchCRM/BackupManager.php @@ -1,480 +1,477 @@ debug('Removing temp folder tree at '.$TempFolder); + FileSystemUtils::recursiveRemoveDirectory($TempFolder, false); + LoggerUtils::getAppLogger()->debug('Creating temp folder at '.$TempFolder); + mkdir($TempFolder, 0750, true); + LoggerUtils::getAppLogger()->debug('Temp folder created'); + + return $TempFolder; } +} + +class BackupJob extends JobBase +{ + /** + * @var string + */ + private $BackupFileBaseName; + /** + * @var SplFileInfo + */ + private $BackupFile; + /** + * @var bool + */ + private $IncludeExtraneousFiles; + /** + * @var string + */ + public $BackupDownloadFileName; + /** + * @var bool + */ + public $shouldEncrypt; + + /** + * @var string + */ + public $BackupPassword; - class JobBase + /** + * @param string $BaseName + * @param BackupType $BackupType + * @param bool $IncludeExtraneousFiles + */ + public function __construct($BaseName, $BackupType, $IncludeExtraneousFiles, $EncryptBackup, $BackupPassword) { - /** - * - * @var BackupType - */ - protected $BackupType; - - /** - * - * @var String - */ - protected $TempFolder; - - protected function CreateEmptyTempFolder() - { - // both backup and restore operations require a clean temporary working folder. Create it. - $TempFolder = SystemURLs::getDocumentRoot() . "/tmp_attach/ChurchCRMBackups"; - LoggerUtils::getAppLogger()->debug("Removing temp folder tree at ". $TempFolder); - FileSystemUtils::recursiveRemoveDirectory($TempFolder, false); - LoggerUtils::getAppLogger()->debug("Creating temp folder at ". $TempFolder); - mkdir($TempFolder, 0750, true); - LoggerUtils::getAppLogger()->debug("Temp folder created"); - return $TempFolder; - } + $this->BackupType = $BackupType; + $this->TempFolder = $this->CreateEmptyTempFolder(); + $this->BackupFileBaseName = $this->TempFolder.'/'.$BaseName; + $this->IncludeExtraneousFiles = $IncludeExtraneousFiles; + $this->shouldEncrypt = $EncryptBackup; + $this->BackupPassword = $BackupPassword; + LoggerUtils::getAppLogger()->debug( + "Backup job created; ready to execute: Type: '". + $this->BackupType. + "' Temp Folder: '". + $this->TempFolder. + "' BaseName: '".$this->BackupFileBaseName. + "' Include extra files: '".($this->IncludeExtraneousFiles ? 'true' : 'false')."'" + ); } - class BackupJob extends JobBase + public function CopyToWebDAV($Endpoint, $Username, $Password) { - /** - * - * @var String - */ - private $BackupFileBaseName; - /** - * - * @var SplFileInfo - */ - private $BackupFile; - /** - * - * @var Boolean - */ - private $IncludeExtraneousFiles; - /** - * - * @var String - */ - public $BackupDownloadFileName; - /** - * - * @var Boolean - */ - public $shouldEncrypt; - - /** - * - * @var String - */ - public $BackupPassword; - - - /** - * - * @param String $BaseName - * @param BackupType $BackupType - * @param Boolean $IncludeExtraneousFiles - */ - public function __construct($BaseName, $BackupType, $IncludeExtraneousFiles, $EncryptBackup, $BackupPassword) - { - $this->BackupType = $BackupType; - $this->TempFolder = $this->CreateEmptyTempFolder(); - $this->BackupFileBaseName = $this->TempFolder .'/'.$BaseName; - $this->IncludeExtraneousFiles = $IncludeExtraneousFiles; - $this->shouldEncrypt = $EncryptBackup; - $this->BackupPassword = $BackupPassword; - LoggerUtils::getAppLogger()->debug( - "Backup job created; ready to execute: Type: '" . - $this->BackupType . - "' Temp Folder: '" . - $this->TempFolder . - "' BaseName: '" . $this->BackupFileBaseName. - "' Include extra files: '". ($this->IncludeExtraneousFiles ? 'true':'false') ."'" - ); - } - - public function CopyToWebDAV($Endpoint, $Username, $Password) - { - LoggerUtils::getAppLogger()->info("Beginning to copy backup to: " . $Endpoint); - try { - $fh = fopen($this->BackupFile->getPathname(), 'r'); - $remoteUrl = $Endpoint.urlencode($this->BackupFile->getFilename()); - LoggerUtils::getAppLogger()->debug("Full remote URL: " .$remoteUrl); - $credentials = $Username.":".$Password; - $ch = curl_init($remoteUrl); - curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); - curl_setopt($ch, CURLOPT_USERPWD, $credentials); - curl_setopt($ch, CURLOPT_PUT, true); - curl_setopt($ch, CURLOPT_FAILONERROR, true); - curl_setopt($ch, CURLOPT_INFILE, $fh); - curl_setopt($ch, CURLOPT_INFILESIZE, $this->BackupFile->getSize()); - LoggerUtils::getAppLogger()->debug("Beginning to send file"); - $time = new \ChurchCRM\Utils\ExecutionTime(); - $result = curl_exec($ch); - if (curl_error($ch)) { - $error_msg = curl_error($ch); - } - curl_close($ch); - fclose($fh); + LoggerUtils::getAppLogger()->info('Beginning to copy backup to: '.$Endpoint); - if (isset($error_msg)) { - throw new \Exception("Error backing up to remote: ". $error_msg); - } - LoggerUtils::getAppLogger()->debug("File send complete. Took: " . $time->getMilliseconds() . "ms"); - } catch (\Exception $e) { - LoggerUtils::getAppLogger()->error("Error copying backup: " . $e); + try { + $fh = fopen($this->BackupFile->getPathname(), 'r'); + $remoteUrl = $Endpoint.urlencode($this->BackupFile->getFilename()); + LoggerUtils::getAppLogger()->debug('Full remote URL: '.$remoteUrl); + $credentials = $Username.':'.$Password; + $ch = curl_init($remoteUrl); + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + curl_setopt($ch, CURLOPT_USERPWD, $credentials); + curl_setopt($ch, CURLOPT_PUT, true); + curl_setopt($ch, CURLOPT_FAILONERROR, true); + curl_setopt($ch, CURLOPT_INFILE, $fh); + curl_setopt($ch, CURLOPT_INFILESIZE, $this->BackupFile->getSize()); + LoggerUtils::getAppLogger()->debug('Beginning to send file'); + $time = new \ChurchCRM\Utils\ExecutionTime(); + $result = curl_exec($ch); + if (curl_error($ch)) { + $error_msg = curl_error($ch); } - LoggerUtils::getAppLogger()->info("Backup copy completed. Curl result: " . $result); - return $result; - } + curl_close($ch); + fclose($fh); - private function CaptureSQLFile(\SplFileInfo $SqlFilePath) - { - global $sSERVERNAME, $sDATABASE, $sUSER, $sPASSWORD; - LoggerUtils::getAppLogger()->debug("Beginning to backup database to: " . $SqlFilePath->getPathname()); - try { - $dump = new Mysqldump(Bootstrapper::GetDSN(), $sUSER, $sPASSWORD, ['add-drop-table' => true]); - $dump->start($SqlFilePath->getPathname()); - LoggerUtils::getAppLogger()->debug("Finished backing up database to " . $SqlFilePath->getPathname()); - } catch (\Exception $e) { - $message = "Failed to backup database to: " . $SqlFilePath->getPathname(). " Exception: " . $e; - LoggerUtils::getAppLogger()->error($message); - throw new Exception($message, 500); + if (isset($error_msg)) { + throw new \Exception('Error backing up to remote: '.$error_msg); } + LoggerUtils::getAppLogger()->debug('File send complete. Took: '.$time->getMilliseconds().'ms'); + } catch (\Exception $e) { + LoggerUtils::getAppLogger()->error('Error copying backup: '.$e); } + LoggerUtils::getAppLogger()->info('Backup copy completed. Curl result: '.$result); - private function ShouldBackupImageFile(SplFileInfo $ImageFile) - { - $isExtraneousFile = strpos($ImageFile->getFileName(), "-initials") != false || - strpos($ImageFile->getFileName(), "-remote") != false || - strpos($ImageFile->getPathName(), "thumbnails") != false; + return $result; + } - return $ImageFile->isFile() && !(!$this->IncludeExtraneousFiles && $isExtraneousFile); //todo: figure out this logic + private function CaptureSQLFile(\SplFileInfo $SqlFilePath) + { + global $sSERVERNAME, $sDATABASE, $sUSER, $sPASSWORD; + LoggerUtils::getAppLogger()->debug('Beginning to backup database to: '.$SqlFilePath->getPathname()); + + try { + $dump = new Mysqldump(Bootstrapper::GetDSN(), $sUSER, $sPASSWORD, ['add-drop-table' => true]); + $dump->start($SqlFilePath->getPathname()); + LoggerUtils::getAppLogger()->debug('Finished backing up database to '.$SqlFilePath->getPathname()); + } catch (\Exception $e) { + $message = 'Failed to backup database to: '.$SqlFilePath->getPathname().' Exception: '.$e; + LoggerUtils::getAppLogger()->error($message); + + throw new Exception($message, 500); } + } - private function CreateFullArchive() - { - $imagesAddedToArchive = array(); - $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.".tar"); - $phar = new PharData($this->BackupFile->getPathname()); - LoggerUtils::getAppLogger()->debug("Archive opened at: ".$this->BackupFile->getPathname()); - $phar->startBuffering(); - - $SqlFile = new \SplFileInfo($this->TempFolder."/".'ChurchCRM-Database.sql'); - $this->CaptureSQLFile($SqlFile); - $phar->addFile($SqlFile, 'ChurchCRM-Database.sql'); - LoggerUtils::getAppLogger()->debug("Database added to archive"); - $imageFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(SystemURLs::getImagesRoot())); - foreach ($imageFiles as $imageFile) { - if ($this->ShouldBackupImageFile($imageFile)) { - $localName = substr(str_replace(SystemURLs::getDocumentRoot(), '', $imageFile->getRealPath()), 1); - $phar->addFile($imageFile->getRealPath(), $localName); - array_push($imagesAddedToArchive, $imageFile->getRealPath()); - } + private function ShouldBackupImageFile(SplFileInfo $ImageFile) + { + $isExtraneousFile = strpos($ImageFile->getFileName(), '-initials') != false || + strpos($ImageFile->getFileName(), '-remote') != false || + strpos($ImageFile->getPathName(), 'thumbnails') != false; + + return $ImageFile->isFile() && !(!$this->IncludeExtraneousFiles && $isExtraneousFile); //todo: figure out this logic + } + + private function CreateFullArchive() + { + $imagesAddedToArchive = []; + $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.'.tar'); + $phar = new PharData($this->BackupFile->getPathname()); + LoggerUtils::getAppLogger()->debug('Archive opened at: '.$this->BackupFile->getPathname()); + $phar->startBuffering(); + + $SqlFile = new \SplFileInfo($this->TempFolder.'/'.'ChurchCRM-Database.sql'); + $this->CaptureSQLFile($SqlFile); + $phar->addFile($SqlFile, 'ChurchCRM-Database.sql'); + LoggerUtils::getAppLogger()->debug('Database added to archive'); + $imageFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(SystemURLs::getImagesRoot())); + foreach ($imageFiles as $imageFile) { + if ($this->ShouldBackupImageFile($imageFile)) { + $localName = substr(str_replace(SystemURLs::getDocumentRoot(), '', $imageFile->getRealPath()), 1); + $phar->addFile($imageFile->getRealPath(), $localName); + array_push($imagesAddedToArchive, $imageFile->getRealPath()); } - LoggerUtils::getAppLogger()->debug("Images files added to archive: ". join(";", $imagesAddedToArchive)); - $phar->stopBuffering(); - LoggerUtils::getAppLogger()->debug("Finished creating archive. Beginning to compress"); - $phar->compress(\Phar::GZ); - LoggerUtils::getAppLogger()->debug("Archive compressed; should now be a .gz file"); - unset($phar); - unlink($this->BackupFile->getPathname()); - LoggerUtils::getAppLogger()->debug("Initial .tar archive deleted: " . $this->BackupFile->getPathname()); - $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.".tar.gz"); - LoggerUtils::getAppLogger()->debug("New backup file: " . $this->BackupFile); - unlink($SqlFile); - LoggerUtils::getAppLogger()->debug("Temp Database backup deleted: " . $SqlFile); } + LoggerUtils::getAppLogger()->debug('Images files added to archive: '.join(';', $imagesAddedToArchive)); + $phar->stopBuffering(); + LoggerUtils::getAppLogger()->debug('Finished creating archive. Beginning to compress'); + $phar->compress(\Phar::GZ); + LoggerUtils::getAppLogger()->debug('Archive compressed; should now be a .gz file'); + unset($phar); + unlink($this->BackupFile->getPathname()); + LoggerUtils::getAppLogger()->debug('Initial .tar archive deleted: '.$this->BackupFile->getPathname()); + $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.'.tar.gz'); + LoggerUtils::getAppLogger()->debug('New backup file: '.$this->BackupFile); + unlink($SqlFile); + LoggerUtils::getAppLogger()->debug('Temp Database backup deleted: '.$SqlFile); + } - private function CreateGZSql() - { - $SqlFile = new \SplFileInfo($this->TempFolder."/".'ChurchCRM-Database.sql'); - $this->CaptureSQLFile($SqlFile); - $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.'.sql.gz'); - $gzf = gzopen($this->BackupFile->getPathname(), 'w6'); - gzwrite($gzf, file_get_contents($SqlFile->getPathname())); - gzclose($gzf); - unlink($SqlFile->getPathname()); - } + private function CreateGZSql() + { + $SqlFile = new \SplFileInfo($this->TempFolder.'/'.'ChurchCRM-Database.sql'); + $this->CaptureSQLFile($SqlFile); + $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.'.sql.gz'); + $gzf = gzopen($this->BackupFile->getPathname(), 'w6'); + gzwrite($gzf, file_get_contents($SqlFile->getPathname())); + gzclose($gzf); + unlink($SqlFile->getPathname()); + } + + private function EncryptBackupFile() + { + LoggerUtils::getAppLogger()->info('Encrypting backup file: '.$this->BackupFile); + $tempfile = new \SplFileInfo($this->BackupFile->getPathname().'temp'); + rename($this->BackupFile, $tempfile); + File::encryptFileWithPassword($tempfile, $this->BackupFile, $this->BackupPassword); + LoggerUtils::getAppLogger()->info('Finished ecrypting backup file'); + } - private function EncryptBackupFile() - { - LoggerUtils::getAppLogger()->info("Encrypting backup file: ".$this->BackupFile); - $tempfile = new \SplFileInfo($this->BackupFile->getPathname()."temp"); - rename($this->BackupFile, $tempfile); - File::encryptFileWithPassword($tempfile, $this->BackupFile, $this->BackupPassword); - LoggerUtils::getAppLogger()->info("Finished ecrypting backup file"); + public function Execute() + { + $time = new \ChurchCRM\Utils\ExecutionTime(); + LoggerUtils::getAppLogger()->info('Beginning backup job. Type: '.$this->BackupType.'. BaseName: '.$this->BackupFileBaseName); + if ($this->BackupType == BackupType::FullBackup) { + $this->CreateFullArchive(); + } elseif ($this->BackupType == BackupType::SQL) { + $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.'.sql'); + $this->CaptureSQLFile($this->BackupFile); + } elseif ($this->BackupType == BackupType::GZSQL) { + $this->CreateGZSql(); } - public function Execute() - { - $time = new \ChurchCRM\Utils\ExecutionTime(); - LoggerUtils::getAppLogger()->info("Beginning backup job. Type: " . $this->BackupType . ". BaseName: " . $this->BackupFileBaseName); - if ($this->BackupType == BackupType::FullBackup) { - $this->CreateFullArchive(); - } elseif ($this->BackupType == BackupType::SQL) { - $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.".sql"); - $this->CaptureSQLFile($this->BackupFile); - } elseif ($this->BackupType == BackupType::GZSQL) { - $this->CreateGZSql(); - } - if ($this->shouldEncrypt) { - $this->EncryptBackupFile(); - } - $time->End(); - $percentExecutionTime = (($time->getMilliseconds()/1000)/ini_get('max_execution_time'))*100; - LoggerUtils::getAppLogger()->info("Completed backup job. Took : " . $time->getMilliseconds()."ms. ".$percentExecutionTime."% of max_execution_time"); - if ($percentExecutionTime > 80) { - // if the backup took more than 80% of the max_execution_time, then write a warning to the log - LoggerUtils::getAppLogger()->warning("Backup task took more than 80% of max_execution_time (".ini_get('max_execution_time')."). Consider increasing this time to avoid a failure"); - } - $this->BackupDownloadFileName = $this->BackupFile->getFilename(); - return true; + if ($this->shouldEncrypt) { + $this->EncryptBackupFile(); + } + $time->End(); + $percentExecutionTime = (($time->getMilliseconds() / 1000) / ini_get('max_execution_time')) * 100; + LoggerUtils::getAppLogger()->info('Completed backup job. Took : '.$time->getMilliseconds().'ms. '.$percentExecutionTime.'% of max_execution_time'); + if ($percentExecutionTime > 80) { + // if the backup took more than 80% of the max_execution_time, then write a warning to the log + LoggerUtils::getAppLogger()->warning('Backup task took more than 80% of max_execution_time ('.ini_get('max_execution_time').'). Consider increasing this time to avoid a failure'); } + $this->BackupDownloadFileName = $this->BackupFile->getFilename(); + + return true; } +} + +class RestoreJob extends JobBase +{ + /** + * @var SplFileInfo + */ + private $RestoreFile; - class RestoreJob extends JobBase + /** + * @var array + */ + public $Messages; + /** + * @var bool + */ + private $IsBackupEncrypted; + /** + * @var string + */ + private $restorePassword; + + private function IsIncomingFileFailed() { - /** - * - * @var SplFileInfo - */ - private $RestoreFile; - - /** - * - * @var Array - */ - public $Messages; - /** - * - * @var Boolean - */ - private $IsBackupEncrypted; - /** - * - * @var String - */ - private $restorePassword; - - private function IsIncomingFileFailed() - { - // Not actually sure what this is supposed to do, but it was working before?? - return $_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0; + // Not actually sure what this is supposed to do, but it was working before?? + return $_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0; + } + + public function __construct() + { + LoggerUtils::getAppLogger()->info('Beginning to process incoming archive for restoration'); + $this->Messages = []; + if ($this->IsIncomingFileFailed()) { + $message = 'The selected file exceeds this servers maximum upload size of: '.SystemService::getMaxUploadFileSize(); + LoggerUtils::getAppLogger()->error($message); + + throw new \Exception($message, 500); } + $rawUploadedFile = $_FILES['restoreFile']; + $this->TempFolder = $this->CreateEmptyTempFolder(); + $this->RestoreFile = new \SplFileInfo($this->TempFolder.'/'.$rawUploadedFile['name']); + LoggerUtils::getAppLogger()->debug('Moving '.$rawUploadedFile['tmp_name'].' to '.$this->RestoreFile); + move_uploaded_file($rawUploadedFile['tmp_name'], $this->RestoreFile); + LoggerUtils::getAppLogger()->debug('File move complete'); + $this->DiscoverBackupType(); + LoggerUtils::getAppLogger()->debug('Detected backup type: '.$this->BackupType); + LoggerUtils::getAppLogger()->info('Restore job created; ready to execute'); + } + + private function DecryptBackup() + { + LoggerUtils::getAppLogger()->info('Decrypting file: '.$this->RestoreFile); + $this->restorePassword = InputUtils::FilterString($_POST['restorePassword']); + $tempfile = new \SplFileInfo($this->RestoreFile->getPathname().'temp'); + + try { + File::decryptFileWithPassword($this->RestoreFile, $tempfile, $this->restorePassword); + rename($tempfile, $this->RestoreFile); + LoggerUtils::getAppLogger()->info('File decrypted'); + } catch (\Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException $ex) { + if ($ex->getMessage() == 'Bad version header.') { + LoggerUtils::getAppLogger()->info("Bad version header; this file probably wasn't encrypted"); + } else { + LoggerUtils::getAppLogger()->error($ex->getMessage()); - public function __construct() - { - LoggerUtils::getAppLogger()->info("Beginning to process incoming archive for restoration"); - $this->Messages = array(); - if ($this->IsIncomingFileFailed()) { - $message = "The selected file exceeds this servers maximum upload size of: " . SystemService::getMaxUploadFileSize(); - LoggerUtils::getAppLogger()->error($message); - throw new \Exception($message, 500); + throw $ex; } - $rawUploadedFile = $_FILES['restoreFile']; - $this->TempFolder = $this->CreateEmptyTempFolder(); - $this->RestoreFile = new \SplFileInfo($this->TempFolder."/" . $rawUploadedFile['name']); - LoggerUtils::getAppLogger()->debug("Moving ".$rawUploadedFile['tmp_name']. " to ". $this->RestoreFile); - move_uploaded_file($rawUploadedFile['tmp_name'], $this->RestoreFile); - LoggerUtils::getAppLogger()->debug("File move complete"); - $this->DiscoverBackupType(); - LoggerUtils::getAppLogger()->debug("Detected backup type: " . $this->BackupType); - LoggerUtils::getAppLogger()->info("Restore job created; ready to execute"); } + } - private function DecryptBackup() - { - LoggerUtils::getAppLogger()->info("Decrypting file: " . $this->RestoreFile); - $this->restorePassword = InputUtils::FilterString($_POST['restorePassword']); - $tempfile = new \SplFileInfo($this->RestoreFile->getPathname()."temp"); - - try { - File::decryptFileWithPassword($this->RestoreFile, $tempfile, $this->restorePassword); - rename($tempfile, $this->RestoreFile); - LoggerUtils::getAppLogger()->info("File decrypted"); - } catch (\Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException $ex) { - if ($ex->getMessage() == 'Bad version header.') { - LoggerUtils::getAppLogger()->info("Bad version header; this file probably wasn't encrypted"); - } else { - LoggerUtils::getAppLogger()->error($ex->getMessage()); - throw $ex; + private function DiscoverBackupType() + { + switch ($this->RestoreFile->getExtension()) { + case 'gz': + $basename = $this->RestoreFile->getBasename(); + if (substr($basename, strlen($basename) - 6, 6) == 'tar.gz') { + $this->BackupType = BackupType::FullBackup; + } elseif (substr($basename, strlen($basename) - 6, 6) == 'sql.gz') { + $this->BackupType = BackupType::GZSQL; } - } - } - private function DiscoverBackupType() - { - switch ($this->RestoreFile->getExtension()) { - case "gz": - $basename = $this->RestoreFile->getBasename(); - if (substr($basename, strlen($basename)-6, 6) == "tar.gz") { - $this->BackupType = BackupType::FullBackup; - } elseif (substr($basename, strlen($basename)-6, 6) == "sql.gz") { - $this->BackupType = BackupType::GZSQL; - } - break; - case "sql": - $this->BackupType = BackupType::SQL; - break; - } + break; + case 'sql': + $this->BackupType = BackupType::SQL; + break; } + } - private function RestoreSQLBackup($SQLFileInfo) - { - $connection = Propel::getConnection(); - LoggerUtils::getAppLogger()->debug("Restoring SQL file from: ".$SQLFileInfo); - SQLUtils::sqlImport($SQLFileInfo, $connection); - LoggerUtils::getAppLogger()->debug("Finished restoring SQL table"); - } + private function RestoreSQLBackup($SQLFileInfo) + { + $connection = Propel::getConnection(); + LoggerUtils::getAppLogger()->debug('Restoring SQL file from: '.$SQLFileInfo); + SQLUtils::sqlImport($SQLFileInfo, $connection); + LoggerUtils::getAppLogger()->debug('Finished restoring SQL table'); + } - private function RestoreFullBackup() - { - LoggerUtils::getAppLogger()->debug("Restoring full archive"); - $phar = new PharData($this->RestoreFile); - LoggerUtils::getAppLogger()->debug("Extracting " . $this->RestoreFile . " to ". $this->TempFolder); - $phar->extractTo($this->TempFolder); - LoggerUtils::getAppLogger()->debug("Finished exctraction"); - $sqlFile = $this->TempFolder."/ChurchCRM-Database.sql"; - if (file_exists($sqlFile)) { - $this->RestoreSQLBackup($sqlFile); - LoggerUtils::getAppLogger()->debug("Removing images from live instance"); - FileSystemUtils::recursiveRemoveDirectory(SystemURLs::getDocumentRoot() . '/Images'); - LoggerUtils::getAppLogger()->debug("Removal complete; Copying restored images to live instance"); - FileSystemUtils::recursiveCopyDirectory($this->TempFolder. '/Images/', SystemURLs::getImagesRoot()); - LoggerUtils::getAppLogger()->debug("Finished copying images"); - } else { - FileSystemUtils::recursiveRemoveDirectory($restoreResult->backupDir, true); - throw new Exception(gettext("Backup archive does not contain a database").": " .$this->RestoreFile); - } - LoggerUtils::getAppLogger()->debug("Finished restoring full archive"); - } + private function RestoreFullBackup() + { + LoggerUtils::getAppLogger()->debug('Restoring full archive'); + $phar = new PharData($this->RestoreFile); + LoggerUtils::getAppLogger()->debug('Extracting '.$this->RestoreFile.' to '.$this->TempFolder); + $phar->extractTo($this->TempFolder); + LoggerUtils::getAppLogger()->debug('Finished exctraction'); + $sqlFile = $this->TempFolder.'/ChurchCRM-Database.sql'; + if (file_exists($sqlFile)) { + $this->RestoreSQLBackup($sqlFile); + LoggerUtils::getAppLogger()->debug('Removing images from live instance'); + FileSystemUtils::recursiveRemoveDirectory(SystemURLs::getDocumentRoot().'/Images'); + LoggerUtils::getAppLogger()->debug('Removal complete; Copying restored images to live instance'); + FileSystemUtils::recursiveCopyDirectory($this->TempFolder.'/Images/', SystemURLs::getImagesRoot()); + LoggerUtils::getAppLogger()->debug('Finished copying images'); + } else { + FileSystemUtils::recursiveRemoveDirectory($restoreResult->backupDir, true); - private function RestoreGZSQL() - { - LoggerUtils::getAppLogger()->debug("Decompressing gzipped SQL file: ". $this->RestoreFile); - $gzf = gzopen($this->RestoreFile, 'r'); - $buffer_size = 4096; - $SqlFile = new \SplFileInfo($this->TempFolder."/".'ChurchCRM-Database.sql'); - $out_file = fopen($SqlFile, 'wb'); - while (!gzeof($gzf)) { - fwrite($out_file, gzread($gzf, $buffer_size)); - } - fclose($out_file); - gzclose($gzf); - $this->RestoreSQLBackup($SqlFile); - unlink($this->RestoreFile); - unlink($SqlFile->getPathname()); + throw new Exception(gettext('Backup archive does not contain a database').': '.$this->RestoreFile); } + LoggerUtils::getAppLogger()->debug('Finished restoring full archive'); + } - private function PostRestoreCleanup() - { - //When restoring a database, do NOT let the database continue to create remote backups. - //This can be very troublesome for users in a testing environment. - LoggerUtils::getAppLogger()->debug("Starting post-restore cleanup"); - SystemConfig::setValue('bEnableExternalBackupTarget', '0'); - array_push($this->Messages, gettext('As part of the restore, external backups have been disabled. If you wish to continue automatic backups, you must manuall re-enable the bEnableExternalBackupTarget setting.')); - SystemConfig::setValue('sLastIntegrityCheckTimeStamp', null); - LoggerUtils::getAppLogger()->debug("Reset System Settings for: bEnableExternalBackupTarget and sLastIntegrityCheckTimeStamp"); + private function RestoreGZSQL() + { + LoggerUtils::getAppLogger()->debug('Decompressing gzipped SQL file: '.$this->RestoreFile); + $gzf = gzopen($this->RestoreFile, 'r'); + $buffer_size = 4096; + $SqlFile = new \SplFileInfo($this->TempFolder.'/'.'ChurchCRM-Database.sql'); + $out_file = fopen($SqlFile, 'wb'); + while (!gzeof($gzf)) { + fwrite($out_file, gzread($gzf, $buffer_size)); } + fclose($out_file); + gzclose($gzf); + $this->RestoreSQLBackup($SqlFile); + unlink($this->RestoreFile); + unlink($SqlFile->getPathname()); + } - public function Execute() - { - LoggerUtils::getAppLogger()->info("Executing restore job"); - try { - $this->DecryptBackup(); - switch ($this->BackupType) { - case BackupType::SQL: - $this->RestoreSQLBackup($this->RestoreFile); - break; - case BackupType::GZSQL: - $this->RestoreGZSQL(); - break; - case BackupType::FullBackup: - $this->RestoreFullBackup(); - break; - } - $this->PostRestoreCleanup(); - LoggerUtils::getAppLogger()->info("Finished executing restore job. Cleaning out temp folder."); - } catch (Exception $ex) { - LoggerUtils::getAppLogger()->error("Error restoring backup: " . $ex); + private function PostRestoreCleanup() + { + //When restoring a database, do NOT let the database continue to create remote backups. + //This can be very troublesome for users in a testing environment. + LoggerUtils::getAppLogger()->debug('Starting post-restore cleanup'); + SystemConfig::setValue('bEnableExternalBackupTarget', '0'); + array_push($this->Messages, gettext('As part of the restore, external backups have been disabled. If you wish to continue automatic backups, you must manuall re-enable the bEnableExternalBackupTarget setting.')); + SystemConfig::setValue('sLastIntegrityCheckTimeStamp', null); + LoggerUtils::getAppLogger()->debug('Reset System Settings for: bEnableExternalBackupTarget and sLastIntegrityCheckTimeStamp'); + } + + public function Execute() + { + LoggerUtils::getAppLogger()->info('Executing restore job'); + + try { + $this->DecryptBackup(); + switch ($this->BackupType) { + case BackupType::SQL: + $this->RestoreSQLBackup($this->RestoreFile); + break; + case BackupType::GZSQL: + $this->RestoreGZSQL(); + break; + case BackupType::FullBackup: + $this->RestoreFullBackup(); + break; } - $this->TempFolder = $this->CreateEmptyTempFolder(); + $this->PostRestoreCleanup(); + LoggerUtils::getAppLogger()->info('Finished executing restore job. Cleaning out temp folder.'); + } catch (Exception $ex) { + LoggerUtils::getAppLogger()->error('Error restoring backup: '.$ex); } + $this->TempFolder = $this->CreateEmptyTempFolder(); } +} - - class BackupDownloader +class BackupDownloader +{ + public static function DownloadBackup($filename) { - public static function DownloadBackup($filename) - { - $path = SystemURLs::getDocumentRoot() . "/tmp_attach/ChurchCRMBackups/$filename"; - LoggerUtils::getAppLogger()->info("Download requested for :" . $path); - if (file_exists($path)) { - if ($fd = fopen($path, 'r')) { - $fsize = filesize($path); - $path_parts = pathinfo($path); - $ext = strtolower($path_parts['extension']); - switch ($ext) { - case 'gz': - header('Content-type: application/x-gzip'); - header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); - break; - case 'tar.gz': - header('Content-type: application/x-gzip'); - header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); - break; - case 'sql': - header('Content-type: text/plain'); - header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); - break; - case 'gpg': - header('Content-type: application/pgp-encrypted'); - header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); - break; - case 'zip': - header('Content-type: application/zip'); - header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); - break; - // add more headers for other content types here - default: - header('Content-type: application/octet-stream'); - header('Content-Disposition: filename="' . $path_parts['basename'] . '"'); - break; - } - header("Content-length: $fsize"); - header('Cache-control: private'); //use this to open files directly - LoggerUtils::getAppLogger()->debug("Headers sent. sending backup file contents"); - while (!feof($fd)) { - $buffer = fread($fd, 2048); - echo $buffer; - } - LoggerUtils::getAppLogger()->debug("Backup file contents sent"); + $path = SystemURLs::getDocumentRoot()."/tmp_attach/ChurchCRMBackups/$filename"; + LoggerUtils::getAppLogger()->info('Download requested for :'.$path); + if (file_exists($path)) { + if ($fd = fopen($path, 'r')) { + $fsize = filesize($path); + $path_parts = pathinfo($path); + $ext = strtolower($path_parts['extension']); + switch ($ext) { + case 'gz': + header('Content-type: application/x-gzip'); + header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"'); + break; + case 'tar.gz': + header('Content-type: application/x-gzip'); + header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"'); + break; + case 'sql': + header('Content-type: text/plain'); + header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"'); + break; + case 'gpg': + header('Content-type: application/pgp-encrypted'); + header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"'); + break; + case 'zip': + header('Content-type: application/zip'); + header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"'); + break; + // add more headers for other content types here + default: + header('Content-type: application/octet-stream'); + header('Content-Disposition: filename="'.$path_parts['basename'].'"'); + break; } - fclose($fd); - FileSystemUtils::recursiveRemoveDirectory(SystemURLs::getDocumentRoot() . '/tmp_attach/', true); - LoggerUtils::getAppLogger()->debug("Removed backup file from server filesystem"); - } else { - $message = "Requested download does not exist: " . $path; - LoggerUtils::getAppLogger()->error($message); - throw new \Exception($message, 500); + header("Content-length: $fsize"); + header('Cache-control: private'); //use this to open files directly + LoggerUtils::getAppLogger()->debug('Headers sent. sending backup file contents'); + while (!feof($fd)) { + $buffer = fread($fd, 2048); + echo $buffer; + } + LoggerUtils::getAppLogger()->debug('Backup file contents sent'); } + fclose($fd); + FileSystemUtils::recursiveRemoveDirectory(SystemURLs::getDocumentRoot().'/tmp_attach/', true); + LoggerUtils::getAppLogger()->debug('Removed backup file from server filesystem'); + } else { + $message = 'Requested download does not exist: '.$path; + LoggerUtils::getAppLogger()->error($message); + + throw new \Exception($message, 500); } } } diff --git a/src/ChurchCRM/Config/Menu/Menu.php b/src/ChurchCRM/Config/Menu/Menu.php index b00ff5718a..0d9eec49a0 100644 --- a/src/ChurchCRM/Config/Menu/Menu.php +++ b/src/ChurchCRM/Config/Menu/Menu.php @@ -2,11 +2,11 @@ namespace ChurchCRM\Config\Menu; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\Config; use ChurchCRM\dto\SystemConfig; use ChurchCRM\GroupQuery; use ChurchCRM\ListOptionQuery; -use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\MenuLinkQuery; class Menu @@ -31,50 +31,51 @@ public static function getMenu() private static function buildMenuItems() { - return array( - "Dashboard" => new MenuItem(gettext("Dashboard"), "Menu.php", true, 'fa-tachometer-alt'), - "Calendar" => self::getCalendarMenu(), - "People" => self::getPeopleMenu(), - "Groups" => self::getGroupMenu(), - "SundaySchool" => self::getSundaySchoolMenu(), - "Email" => new MenuItem(gettext("Email"), "v2/email/dashboard", SystemConfig::getBooleanValue("bEnabledEmail"), 'fa-envelope'), - "Events" => self::getEventsMenu(), - "Deposits" => self::getDepositsMenu(), - "Fundraiser" => self::getFundraisersMenu(), - "Reports" => self::getReportsMenu(), - "Admin" => self::getAdminMenu(), - "Custom" => self::getCustomMenu(), - ); + return [ + 'Dashboard' => new MenuItem(gettext('Dashboard'), 'Menu.php', true, 'fa-tachometer-alt'), + 'Calendar' => self::getCalendarMenu(), + 'People' => self::getPeopleMenu(), + 'Groups' => self::getGroupMenu(), + 'SundaySchool' => self::getSundaySchoolMenu(), + 'Email' => new MenuItem(gettext('Email'), 'v2/email/dashboard', SystemConfig::getBooleanValue('bEnabledEmail'), 'fa-envelope'), + 'Events' => self::getEventsMenu(), + 'Deposits' => self::getDepositsMenu(), + 'Fundraiser' => self::getFundraisersMenu(), + 'Reports' => self::getReportsMenu(), + 'Admin' => self::getAdminMenu(), + 'Custom' => self::getCustomMenu(), + ]; } private static function getCalendarMenu() { - $calendarMenu = new MenuItem(gettext("Calendar"), "v2/calendar", SystemConfig::getBooleanValue("bEnabledCalendar"), 'fa-calendar'); - $calendarMenu->addCounter(new MenuCounter("AnniversaryNumber", "bg-blue")); - $calendarMenu->addCounter(new MenuCounter("BirthdateNumber", "bg-red")); - $calendarMenu->addCounter(new MenuCounter("EventsNumber", "bg-yellow")); + $calendarMenu = new MenuItem(gettext('Calendar'), 'v2/calendar', SystemConfig::getBooleanValue('bEnabledCalendar'), 'fa-calendar'); + $calendarMenu->addCounter(new MenuCounter('AnniversaryNumber', 'bg-blue')); + $calendarMenu->addCounter(new MenuCounter('BirthdateNumber', 'bg-red')); + $calendarMenu->addCounter(new MenuCounter('EventsNumber', 'bg-yellow')); + return $calendarMenu; } private static function getPeopleMenu() { - $peopleMenu = new MenuItem(gettext("People"), "", true, 'fa-users'); - $peopleMenu->addSubMenu(new MenuItem(gettext("Dashboard"), "PeopleDashboard.php")); - $peopleMenu->addSubMenu(new MenuItem(gettext("Add New Person"), "PersonEditor.php", AuthenticationManager::GetCurrentUser()->isAddRecordsEnabled())); - $peopleMenu->addSubMenu(new MenuItem(gettext("View Active People"), "v2/people")); - $peopleMenu->addSubMenu(new MenuItem(gettext("View Inactive People"), "v2/people?familyActiveStatus=inactive")); - $peopleMenu->addSubMenu(new MenuItem(gettext("View All People"), "v2/people?familyActiveStatus=all")); - $peopleMenu->addSubMenu(new MenuItem(gettext("Add New Family"), "FamilyEditor.php", AuthenticationManager::GetCurrentUser()->isAddRecordsEnabled())); - $peopleMenu->addSubMenu(new MenuItem(gettext("View Active Families"), "v2/family")); - $peopleMenu->addSubMenu(new MenuItem(gettext("View Inactive Families"), "v2/family?mode=inactive")); - $adminMenu = new MenuItem(gettext("Admin"), "", AuthenticationManager::GetCurrentUser()->isAdmin()); - $adminMenu->addSubMenu(new MenuItem(gettext("Classifications Manager"), "OptionManager.php?mode=classes", AuthenticationManager::GetCurrentUser()->isAdmin())); - $adminMenu->addSubMenu(new MenuItem(gettext("Family Roles"), "OptionManager.php?mode=famroles", AuthenticationManager::GetCurrentUser()->isAdmin())); - $adminMenu->addSubMenu(new MenuItem(gettext("Family Properties"), "PropertyList.php?Type=f", AuthenticationManager::GetCurrentUser()->isAdmin())); - $adminMenu->addSubMenu(new MenuItem(gettext("Family Custom Fields"), "FamilyCustomFieldsEditor.php", AuthenticationManager::GetCurrentUser()->isAdmin())); - $adminMenu->addSubMenu(new MenuItem(gettext("People Properties"), "PropertyList.php?Type=p", AuthenticationManager::GetCurrentUser()->isAdmin())); - $adminMenu->addSubMenu(new MenuItem(gettext("Person Custom Fields"), "PersonCustomFieldsEditor.php", AuthenticationManager::GetCurrentUser()->isAdmin())); - $adminMenu->addSubMenu(new MenuItem(gettext("Volunteer Opportunities"), "VolunteerOpportunityEditor.php", AuthenticationManager::GetCurrentUser()->isAdmin())); + $peopleMenu = new MenuItem(gettext('People'), '', true, 'fa-users'); + $peopleMenu->addSubMenu(new MenuItem(gettext('Dashboard'), 'PeopleDashboard.php')); + $peopleMenu->addSubMenu(new MenuItem(gettext('Add New Person'), 'PersonEditor.php', AuthenticationManager::GetCurrentUser()->isAddRecordsEnabled())); + $peopleMenu->addSubMenu(new MenuItem(gettext('View Active People'), 'v2/people')); + $peopleMenu->addSubMenu(new MenuItem(gettext('View Inactive People'), 'v2/people?familyActiveStatus=inactive')); + $peopleMenu->addSubMenu(new MenuItem(gettext('View All People'), 'v2/people?familyActiveStatus=all')); + $peopleMenu->addSubMenu(new MenuItem(gettext('Add New Family'), 'FamilyEditor.php', AuthenticationManager::GetCurrentUser()->isAddRecordsEnabled())); + $peopleMenu->addSubMenu(new MenuItem(gettext('View Active Families'), 'v2/family')); + $peopleMenu->addSubMenu(new MenuItem(gettext('View Inactive Families'), 'v2/family?mode=inactive')); + $adminMenu = new MenuItem(gettext('Admin'), '', AuthenticationManager::GetCurrentUser()->isAdmin()); + $adminMenu->addSubMenu(new MenuItem(gettext('Classifications Manager'), 'OptionManager.php?mode=classes', AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu->addSubMenu(new MenuItem(gettext('Family Roles'), 'OptionManager.php?mode=famroles', AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu->addSubMenu(new MenuItem(gettext('Family Properties'), 'PropertyList.php?Type=f', AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu->addSubMenu(new MenuItem(gettext('Family Custom Fields'), 'FamilyCustomFieldsEditor.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu->addSubMenu(new MenuItem(gettext('People Properties'), 'PropertyList.php?Type=p', AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu->addSubMenu(new MenuItem(gettext('Person Custom Fields'), 'PersonCustomFieldsEditor.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu->addSubMenu(new MenuItem(gettext('Volunteer Opportunities'), 'VolunteerOpportunityEditor.php', AuthenticationManager::GetCurrentUser()->isAdmin())); $peopleMenu->addSubMenu($adminMenu); @@ -83,14 +84,14 @@ private static function getPeopleMenu() private static function getGroupMenu() { - $groupMenu = new MenuItem(gettext("Groups"), "", true, 'fa-tag'); - $groupMenu->addSubMenu(new MenuItem(gettext("List Groups"), "GroupList.php")); + $groupMenu = new MenuItem(gettext('Groups'), '', true, 'fa-tag'); + $groupMenu->addSubMenu(new MenuItem(gettext('List Groups'), 'GroupList.php')); $listOptions = ListOptionQuery::Create()->filterById(3)->orderByOptionSequence()->find(); foreach ($listOptions as $listOption) { if ($listOption->getOptionId() != 4) {// we avoid the sundaySchool, it's done under - $tmpMenu = self::addGroupSubMenus($listOption->getOptionName(), $listOption->getOptionId(), "GroupView.php?GroupID="); + $tmpMenu = self::addGroupSubMenus($listOption->getOptionName(), $listOption->getOptionId(), 'GroupView.php?GroupID='); if (!empty($tmpMenu)) { $groupMenu->addSubMenu($tmpMenu); } @@ -98,14 +99,14 @@ private static function getGroupMenu() } // now we're searching the unclassified groups - $tmpMenu = self::addGroupSubMenus(gettext("Unassigned"), 0, "GroupView.php?GroupID="); + $tmpMenu = self::addGroupSubMenus(gettext('Unassigned'), 0, 'GroupView.php?GroupID='); if (!empty($tmpMenu)) { $groupMenu->addSubMenu($tmpMenu); } - $adminMenu = new MenuItem(gettext("Admin"), "", AuthenticationManager::GetCurrentUser()->isAdmin()); - $adminMenu->addSubMenu(new MenuItem(gettext("Group Properties"), "PropertyList.php?Type=g", AuthenticationManager::GetCurrentUser()->isAdmin())); - $adminMenu->addSubMenu(new MenuItem(gettext("Group Types"), "OptionManager.php?mode=grptypes", AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu = new MenuItem(gettext('Admin'), '', AuthenticationManager::GetCurrentUser()->isAdmin()); + $adminMenu->addSubMenu(new MenuItem(gettext('Group Properties'), 'PropertyList.php?Type=g', AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu->addSubMenu(new MenuItem(gettext('Group Types'), 'OptionManager.php?mode=grptypes', AuthenticationManager::GetCurrentUser()->isAdmin())); $groupMenu->addSubMenu($adminMenu); @@ -114,10 +115,10 @@ private static function getGroupMenu() private static function getSundaySchoolMenu() { - $sundaySchoolMenu = new MenuItem(gettext("Sunday School"), "", SystemConfig::getBooleanValue("bEnabledSundaySchool"), 'fa-child'); - $sundaySchoolMenu->addSubMenu(new MenuItem(gettext("Dashboard"), "sundayschool/SundaySchoolDashboard.php")); + $sundaySchoolMenu = new MenuItem(gettext('Sunday School'), '', SystemConfig::getBooleanValue('bEnabledSundaySchool'), 'fa-child'); + $sundaySchoolMenu->addSubMenu(new MenuItem(gettext('Dashboard'), 'sundayschool/SundaySchoolDashboard.php')); // now we're searching the unclassified groups - $tmpMenu = self::addGroupSubMenus(gettext("Classes"), 4, "sundayschool/SundaySchoolClassView.php?groupId="); + $tmpMenu = self::addGroupSubMenus(gettext('Classes'), 4, 'sundayschool/SundaySchoolClassView.php?groupId='); if (!empty($tmpMenu)) { $sundaySchoolMenu->addSubMenu($tmpMenu); } @@ -127,97 +128,100 @@ private static function getSundaySchoolMenu() private static function getEventsMenu() { - $eventsMenu = new MenuItem(gettext("Events"), "", SystemConfig::getBooleanValue("bEnabledEvents"), 'fa-ticket-alt'); - $eventsMenu->addSubMenu(new MenuItem(gettext("Add Church Event"), "EventEditor.php", AuthenticationManager::GetCurrentUser()->isAddEventEnabled())); - $eventsMenu->addSubMenu(new MenuItem(gettext("List Church Events"), "ListEvents.php")); - $eventsMenu->addSubMenu(new MenuItem(gettext("List Event Types"), "EventNames.php", AuthenticationManager::GetCurrentUser()->isAddEventEnabled())); - $eventsMenu->addSubMenu(new MenuItem(gettext("Check-in and Check-out"), "Checkin.php")); - $eventsMenu->addSubMenu(new MenuItem(gettext('Event Attendance Reports'), "EventAttendance.php")); + $eventsMenu = new MenuItem(gettext('Events'), '', SystemConfig::getBooleanValue('bEnabledEvents'), 'fa-ticket-alt'); + $eventsMenu->addSubMenu(new MenuItem(gettext('Add Church Event'), 'EventEditor.php', AuthenticationManager::GetCurrentUser()->isAddEventEnabled())); + $eventsMenu->addSubMenu(new MenuItem(gettext('List Church Events'), 'ListEvents.php')); + $eventsMenu->addSubMenu(new MenuItem(gettext('List Event Types'), 'EventNames.php', AuthenticationManager::GetCurrentUser()->isAddEventEnabled())); + $eventsMenu->addSubMenu(new MenuItem(gettext('Check-in and Check-out'), 'Checkin.php')); + $eventsMenu->addSubMenu(new MenuItem(gettext('Event Attendance Reports'), 'EventAttendance.php')); + return $eventsMenu; } private static function getDepositsMenu() { - $depositsMenu = new MenuItem(gettext("Deposit"), "", SystemConfig::getBooleanValue("bEnabledFinance") && AuthenticationManager::GetCurrentUser()->isFinanceEnabled(), 'fa-cash-register'); - $depositsMenu->addSubMenu(new MenuItem(gettext("View All Deposits"), "FindDepositSlip.php", AuthenticationManager::GetCurrentUser()->isFinanceEnabled())); - $depositsMenu->addSubMenu(new MenuItem(gettext("Deposit Reports"), "FinancialReports.php", AuthenticationManager::GetCurrentUser()->isFinanceEnabled())); - $depositsMenu->addSubMenu(new MenuItem(gettext("Edit Deposit Slip"), "DepositSlipEditor.php?DepositSlipID=".$_SESSION['iCurrentDeposit'], AuthenticationManager::GetCurrentUser()->isFinanceEnabled())); - $depositsMenu->addCounter(new MenuCounter("iCurrentDeposit", "bg-green", $_SESSION['iCurrentDeposit'])); + $depositsMenu = new MenuItem(gettext('Deposit'), '', SystemConfig::getBooleanValue('bEnabledFinance') && AuthenticationManager::GetCurrentUser()->isFinanceEnabled(), 'fa-cash-register'); + $depositsMenu->addSubMenu(new MenuItem(gettext('View All Deposits'), 'FindDepositSlip.php', AuthenticationManager::GetCurrentUser()->isFinanceEnabled())); + $depositsMenu->addSubMenu(new MenuItem(gettext('Deposit Reports'), 'FinancialReports.php', AuthenticationManager::GetCurrentUser()->isFinanceEnabled())); + $depositsMenu->addSubMenu(new MenuItem(gettext('Edit Deposit Slip'), 'DepositSlipEditor.php?DepositSlipID='.$_SESSION['iCurrentDeposit'], AuthenticationManager::GetCurrentUser()->isFinanceEnabled())); + $depositsMenu->addCounter(new MenuCounter('iCurrentDeposit', 'bg-green', $_SESSION['iCurrentDeposit'])); - $adminMenu = new MenuItem(gettext("Admin"), "", AuthenticationManager::GetCurrentUser()->isAdmin()); - $adminMenu->addSubMenu(new MenuItem(gettext("Envelope Manager"), "ManageEnvelopes.php", AuthenticationManager::GetCurrentUser()->isAdmin())); - $adminMenu->addSubMenu(new MenuItem(gettext("Donation Funds"), "DonationFundEditor.php", AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu = new MenuItem(gettext('Admin'), '', AuthenticationManager::GetCurrentUser()->isAdmin()); + $adminMenu->addSubMenu(new MenuItem(gettext('Envelope Manager'), 'ManageEnvelopes.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $adminMenu->addSubMenu(new MenuItem(gettext('Donation Funds'), 'DonationFundEditor.php', AuthenticationManager::GetCurrentUser()->isAdmin())); $depositsMenu->addSubMenu($adminMenu); + return $depositsMenu; } - private static function getFundraisersMenu() { - $fundraiserMenu = new MenuItem(gettext("Fundraiser"), "", SystemConfig::getBooleanValue("bEnabledFundraiser"), 'fa-money-bill-alt'); - $fundraiserMenu->addSubMenu(new MenuItem(gettext("Create New Fundraiser"), "FundRaiserEditor.php?FundRaiserID=-1")); - $fundraiserMenu->addSubMenu(new MenuItem(gettext("View All Fundraisers"), "FindFundRaiser.php")); - $fundraiserMenu->addSubMenu(new MenuItem(gettext("Edit Fundraiser"), "FundRaiserEditor.php")); - $fundraiserMenu->addSubMenu(new MenuItem(gettext("Add Donors to Buyer List"), "AddDonors.php")); - $fundraiserMenu->addSubMenu(new MenuItem(gettext("View Buyers"), "PaddleNumList.php")); + $fundraiserMenu = new MenuItem(gettext('Fundraiser'), '', SystemConfig::getBooleanValue('bEnabledFundraiser'), 'fa-money-bill-alt'); + $fundraiserMenu->addSubMenu(new MenuItem(gettext('Create New Fundraiser'), 'FundRaiserEditor.php?FundRaiserID=-1')); + $fundraiserMenu->addSubMenu(new MenuItem(gettext('View All Fundraisers'), 'FindFundRaiser.php')); + $fundraiserMenu->addSubMenu(new MenuItem(gettext('Edit Fundraiser'), 'FundRaiserEditor.php')); + $fundraiserMenu->addSubMenu(new MenuItem(gettext('Add Donors to Buyer List'), 'AddDonors.php')); + $fundraiserMenu->addSubMenu(new MenuItem(gettext('View Buyers'), 'PaddleNumList.php')); $iCurrentFundraiser = 0; - if (array_key_exists('iCurrentFundraiser', $_SESSION)) - { + if (array_key_exists('iCurrentFundraiser', $_SESSION)) { $iCurrentFundraiser = $_SESSION['iCurrentFundraiser']; } - $fundraiserMenu->addCounter(new MenuCounter("iCurrentFundraiser", "bg-blue", $iCurrentFundraiser)); + $fundraiserMenu->addCounter(new MenuCounter('iCurrentFundraiser', 'bg-blue', $iCurrentFundraiser)); return $fundraiserMenu; } private static function getReportsMenu() { - $reportsMenu = new MenuItem(gettext("Data/Reports"), "", true, 'fa-file-pdf'); - $reportsMenu->addSubMenu(new MenuItem(gettext('Canvass Automation'), "CanvassAutomation.php")); - $reportsMenu->addSubMenu(new MenuItem(gettext("Query Menu"), "QueryList.php")); + $reportsMenu = new MenuItem(gettext('Data/Reports'), '', true, 'fa-file-pdf'); + $reportsMenu->addSubMenu(new MenuItem(gettext('Canvass Automation'), 'CanvassAutomation.php')); + $reportsMenu->addSubMenu(new MenuItem(gettext('Query Menu'), 'QueryList.php')); + return $reportsMenu; } - private static function addGroupSubMenus($menuName, $groupId, $viewURl) { $groups = GroupQuery::Create()->filterByType($groupId)->orderByName()->find(); if (!$groups->isEmpty()) { - $unassignedGroups = new MenuItem($menuName, "", true, "fa-tag"); + $unassignedGroups = new MenuItem($menuName, '', true, 'fa-tag'); foreach ($groups as $group) { - $unassignedGroups->addSubMenu(new MenuItem($group->getName(), $viewURl . $group->getID(), true, "fa-user-tag")); + $unassignedGroups->addSubMenu(new MenuItem($group->getName(), $viewURl.$group->getID(), true, 'fa-user-tag')); } + return $unassignedGroups; } + return null; } private static function getAdminMenu() { - $menu = new MenuItem(gettext("Admin"), "", true, 'fa-tools'); - $menu->addSubMenu(new MenuItem(gettext("Edit General Settings"), "SystemSettings.php",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("System Users"), "UserList.php",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("Property Types"), "PropertyTypeList.php",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("Restore Database"), "RestoreDatabase.php",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("Backup Database"), "BackupDatabase.php",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("CSV Import"), "CSVImport.php",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("CSV Export Records"), "CSVExport.php",AuthenticationManager::GetCurrentUser()->isCSVExport())); - $menu->addSubMenu(new MenuItem(gettext("Kiosk Manager"), "KioskManager.php",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("Debug"), "v2/admin/debug",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("Custom Menus"), "v2/admin/menus",AuthenticationManager::GetCurrentUser()->isAdmin())); - $menu->addSubMenu(new MenuItem(gettext("Reset System"), "v2/admin/database/reset",AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu = new MenuItem(gettext('Admin'), '', true, 'fa-tools'); + $menu->addSubMenu(new MenuItem(gettext('Edit General Settings'), 'SystemSettings.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('System Users'), 'UserList.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('Property Types'), 'PropertyTypeList.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('Restore Database'), 'RestoreDatabase.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('Backup Database'), 'BackupDatabase.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('CSV Import'), 'CSVImport.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('CSV Export Records'), 'CSVExport.php', AuthenticationManager::GetCurrentUser()->isCSVExport())); + $menu->addSubMenu(new MenuItem(gettext('Kiosk Manager'), 'KioskManager.php', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('Debug'), 'v2/admin/debug', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('Custom Menus'), 'v2/admin/menus', AuthenticationManager::GetCurrentUser()->isAdmin())); + $menu->addSubMenu(new MenuItem(gettext('Reset System'), 'v2/admin/database/reset', AuthenticationManager::GetCurrentUser()->isAdmin())); + return $menu; } - - private static function getCustomMenu() { - $menu = new MenuItem(gettext("Links"), "", SystemConfig::getBooleanValue("bEnabledMenuLinks"), 'fa-link'); + private static function getCustomMenu() + { + $menu = new MenuItem(gettext('Links'), '', SystemConfig::getBooleanValue('bEnabledMenuLinks'), 'fa-link'); $menuLinks = MenuLinkQuery::create()->orderByOrder()->find(); foreach ($menuLinks as $link) { $menu->addSubMenu(new MenuItem($link->getName(), $link->getUri())); } + return $menu; } - } diff --git a/src/ChurchCRM/Config/Menu/MenuCounter.php b/src/ChurchCRM/Config/Menu/MenuCounter.php index d3f7e6618d..ddeb72de77 100644 --- a/src/ChurchCRM/Config/Menu/MenuCounter.php +++ b/src/ChurchCRM/Config/Menu/MenuCounter.php @@ -2,7 +2,6 @@ namespace ChurchCRM\Config\Menu; - class MenuCounter { private $name; @@ -39,5 +38,4 @@ public function getInitValue() { return $this->initValue; } - } diff --git a/src/ChurchCRM/Config/Menu/MenuItem.php b/src/ChurchCRM/Config/Menu/MenuItem.php index 719b299f6b..b9b9714bbe 100644 --- a/src/ChurchCRM/Config/Menu/MenuItem.php +++ b/src/ChurchCRM/Config/Menu/MenuItem.php @@ -15,7 +15,7 @@ class MenuItem private $subItems = []; private $counters = []; - public function __construct($name, $uri, $hasPermission = true, $icon = "") + public function __construct($name, $uri, $hasPermission = true, $icon = '') { $this->name = $name; $this->uri = $uri; @@ -26,7 +26,7 @@ public function __construct($name, $uri, $hasPermission = true, $icon = "") public function addSubMenu(MenuItem $menuItem) { if (empty($menuItem->getIcon())) { - $menuItem->setIcon("fa-angle-double-right"); + $menuItem->setIcon('fa-angle-double-right'); } array_push($this->subItems, $menuItem); } @@ -40,12 +40,14 @@ public function getURI() { //Review SessionVar stuff if (!empty($this->uri)) { - if (filter_var($this->uri, FILTER_VALIDATE_URL) === FALSE) { - return SystemURLs::getRootPath() . "/" . $this->uri; + if (filter_var($this->uri, FILTER_VALIDATE_URL) === false) { + return SystemURLs::getRootPath().'/'.$this->uri; } $this->external = true; + return $this->uri; } + return ''; } @@ -57,8 +59,9 @@ public function setIcon($icon) public function getName() { if (mb_strlen($this->name) > $this->maxNameStr) { - return mb_substr($this->name, 0, $this->maxNameStr - 3) . " ..."; + return mb_substr($this->name, 0, $this->maxNameStr - 3).' ...'; } + return $this->name; } @@ -92,6 +95,7 @@ public function hasVisibleSubMenus() return true; } } + return false; } @@ -110,15 +114,18 @@ public function isVisible() if ($this->hasPermission && (!empty($this->uri) || $this->hasVisibleSubMenus())) { return true; } + return false; } - public function openMenu() { + public function openMenu() + { foreach ($this->subItems as $item) { if ($item->isActive()) { return true; } } + return false; } @@ -127,7 +134,7 @@ public function isActive() if (empty($this->uri)) { return false; } - return $_SERVER["REQUEST_URI"] == $this->getURI(); - } + return $_SERVER['REQUEST_URI'] == $this->getURI(); + } } diff --git a/src/ChurchCRM/Dashboard/ClassificationDashboardItem.php.php b/src/ChurchCRM/Dashboard/ClassificationDashboardItem.php.php index e615419a8b..779c148949 100644 --- a/src/ChurchCRM/Dashboard/ClassificationDashboardItem.php.php +++ b/src/ChurchCRM/Dashboard/ClassificationDashboardItem.php.php @@ -2,14 +2,16 @@ namespace ChurchCRM\Dashboard; -class ClassificationDashboardItem implements DashboardItemInterface { +class ClassificationDashboardItem implements DashboardItemInterface +{ + public static function getDashboardItemName() + { + return 'ClassificationBreakdown'; + } - public static function getDashboardItemName() { - return "ClassificationBreakdown"; - } - - public static function getDashboardItemValue() { - $data = []; + public static function getDashboardItemValue() + { + $data = []; $sSQL = 'select lst_OptionName as Classification, count(*) as count from person_per INNER JOIN list_lst ON per_cls_ID = lst_OptionID LEFT JOIN family_fam ON family_fam.fam_ID = person_per.per_fam_ID @@ -21,10 +23,10 @@ public static function getDashboardItemValue() { } return $data; - } - - public static function shouldInclude($PageName) { - return $PageName=="PeopleDashboard.php"; // this ID would be found on all pages. - } + } + public static function shouldInclude($PageName) + { + return $PageName == 'PeopleDashboard.php'; // this ID would be found on all pages. + } } diff --git a/src/ChurchCRM/Dashboard/CurrentLocaleMetadata.php b/src/ChurchCRM/Dashboard/CurrentLocaleMetadata.php index 8631243664..492ee6d173 100644 --- a/src/ChurchCRM/Dashboard/CurrentLocaleMetadata.php +++ b/src/ChurchCRM/Dashboard/CurrentLocaleMetadata.php @@ -1,17 +1,15 @@ getName(); - $data["code"] = $localeInfo->getLocale(); - $data["countryFlagCode"] = strtolower($localeInfo->getCountryCode()); + $data['name'] = $localeInfo->getName(); + $data['code'] = $localeInfo->getLocale(); + $data['countryFlagCode'] = strtolower($localeInfo->getCountryCode()); - $poLocalesFile = file_get_contents(SystemURLs::getDocumentRoot() . "/locale/poeditor.json"); + $poLocalesFile = file_get_contents(SystemURLs::getDocumentRoot().'/locale/poeditor.json'); $poLocales = json_decode($poLocalesFile, true); - $rawPOData = $poLocales["result"]["languages"]; - $data["poPerComplete"] = 0; - $data["displayPerCompleted"] = false; - if (!preg_match("#^en_(.*)$#i", $localeInfo->getLocale())) { + $rawPOData = $poLocales['result']['languages']; + $data['poPerComplete'] = 0; + $data['displayPerCompleted'] = false; + if (!preg_match('#^en_(.*)$#i', $localeInfo->getLocale())) { foreach ($rawPOData as $poLocale) { - if (strtolower($localeInfo->getPoLocaleId()) === strtolower($poLocale["code"])) { - $data["poPerComplete"] = $poLocale["percentage"]; - $data["displayPerCompleted"] = true; + if (strtolower($localeInfo->getPoLocaleId()) === strtolower($poLocale['code'])) { + $data['poPerComplete'] = $poLocale['percentage']; + $data['displayPerCompleted'] = true; break; } } diff --git a/src/ChurchCRM/Dashboard/DashboardItemInterface.php b/src/ChurchCRM/Dashboard/DashboardItemInterface.php index b7d71cb745..61e5943f5c 100644 --- a/src/ChurchCRM/Dashboard/DashboardItemInterface.php +++ b/src/ChurchCRM/Dashboard/DashboardItemInterface.php @@ -2,14 +2,14 @@ namespace ChurchCRM\Dashboard; -interface DashboardItemInterface { - - //must be all one word - no spaces - public static function getDashboardItemName(); - - //when provided with the page name of the user context, return true or false if this item should be loaded / provided in AJAX updates. - public static function shouldInclude($PageName); - - // return a PHP array with all of the values to be passed to the renderer - public static function getDashboardItemValue(); +interface DashboardItemInterface +{ + //must be all one word - no spaces + public static function getDashboardItemName(); + + //when provided with the page name of the user context, return true or false if this item should be loaded / provided in AJAX updates. + public static function shouldInclude($PageName); + + // return a PHP array with all of the values to be passed to the renderer + public static function getDashboardItemValue(); } diff --git a/src/ChurchCRM/Dashboard/EventsMenuItems.php b/src/ChurchCRM/Dashboard/EventsMenuItems.php index 4624cba709..6667994682 100644 --- a/src/ChurchCRM/Dashboard/EventsMenuItems.php +++ b/src/ChurchCRM/Dashboard/EventsMenuItems.php @@ -8,33 +8,36 @@ use ChurchCRM\PersonQuery; use Propel\Runtime\ActiveQuery\Criteria; -class EventsMenuItems implements DashboardItemInterface { - - public static function getDashboardItemName() { - return "EventsCounters"; +class EventsMenuItems implements DashboardItemInterface +{ + public static function getDashboardItemName() + { + return 'EventsCounters'; } - public static function getDashboardItemValue() { - $activeEvents = array ( - "Events" => self::getNumberEventsOfToday(), - "Birthdays" => self::getNumberBirthDates(), - "Anniversaries" => self::getNumberAnniversaries() - ); + public static function getDashboardItemValue() + { + $activeEvents = [ + 'Events' => self::getNumberEventsOfToday(), + 'Birthdays' => self::getNumberBirthDates(), + 'Anniversaries' => self::getNumberAnniversaries(), + ]; return $activeEvents; } - public static function shouldInclude($PageName) { + public static function shouldInclude($PageName) + { return true; // this ID would be found on all pages. } private static function getNumberEventsOfToday() { - $start_date = date("Y-m-d ")." 00:00:00"; - $end_date = date('Y-m-d H:i:s', strtotime($start_date . ' +1 day')); + $start_date = date('Y-m-d ').' 00:00:00'; + $end_date = date('Y-m-d H:i:s', strtotime($start_date.' +1 day')); return EventQuery::create() - ->where("event_start <= '".$start_date ."' AND event_end >= '".$end_date."'") /* the large events */ + ->where("event_start <= '".$start_date."' AND event_end >= '".$end_date."'") /* the large events */ ->_or()->where("event_start>='".$start_date."' AND event_end <= '".$end_date."'") /* the events of the day */ ->count(); } @@ -54,10 +57,9 @@ private static function getNumberAnniversaries() return $families = FamilyQuery::create() ->filterByDateDeactivated(null) ->filterByWeddingdate(null, Criteria::NOT_EQUAL) - ->addUsingAlias(FamilyTableMap::COL_FAM_WEDDINGDATE,"MONTH(". FamilyTableMap::COL_FAM_WEDDINGDATE .") =" . date('m'),Criteria::CUSTOM) - ->addUsingAlias(FamilyTableMap::COL_FAM_WEDDINGDATE,"DAY(". FamilyTableMap::COL_FAM_WEDDINGDATE .") =" . date('d'),Criteria::CUSTOM) + ->addUsingAlias(FamilyTableMap::COL_FAM_WEDDINGDATE, 'MONTH('.FamilyTableMap::COL_FAM_WEDDINGDATE.') ='.date('m'), Criteria::CUSTOM) + ->addUsingAlias(FamilyTableMap::COL_FAM_WEDDINGDATE, 'DAY('.FamilyTableMap::COL_FAM_WEDDINGDATE.') ='.date('d'), Criteria::CUSTOM) ->orderByWeddingdate('DESC') ->count(); } - } diff --git a/src/ChurchCRM/Emails/BaseEmail.php b/src/ChurchCRM/Emails/BaseEmail.php index 60e31556d2..9942123e7e 100644 --- a/src/ChurchCRM/Emails/BaseEmail.php +++ b/src/ChurchCRM/Emails/BaseEmail.php @@ -2,13 +2,13 @@ namespace ChurchCRM\Emails; +use ChurchCRM\dto\ChurchMetaData; use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; -use ChurchCRM\dto\ChurchMetaData; +use ChurchCRM\Service\SystemService; use Mustache_Engine; use Mustache_Loader_FilesystemLoader; use PHPMailer\PHPMailer\PHPMailer; -use ChurchCRM\Service\SystemService; abstract class BaseEmail { @@ -25,31 +25,30 @@ public function __construct($toAddresses) } // use .html instead of .mustache for default template extension - $options = array('extension' => '.html'); + $options = ['extension' => '.html']; - $this->mustache = new Mustache_Engine(array( - 'loader' => new Mustache_Loader_FilesystemLoader(SystemURLs::getDocumentRoot() . '/views/email', $options), - )); + $this->mustache = new Mustache_Engine([ + 'loader' => new Mustache_Loader_FilesystemLoader(SystemURLs::getDocumentRoot().'/views/email', $options), + ]); } private function setConnection() { - $this->mail = new PHPMailer(); $this->mail->IsSMTP(); $this->mail->CharSet = 'UTF-8'; - $this->mail->Timeout = intval(SystemConfig::getValue("iSMTPTimeout")); - $this->mail->Host = SystemConfig::getValue("sSMTPHost"); - $this->mail->SMTPAutoTLS = SystemConfig::getBooleanValue("bPHPMailerAutoTLS"); - $this->mail->SMTPSecure = SystemConfig::getValue("sPHPMailerSMTPSecure"); - if (SystemConfig::getBooleanValue("bSMTPAuth")) { + $this->mail->Timeout = intval(SystemConfig::getValue('iSMTPTimeout')); + $this->mail->Host = SystemConfig::getValue('sSMTPHost'); + $this->mail->SMTPAutoTLS = SystemConfig::getBooleanValue('bPHPMailerAutoTLS'); + $this->mail->SMTPSecure = SystemConfig::getValue('sPHPMailerSMTPSecure'); + if (SystemConfig::getBooleanValue('bSMTPAuth')) { $this->mail->SMTPAuth = true; - $this->mail->Username = SystemConfig::getValue("sSMTPUser"); - $this->mail->Password = SystemConfig::getValue("sSMTPPass"); + $this->mail->Username = SystemConfig::getValue('sSMTPUser'); + $this->mail->Password = SystemConfig::getValue('sSMTPPass'); } if (SystemConfig::debugEnabled()) { $this->mail->SMTPDebug = 1; - $this->mail->Debugoutput = "error_log"; + $this->mail->Debugoutput = 'error_log'; } } @@ -58,8 +57,8 @@ public function send() if (SystemConfig::hasValidMailServerSettings()) { return $this->mail->send(); } - return false; // we don't have a valid setting so let us make sure we don't crash. + return false; // we don't have a valid setting so let us make sure we don't crash. } public function getError() @@ -79,30 +78,31 @@ protected function buildMessage() protected function getMustacheTemplateName() { - return "BaseEmail"; + return 'BaseEmail'; } - protected function getCommonTokens() { + protected function getCommonTokens() + { $commonTokens = [ - "toEmails" => $this->mail->getToAddresses(), - "churchName" => ChurchMetaData::getChurchName(), - "churchAddress" => ChurchMetaData::getChurchFullAddress(), - "churchPhone" => ChurchMetaData::getChurchPhone(), - "churchEmail" => ChurchMetaData::getChurchEmail(), - "churchCRMURL" => SystemURLs::getURL(), - "dear" => SystemConfig::getValue('sDear'), - "confirmSincerely" => SystemConfig::getValue('sConfirmSincerely'), - "confirmSigner" => SystemConfig::getValue('sConfirmSigner'), - "copyrightDate" => SystemService::getCopyrightDate(), - "buttonNotWorkingText" => getText("If that doesn't work, copy and paste the following link in your browser"), - "emailErrorText" => getText("You received this email because we received a request for activity on your account. If you didn't request this you can safely delete this email."), - "stopEmailText" => getText("To stop receiving these emails, you can email") + 'toEmails' => $this->mail->getToAddresses(), + 'churchName' => ChurchMetaData::getChurchName(), + 'churchAddress' => ChurchMetaData::getChurchFullAddress(), + 'churchPhone' => ChurchMetaData::getChurchPhone(), + 'churchEmail' => ChurchMetaData::getChurchEmail(), + 'churchCRMURL' => SystemURLs::getURL(), + 'dear' => SystemConfig::getValue('sDear'), + 'confirmSincerely' => SystemConfig::getValue('sConfirmSincerely'), + 'confirmSigner' => SystemConfig::getValue('sConfirmSigner'), + 'copyrightDate' => SystemService::getCopyrightDate(), + 'buttonNotWorkingText' => gettext("If that doesn't work, copy and paste the following link in your browser"), + 'emailErrorText' => gettext("You received this email because we received a request for activity on your account. If you didn't request this you can safely delete this email."), + 'stopEmailText' => gettext('To stop receiving these emails, you can email'), ]; if (!empty($this->getFullURL())) { $buttonTokens = [ - "fullURL" => $this->getFullURL(), - "buttonText" => $this->getButtonText() + 'fullURL' => $this->getFullURL(), + 'buttonText' => $this->getButtonText(), ]; $commonTokens = array_merge($commonTokens, $buttonTokens); } @@ -110,7 +110,9 @@ protected function getCommonTokens() { return $commonTokens; } - abstract function getTokens(); - abstract function getFullURL(); - abstract function getButtonText(); + abstract public function getTokens(); + + abstract public function getFullURL(); + + abstract public function getButtonText(); } diff --git a/src/ChurchCRM/Emails/notifications/NewPersonOrFamilyEmail.php b/src/ChurchCRM/Emails/notifications/NewPersonOrFamilyEmail.php index 1256f99136..9c1e822c43 100644 --- a/src/ChurchCRM/Emails/notifications/NewPersonOrFamilyEmail.php +++ b/src/ChurchCRM/Emails/notifications/NewPersonOrFamilyEmail.php @@ -3,9 +3,8 @@ namespace ChurchCRM\Emails; use ChurchCRM\dto\SystemConfig; -use ChurchCRM\PersonQuery; -use ChurchCRM\FamilyQuery; use ChurchCRM\dto\SystemURLs; +use ChurchCRM\PersonQuery; class NewPersonOrFamilyEmail extends BaseEmail { @@ -13,92 +12,82 @@ class NewPersonOrFamilyEmail extends BaseEmail public function __construct($RelatedObject) { - $this->relatedObject = $RelatedObject; + $this->relatedObject = $RelatedObject; - $toAddresses = []; - $recipientPeople = explode(",",SystemConfig::getValue("sNewPersonNotificationRecipientIDs") ); + $toAddresses = []; + $recipientPeople = explode(',', SystemConfig::getValue('sNewPersonNotificationRecipientIDs')); - foreach($recipientPeople as $PersonID) { - $Person = PersonQuery::create()->findOneById($PersonID); - if(!empty($Person)) { - $email = $Person->getEmail(); - if (!empty($email)) { - array_push($toAddresses,$email); - } + foreach ($recipientPeople as $PersonID) { + $Person = PersonQuery::create()->findOneById($PersonID); + if (!empty($Person)) { + $email = $Person->getEmail(); + if (!empty($email)) { + array_push($toAddresses, $email); + } + } } - } - parent::__construct($toAddresses); - $this->mail->Subject = SystemConfig::getValue("sChurchName") . ": " . $this->getSubSubject(); - $this->mail->isHTML(true); - $this->mail->msgHTML($this->buildMessage()); + parent::__construct($toAddresses); + $this->mail->Subject = SystemConfig::getValue('sChurchName').': '.$this->getSubSubject(); + $this->mail->isHTML(true); + $this->mail->msgHTML($this->buildMessage()); } protected function getSubSubject() { - if (get_class($this->relatedObject) == "ChurchCRM\Person") - { - return gettext("New Person Added"); - } - else if (get_class($this->relatedObject) == "ChurchCRM\Family") - { - return gettext("New Family Added"); - } - + if (get_class($this->relatedObject) == "ChurchCRM\Person") { + return gettext('New Person Added'); + } elseif (get_class($this->relatedObject) == "ChurchCRM\Family") { + return gettext('New Family Added'); + } } - public function getTokens() + public function getTokens() { - $myTokens = [ - "toName" => gettext("Church Greeter") + $myTokens = [ + 'toName' => gettext('Church Greeter'), ]; - if (get_class($this->relatedObject) == "ChurchCRM\Family") - { - /* @var $family ChurchCRM\Family */ - $family = $this->relatedObject; - $myTokens['body'] = gettext("New Family Added")."\r\n". - gettext("Family Name").": ". $family->getName(); - $myTokens['FamilyEmail'] = $family->getEmail(); - $myTokens['FamilyPhone'] = $family->getCellPhone(); - $myTokens['FamilyAddress'] = $family->getAddress(); - $myTokens['IncludeDataInNewFamilyNotifications'] = SystemConfig::getBooleanValue("IncludeDataInNewPersonNotifications"); - } - elseif (get_class($this->relatedObject) == "ChurchCRM\Person") - { - /* @var $person ChurchCRM\Person */ - $person = $this->relatedObject; - $myTokens['body'] = gettext("New Person Added")."\r\n". - gettext("Person Name").": ". $person->getFullName(); - $myTokens['PersonEmail'] = $person->getEmail(); - $myTokens['PersonPhone'] = $person->getCellPhone(); - $myTokens['PersonAddress'] = $person->getAddress(); - $myTokens['PersonAge'] = $person->getAge(); - $myTokens['IncludeDataInNewPersonNotifications'] = SystemConfig::getBooleanValue("IncludeDataInNewPersonNotifications"); + if (get_class($this->relatedObject) == "ChurchCRM\Family") { + /* @var $family ChurchCRM\Family */ + $family = $this->relatedObject; + $myTokens['body'] = gettext('New Family Added')."\r\n". + gettext('Family Name').': '.$family->getName(); + $myTokens['FamilyEmail'] = $family->getEmail(); + $myTokens['FamilyPhone'] = $family->getCellPhone(); + $myTokens['FamilyAddress'] = $family->getAddress(); + $myTokens['IncludeDataInNewFamilyNotifications'] = SystemConfig::getBooleanValue('IncludeDataInNewPersonNotifications'); + } elseif (get_class($this->relatedObject) == "ChurchCRM\Person") { + /* @var $person ChurchCRM\Person */ + $person = $this->relatedObject; + $myTokens['body'] = gettext('New Person Added')."\r\n". + gettext('Person Name').': '.$person->getFullName(); + $myTokens['PersonEmail'] = $person->getEmail(); + $myTokens['PersonPhone'] = $person->getCellPhone(); + $myTokens['PersonAddress'] = $person->getAddress(); + $myTokens['PersonAge'] = $person->getAge(); + $myTokens['IncludeDataInNewPersonNotifications'] = SystemConfig::getBooleanValue('IncludeDataInNewPersonNotifications'); } - $myTokens['sGreeterCustomMsg1'] = SystemConfig::getValue("sGreeterCustomMsg1"); - $myTokens['sGreeterCustomMsg2'] = SystemConfig::getValue("sGreeterCustomMsg2"); + $myTokens['sGreeterCustomMsg1'] = SystemConfig::getValue('sGreeterCustomMsg1'); + $myTokens['sGreeterCustomMsg2'] = SystemConfig::getValue('sGreeterCustomMsg2'); return array_merge($this->getCommonTokens(), $myTokens); } - function getFullURL() + public function getFullURL() { if (get_class($this->relatedObject) == "ChurchCRM\Family") { - return SystemURLs::getURL() . "/v2/family/" . $this->relatedObject->getId(); - } - elseif (get_class($this->relatedObject) == "ChurchCRM\Person") { - return SystemURLs::getURL()."/PersonView.php?PersonID=". $this->relatedObject->getId(); + return SystemURLs::getURL().'/v2/family/'.$this->relatedObject->getId(); + } elseif (get_class($this->relatedObject) == "ChurchCRM\Person") { + return SystemURLs::getURL().'/PersonView.php?PersonID='.$this->relatedObject->getId(); } } - function getButtonText() + public function getButtonText() { if (get_class($this->relatedObject) == "ChurchCRM\Family") { - return gettext("View Family Page"); + return gettext('View Family Page'); + } elseif (get_class($this->relatedObject) == "ChurchCRM\Person") { + return gettext('View Person Page'); } - elseif (get_class($this->relatedObject) == "ChurchCRM\Person") { - return gettext("View Person Page"); - } - } } diff --git a/src/ChurchCRM/Emails/notifications/NotificationEmail.php b/src/ChurchCRM/Emails/notifications/NotificationEmail.php index 9f56f8c804..d1684b1fc0 100644 --- a/src/ChurchCRM/Emails/notifications/NotificationEmail.php +++ b/src/ChurchCRM/Emails/notifications/NotificationEmail.php @@ -8,35 +8,36 @@ class NotificationEmail extends BaseEmail { private $notificationSource; - public function __construct($toAddresses,$notificationSource) + public function __construct($toAddresses, $notificationSource) { $this->notificationSource = $notificationSource; parent::__construct($toAddresses); - $this->mail->Subject = SystemConfig::getValue("sChurchName") . ": " . $this->getSubSubject(); + $this->mail->Subject = SystemConfig::getValue('sChurchName').': '.$this->getSubSubject(); $this->mail->isHTML(true); $this->mail->msgHTML($this->buildMessage()); } protected function getSubSubject() { - return gettext("Notification"); + return gettext('Notification'); } - public function getTokens() + public function getTokens() { - $myTokens = [ - "toName" => gettext("Guardian(s) of") . " " . $this->notificationSource, - "body" => gettext("A notification was triggered by the classroom teacher at") . " " . date('Y-m-d H:i:s') . " " . gettext("Please go to this location") + $myTokens = [ + 'toName' => gettext('Guardian(s) of').' '.$this->notificationSource, + 'body' => gettext('A notification was triggered by the classroom teacher at').' '.date('Y-m-d H:i:s').' '.gettext('Please go to this location'), ]; + return array_merge($this->getCommonTokens(), $myTokens); } - function getFullURL() + public function getFullURL() { // TODO: Implement getFullURL() method. } - function getButtonText() + public function getButtonText() { // TODO: Implement getButtonText() method. } diff --git a/src/ChurchCRM/Emails/users/AccountDeletedEmail.php b/src/ChurchCRM/Emails/users/AccountDeletedEmail.php index 2141a9feb1..43324292a5 100644 --- a/src/ChurchCRM/Emails/users/AccountDeletedEmail.php +++ b/src/ChurchCRM/Emails/users/AccountDeletedEmail.php @@ -2,17 +2,15 @@ namespace ChurchCRM\Emails; - class AccountDeletedEmail extends BaseUserEmail { - protected function getSubSubject() { - return gettext("Your Account was Deleted"); + return gettext('Your Account was Deleted'); } protected function buildMessageBody() { - return gettext("Your ChurchCRM Account was Deleted."); + return gettext('Your ChurchCRM Account was Deleted.'); } } diff --git a/src/ChurchCRM/Emails/users/BaseUserEmail.php b/src/ChurchCRM/Emails/users/BaseUserEmail.php index ad79c91de1..09ec82f8e9 100644 --- a/src/ChurchCRM/Emails/users/BaseUserEmail.php +++ b/src/ChurchCRM/Emails/users/BaseUserEmail.php @@ -6,43 +6,44 @@ use ChurchCRM\dto\SystemURLs; use ChurchCRM\User; - abstract class BaseUserEmail extends BaseEmail { protected $user; /** * BaseUserEmail constructor. + * * @param $user User */ public function __construct($user) { parent::__construct([$user->getEmail()]); $this->user = $user; - $this->mail->Subject = SystemConfig::getValue("sChurchName") . ": " . $this->getSubSubject(); + $this->mail->Subject = SystemConfig::getValue('sChurchName').': '.$this->getSubSubject(); $this->mail->isHTML(true); $this->mail->msgHTML($this->buildMessage()); } public function getTokens() { - $myTokens = ["toName" => $this->user->getPerson()->getFirstName(), - "userName" => $this->user->getUserName(), - "userNameText" => gettext('Email/Username'), - "body" => $this->buildMessageBody() + $myTokens = ['toName' => $this->user->getPerson()->getFirstName(), + 'userName' => $this->user->getUserName(), + 'userNameText' => gettext('Email/Username'), + 'body' => $this->buildMessageBody(), ]; + return array_merge($this->getCommonTokens(), $myTokens); } - function getFullURL() + public function getFullURL() { - return SystemURLs::getURL() . "/session/begin?username=". $this->user->getUserName(); + return SystemURLs::getURL().'/session/begin?username='.$this->user->getUserName(); } - function getButtonText() + public function getButtonText() { return $this->user->getUserName(); } - protected abstract function buildMessageBody(); + abstract protected function buildMessageBody(); } diff --git a/src/ChurchCRM/Emails/users/LockedEmail.php b/src/ChurchCRM/Emails/users/LockedEmail.php index 78f25ce5b8..134604ac50 100644 --- a/src/ChurchCRM/Emails/users/LockedEmail.php +++ b/src/ChurchCRM/Emails/users/LockedEmail.php @@ -2,17 +2,15 @@ namespace ChurchCRM\Emails; - class LockedEmail extends BaseUserEmail { - protected function getSubSubject() { - return gettext("Account Locked"); + return gettext('Account Locked'); } protected function buildMessageBody() { - return gettext("Your ChurchCRM account was locked."); + return gettext('Your ChurchCRM account was locked.'); } } diff --git a/src/ChurchCRM/Emails/users/NewAccountEmail.php b/src/ChurchCRM/Emails/users/NewAccountEmail.php index 061f8472d7..d96e2ca47d 100644 --- a/src/ChurchCRM/Emails/users/NewAccountEmail.php +++ b/src/ChurchCRM/Emails/users/NewAccountEmail.php @@ -2,32 +2,32 @@ namespace ChurchCRM\Emails; - class NewAccountEmail extends BaseUserEmail { - protected $password; - public function __construct($user, $password) { + public function __construct($user, $password) + { $this->password = $password; parent::__construct($user); } protected function getSubSubject() { - return gettext("Your New Account"); + return gettext('Your New Account'); } protected function buildMessageBody() { - return gettext("A ChurchCRM account was created for you").":"; + return gettext('A ChurchCRM account was created for you').':'; } public function getTokens() { $parentTokens = parent::getTokens(); - $myTokens = ["password" => $this->password, - "passwordText" => gettext('New Password')]; + $myTokens = ['password' => $this->password, + 'passwordText' => gettext('New Password')]; + return array_merge($parentTokens, $myTokens); } } diff --git a/src/ChurchCRM/Emails/users/PasswordChangeEmail.php b/src/ChurchCRM/Emails/users/PasswordChangeEmail.php index b548e221a9..ebc363a488 100644 --- a/src/ChurchCRM/Emails/users/PasswordChangeEmail.php +++ b/src/ChurchCRM/Emails/users/PasswordChangeEmail.php @@ -2,31 +2,32 @@ namespace ChurchCRM\Emails; - class PasswordChangeEmail extends BaseUserEmail { protected $password; - public function __construct($user, $password) { + public function __construct($user, $password) + { $this->password = $password; parent::__construct($user); } protected function getSubSubject() { - return gettext("Password Changed"); + return gettext('Password Changed'); } protected function buildMessageBody() { - return gettext("Your ChurchCRM password was changed").":"; + return gettext('Your ChurchCRM password was changed').':'; } public function getTokens() { $parentTokens = parent::getTokens(); - $myTokens = ["password" => $this->password, - "passwordText" => gettext('New Password')]; + $myTokens = ['password' => $this->password, + 'passwordText' => gettext('New Password')]; + return array_merge($parentTokens, $myTokens); } } diff --git a/src/ChurchCRM/Emails/users/ResetPasswordEmail.php b/src/ChurchCRM/Emails/users/ResetPasswordEmail.php index ecfac5d25e..749a20012d 100644 --- a/src/ChurchCRM/Emails/users/ResetPasswordEmail.php +++ b/src/ChurchCRM/Emails/users/ResetPasswordEmail.php @@ -4,29 +4,30 @@ class ResetPasswordEmail extends BaseUserEmail { - protected $password; - public function __construct($user, $password) { + public function __construct($user, $password) + { $this->password = $password; parent::__construct($user); } protected function getSubSubject() { - return gettext("Password Reset"); + return gettext('Password Reset'); } protected function buildMessageBody() { - return gettext("You ChurchCRM updated password has been changed").":"; + return gettext('You ChurchCRM updated password has been changed').':'; } public function getTokens() { $parentTokens = parent::getTokens(); - $myTokens = ["password" => $this->password, - "passwordText" => gettext('New Password')]; + $myTokens = ['password' => $this->password, + 'passwordText' => gettext('New Password')]; + return array_merge($parentTokens, $myTokens); } } diff --git a/src/ChurchCRM/Emails/users/ResetPasswordTokenEmail.php b/src/ChurchCRM/Emails/users/ResetPasswordTokenEmail.php index 52c509c557..8685e57e45 100644 --- a/src/ChurchCRM/Emails/users/ResetPasswordTokenEmail.php +++ b/src/ChurchCRM/Emails/users/ResetPasswordTokenEmail.php @@ -6,30 +6,30 @@ class ResetPasswordTokenEmail extends BaseUserEmail { - protected $token; - public function __construct($user, $token) { + public function __construct($user, $token) + { $this->token = $token; parent::__construct($user); } protected function getSubSubject() { - return gettext("Password Reset Link"); + return gettext('Password Reset Link'); } protected function buildMessageBody() { - return gettext("You can reset your ChurchCRM password by clicking this link").":"; + return gettext('You can reset your ChurchCRM password by clicking this link').':'; } - function getFullURL() + public function getFullURL() { - return SystemURLs::getURL() . "/session/forgot-password/set/".$this->token; + return SystemURLs::getURL().'/session/forgot-password/set/'.$this->token; } - function getButtonText() + public function getButtonText() { return gettext('Reset Password'); } diff --git a/src/ChurchCRM/Emails/users/UnlockedEmail.php b/src/ChurchCRM/Emails/users/UnlockedEmail.php index 032e2a8624..157762e34f 100644 --- a/src/ChurchCRM/Emails/users/UnlockedEmail.php +++ b/src/ChurchCRM/Emails/users/UnlockedEmail.php @@ -2,17 +2,15 @@ namespace ChurchCRM\Emails; - class UnlockedEmail extends BaseUserEmail { - protected function getSubSubject() { - return gettext("Account Unlocked"); + return gettext('Account Unlocked'); } protected function buildMessageBody() { - return gettext("Your ChurchCRM account was unlocked."); + return gettext('Your ChurchCRM account was unlocked.'); } } diff --git a/src/ChurchCRM/Emails/verify/FamilyVerificationEmail.php b/src/ChurchCRM/Emails/verify/FamilyVerificationEmail.php index 6dd00ece6f..de336a3a8c 100644 --- a/src/ChurchCRM/Emails/verify/FamilyVerificationEmail.php +++ b/src/ChurchCRM/Emails/verify/FamilyVerificationEmail.php @@ -10,31 +10,32 @@ class FamilyVerificationEmail extends BaseEmail private $token; protected $familyName; - public function __construct($emails, $familyName, $token = "") + public function __construct($emails, $familyName, $token = '') { parent::__construct($emails); $this->familyName = $familyName; $this->token = $token; - $this->mail->Subject = $familyName . ": " . gettext("Please verify your family's information"); + $this->mail->Subject = $familyName.': '.gettext("Please verify your family's information"); $this->mail->isHTML(true); $this->mail->msgHTML($this->buildMessage()); } public function getTokens() { - $myTokens = ["toName" => $this->familyName . " " . gettext("Family"), - "body" => SystemConfig::getValue("sConfirm1") + $myTokens = ['toName' => $this->familyName.' '.gettext('Family'), + 'body' => SystemConfig::getValue('sConfirm1'), ]; + return array_merge($this->getCommonTokens(), $myTokens); } - function getFullURL() + public function getFullURL() { - return SystemURLs::getURL() . "/external/verify/". $this->token->getToken(); + return SystemURLs::getURL().'/external/verify/'.$this->token->getToken(); } - function getButtonText() + public function getButtonText() { - return gettext("Verify"); + return gettext('Verify'); } } diff --git a/src/ChurchCRM/Exceptions/NotImplementedException.php b/src/ChurchCRM/Exceptions/NotImplementedException.php index 28be4b90a7..ffa4e8474b 100644 --- a/src/ChurchCRM/Exceptions/NotImplementedException.php +++ b/src/ChurchCRM/Exceptions/NotImplementedException.php @@ -2,8 +2,6 @@ namespace ChurchCRM\Exceptions; - class NotImplementedException extends \LogicException { - -} \ No newline at end of file +} diff --git a/src/ChurchCRM/FileSystemUtils.php b/src/ChurchCRM/FileSystemUtils.php index da5df26b24..b00f41855f 100644 --- a/src/ChurchCRM/FileSystemUtils.php +++ b/src/ChurchCRM/FileSystemUtils.php @@ -1,68 +1,68 @@ info('Deleting files: '. $path . "*." . $ext); - foreach (GLOB($path . "*." . $ext) as $filename) { - UNLINK($filename); - } + public static function deleteFiles($path, $extArray) + { + foreach ($extArray as $ext) { + LoggerUtils::getAppLogger()->info('Deleting files: '.$path.'*.'.$ext); + foreach (glob($path.'*.'.$ext) as $filename) { + unlink($filename); } } + } - public static function moveDir($src, $dest) - { - $files = array_diff(scandir($src), ['.', '..']); - foreach ($files as $file) { - if (is_dir("$src/$file")) { - mkdir("$dest/$file"); - self::moveDir("$src/$file", "$dest/$file"); - } else { - rename("$src/$file", "$dest/$file"); - } + public static function moveDir($src, $dest) + { + $files = array_diff(scandir($src), ['.', '..']); + foreach ($files as $file) { + if (is_dir("$src/$file")) { + mkdir("$dest/$file"); + self::moveDir("$src/$file", "$dest/$file"); + } else { + rename("$src/$file", "$dest/$file"); } - return rmdir($src); } + + return rmdir($src); } } diff --git a/src/ChurchCRM/Interfaces/SystemCalendar.php b/src/ChurchCRM/Interfaces/SystemCalendar.php index 993d7e74ce..c5cba9ac25 100644 --- a/src/ChurchCRM/Interfaces/SystemCalendar.php +++ b/src/ChurchCRM/Interfaces/SystemCalendar.php @@ -2,14 +2,21 @@ namespace ChurchCRM\Interfaces; +interface SystemCalendar +{ + public function getId(); -interface SystemCalendar { - public function getId(); - public function getName(); - public function getAccessToken(); - public function getForegroundColor(); - public function getBackgroundColor(); - public function getEvents($start,$end); - public function getEventById($Id); - public static function isAvailable(); + public function getName(); + + public function getAccessToken(); + + public function getForegroundColor(); + + public function getBackgroundColor(); + + public function getEvents($start, $end); + + public function getEventById($Id); + + public static function isAvailable(); } diff --git a/src/ChurchCRM/KeyManager.php b/src/ChurchCRM/KeyManager.php index 40271d97b5..8e08517390 100644 --- a/src/ChurchCRM/KeyManager.php +++ b/src/ChurchCRM/KeyManager.php @@ -1,24 +1,23 @@ Image(SystemConfig::getValue('bDirLetterHead'), 12, 15, 185); $curY = 20 + (SystemConfig::getValue('incrementY') * 3) + 25; - $this->WriteAt(170, $curY, date(SystemConfig::getValue("sDateFormatLong"))); + $this->WriteAt(170, $curY, date(SystemConfig::getValue('sDateFormatLong'))); } elseif ($letterhead == 'none') { $curY = 20 + (SystemConfig::getValue('incrementY') * 3) + 25; - $this->WriteAt(170, $curY, date(SystemConfig::getValue("sDateFormatLong"))); + $this->WriteAt(170, $curY, date(SystemConfig::getValue('sDateFormatLong'))); } else { $dateX = 170; $dateY = 25; - $this->WriteAt($dateX, $dateY, date(SystemConfig::getValue("sDateFormatLong"))); + $this->WriteAt($dateX, $dateY, date(SystemConfig::getValue('sDateFormatLong'))); $curY = 20; $this->WriteAt(SystemConfig::getValue('leftX'), $curY, SystemConfig::getValue('sChurchName')); $curY += SystemConfig::getValue('incrementY'); @@ -112,7 +112,7 @@ public function StartLetterPage($fam_ID, $fam_Name, $fam_Address1, $fam_Address2 $this->WriteAt(SystemConfig::getValue('leftX'), $curY, SystemConfig::getValue('sChurchCity').', '.SystemConfig::getValue('sChurchState').' '.SystemConfig::getValue('sChurchZip')); $curY += SystemConfig::getValue('incrementY'); $curY += SystemConfig::getValue('incrementY'); // Skip another line before the phone/email - $this->WriteAt(SystemConfig::getValue('leftX'), $curY, SystemConfig::getValue('sChurchPhone').' '.SystemConfig::getValue('sChurchEmail')); + $this->WriteAt(SystemConfig::getValue('leftX'), $curY, SystemConfig::getValue('sChurchPhone').' '.SystemConfig::getValue('sChurchEmail')); $curY += 25; // mm to move to the second window } $this->WriteAt(SystemConfig::getValue('leftX'), $curY, $this->MakeSalutation($fam_ID)); @@ -132,13 +132,14 @@ public function StartLetterPage($fam_ID, $fam_Name, $fam_Address1, $fam_Address2 $curY += SystemConfig::getValue('incrementY'); } $curY += 5.0; // mm to get away from the second window - return $curY; + + return $curY; } public function MakeSalutation($famID) { $family = FamilyQuery::create()->findPk($famID); + return $family->getSalutation(); - } } diff --git a/src/ChurchCRM/Reports/PDF_Attendance.php b/src/ChurchCRM/Reports/PDF_Attendance.php index 43d30ce91d..c7554f8852 100644 --- a/src/ChurchCRM/Reports/PDF_Attendance.php +++ b/src/ChurchCRM/Reports/PDF_Attendance.php @@ -11,18 +11,17 @@ namespace ChurchCRM\Reports; - class PDF_Attendance extends ChurchInfoReport { ///////////////////////////////////////////////////////////////////////////// // -// function modified by S. Shaffer 3/2006 to change the following -// (1) handle the case where the list of names covers more than one page -// (2) rearranged some of the code to make it clearer for multi-page + // function modified by S. Shaffer 3/2006 to change the following + // (1) handle the case where the list of names covers more than one page + // (2) rearranged some of the code to make it clearer for multi-page // // for information contact Steve Shaffer at stephen@shaffers4christ.com // -///////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////// // Constructor public function __construct() @@ -37,289 +36,304 @@ public function __construct() $this->AddPage(); } - public function DrawAttendanceCalendar($nameX, $yTop, $aNames, $tTitle, $extraLines, - $tFirstSunday, $tLastSunday, - $tNoSchool1, $tNoSchool2, $tNoSchool3, $tNoSchool4, - $tNoSchool5, $tNoSchool6, $tNoSchool7, $tNoSchool8, $rptHeader,$imgs,$with_img) + public function DrawAttendanceCalendar( + $nameX, + $yTop, + $aNames, + $tTitle, + $extraLines, + $tFirstSunday, + $tLastSunday, + $tNoSchool1, + $tNoSchool2, + $tNoSchool3, + $tNoSchool4, + $tNoSchool5, + $tNoSchool6, + $tNoSchool7, + $tNoSchool8, + $rptHeader, + $imgs, + $with_img + ) { $startMonthX = 60; $dayWid = 7; - if ($with_img) - $yIncrement = 10; // normally 6 - else - $yIncrement = 6; + if ($with_img) { + $yIncrement = 10; + } // normally 6 + else { + $yIncrement = 6; + } $yTitle = 20; $yTeachers = $yTitle + $yIncrement; - $nameX = 10+$yIncrement/2; + $nameX = 10 + $yIncrement / 2; unset($NameList); $numMembers = 0; $aNameCount = 0; - $MaxLinesPerPage = -5*$yIncrement+66; // 36 lines for a yIncrement of 6, 16 lines for a yIncrement of 10, y=-5x+66 + $MaxLinesPerPage = -5 * $yIncrement + 66; // 36 lines for a yIncrement of 6, 16 lines for a yIncrement of 10, y=-5x+66 $fontTitleTitle = 16; - if ($with_img) - $fontTitleNormal = 11; - else - $fontTitleNormal = 10; + if ($with_img) { + $fontTitleNormal = 11; + } else { + $fontTitleNormal = 10; + } $aNoSchoolX = []; $noSchoolCnt = 0; // -// determine how many pages will be includes in this report + // determine how many pages will be includes in this report // // -// First cull the input names array to remove duplicates, then extend the array to include the requested -// number of blank lines + // First cull the input names array to remove duplicates, then extend the array to include the requested + // number of blank lines // - $prevThisName = ''; + $prevThisName = ''; $aNameCount = 0; for ($row = 0; $row < count($aNames); $row++) { - $person = $aNames[$row]; - $thisName = ($person->getFullName()); - - // Special handling for person listed twice- only show once in the Attendance Calendar - // This happens when a child is listed in two different families (parents divorced and - // both active in the church) - if ($thisName != $prevThisName) { - $NameList[$aNameCount] = $thisName; - $imgList[$aNameCount++] = $imgs[$row]; - // echo "adding {$thisName} to NameList at {$aNameCount}\n\r"; - } + $person = $aNames[$row]; + $thisName = $person->getFullName(); + + // Special handling for person listed twice- only show once in the Attendance Calendar + // This happens when a child is listed in two different families (parents divorced and + // both active in the church) + if ($thisName != $prevThisName) { + $NameList[$aNameCount] = $thisName; + $imgList[$aNameCount++] = $imgs[$row]; + // echo "adding {$thisName} to NameList at {$aNameCount}\n\r"; + } $prevThisName = $thisName; } // -// add extra blank lines to the array + // add extra blank lines to the array // - for ($i = 0; $i < $extraLines; $i++) { - $NameList[$aNameCount] = ' '; - $imgList[$aNameCount++] = ''; - } - - $numMembers = count($NameList); - $nPages = ceil($numMembers / $MaxLinesPerPage); - - - // echo "nPages = {$nPages} \n\r"; - // - // Main loop which draws each page - // - for ($p = 0; $p < $nPages; $p++) { - // - // Paint the title section- class name and year on the top, then teachers/liaison - // - if ($p > 0) { - $this->AddPage(); - } - $this->SetFont('Times', 'B', $fontTitleTitle); - $this->WriteAt($nameX, $yTitle, $rptHeader); - - $this->SetLineWidth(0.5); - //$this->Line($nameX-5, $yTeachers - 0.45, 195, $yTeachers - 0.45); // unusefull - $yMonths = $yTop; - $yDays = $yTop + $yIncrement; - $y = $yDays + $yIncrement; - // - // put title on the page - // - $this->SetFont('Times', 'B', $fontTitleNormal); - $this->WriteAt($nameX, $yDays + 1, $tTitle); - $this->SetFont('Times', '', $fontTitleNormal); - - // - // calculate the starting and ending rows for the page - // - $pRowStart = $p * $MaxLinesPerPage; - $pRowEnd = min(((($p + 1) * $MaxLinesPerPage)), $numMembers); - // echo "pRowStart = {$pRowStart} and pRowEnd= {$pRowEnd}\n\r"; - // - // Write the names down the page and draw lines between - // - - $this->SetLineWidth(0.25); - for ($row = $pRowStart; $row < $pRowEnd; $row++) { - $this->WriteAt($nameX, $y + (($with_img==true)?3:1), $NameList[$row]); - - if($with_img == true) - { - //$this->SetLineWidth(0.5); - $this->Line($nameX-$yIncrement,$y,$nameX,$y); - $this->Line($nameX-$yIncrement,$y+$yIncrement,$nameX,$y+$yIncrement); - $this->Line($nameX-$yIncrement,$y,$nameX,$y); - $this->Line($nameX-$yIncrement,$y,$nameX-$yIncrement,$y+$yIncrement); - - // we build the cross in the case of there's no photo - //$this->SetLineWidth(0.25); - $this->Line($nameX-$yIncrement,$y+$yIncrement,$nameX,$y); - $this->Line($nameX-$yIncrement,$y,$nameX,$y+$yIncrement); - - - if ($NameList[$row] != ' ' && strlen($imgList[$row]) > 5 && file_exists($imgList[$row])) - { - list($width, $height) = getimagesize($imgList[$row]); - $factor = $yIncrement/$height; - $nw = $width*$factor; - $nh = $yIncrement; - - $this->Image($imgList[$row], $nameX-$nw , $y, $nw,$nh,'JPG'); - } - } - - $y += $yIncrement; - } - // - // write a totals text at the bottom - // - $this->SetFont('Times', 'B', $fontTitleNormal); - $this->WriteAt($nameX, $y + 1, gettext('Totals')); - $this->SetFont('Times', '', $fontTitleNormal); - - $bottomY = $y + $yIncrement; - // - // Paint the calendar grid - // - $dayCounter = 0; - $monthCounter = 0; - $dayX = $startMonthX; - $monthX = $startMonthX; - $noSchoolCnt = 0; - $heavyVerticalXCnt = 0; - $lightVerticalXCnt = 0; - - $tWhichSunday = $tFirstSunday; - $dWhichSunday = strtotime($tWhichSunday); - - $dWhichMonthDate = $dWhichSunday; - $whichMonth = date('n', $dWhichMonthDate); - - $doneFlag = false; - - while (!$doneFlag) { - $dayListX[$dayCounter] = $dayX; - - $dayListNum[$dayCounter] = date('d', $dWhichSunday); - - if ($tWhichSunday == $tNoSchool1) { - $aNoSchoolX[$noSchoolCnt++] = $dayX; - } - if ($tWhichSunday == $tNoSchool2) { - $aNoSchoolX[$noSchoolCnt++] = $dayX; - } - if ($tWhichSunday == $tNoSchool3) { - $aNoSchoolX[$noSchoolCnt++] = $dayX; - } - if ($tWhichSunday == $tNoSchool4) { - $aNoSchoolX[$noSchoolCnt++] = $dayX; - } - if ($tWhichSunday == $tNoSchool5) { - $aNoSchoolX[$noSchoolCnt++] = $dayX; - } - if ($tWhichSunday == $tNoSchool6) { - $aNoSchoolX[$noSchoolCnt++] = $dayX; - } - if ($tWhichSunday == $tNoSchool7) { - $aNoSchoolX[$noSchoolCnt++] = $dayX; - } - if ($tWhichSunday == $tNoSchool8) { - $aNoSchoolX[$noSchoolCnt++] = $dayX; - } - - if (date('n', $dWhichSunday) != $whichMonth) { // Finish the previous month - $this->WriteAt($monthX, $yMonths + 1, mb_substr(gettext(date('F', $dWhichMonthDate)),0,3)); - $aHeavyVerticalX[$heavyVerticalXCnt++] = $monthX; - $whichMonth = date('n', $dWhichSunday); - $dWhichMonthDate = $dWhichSunday; - $monthX = $dayX; - } else { - $aLightVerticalX[$lightVerticalXCnt++] = $dayX; - } - $dayX += $dayWid; - ++$dayCounter; - - // if ($tWhichSunday == $tLastSunday) $doneFlag = true; - // - // replaced this conditional to correct a problem where begin and end dates were not the same - // day of week - // - if (strtotime($tWhichSunday) >= strtotime($tLastSunday)) { - $doneFlag = true; - } - - // Increment the date by one week - // - $sundayDay = date('d', $dWhichSunday); - $sundayMonth = date('m', $dWhichSunday); - $sundayYear = date('Y', $dWhichSunday); - $dWhichSunday = mktime(0, 0, 0, $sundayMonth, $sundayDay + 7, $sundayYear); - $tWhichSunday = date('Y-m-d', $dWhichSunday); - } - $aHeavyVerticalX[$heavyVerticalXCnt++] = $monthX; - $this->WriteAt($monthX, $yMonths + 1, substr(gettext(date('F', $dWhichMonthDate)),0,3)); - - $rightEdgeX = $dayX; - - // Draw vertical lines now that we know how far down the list goes - - // Draw the left-most vertical line heavy, through the month row - $this->SetLineWidth(0.5); - $this->Line($nameX, $yMonths, $nameX, $bottomY); - - // Draw the left-most line between the people and the calendar - $lineTopY = $yMonths; - $this->Line($startMonthX, $lineTopY, $startMonthX, $bottomY); - - // Draw the vertical lines in the grid based on X coords stored above - $this->SetLineWidth(0.5); - for ($i = 0; $i < $heavyVerticalXCnt; $i++) { - $this->Line($aHeavyVerticalX[$i], $lineTopY, $aHeavyVerticalX[$i], $bottomY); - } - - $lineTopY = $yDays; - $this->SetLineWidth(0.25); - for ($i = 0; $i < $lightVerticalXCnt; $i++) { - $this->Line($aLightVerticalX[$i], $lineTopY, $aLightVerticalX[$i], $bottomY); - } - - // Draw the right-most vertical line heavy, through the month row - $this->SetLineWidth(0.5); - $this->Line($dayX, $yMonths, $dayX, $bottomY); - - // Fill the no-school days - $this->SetFillColor(200, 200, 200); - $this->SetLineWidth(0.25); - for ($i = 0; $i < count($aNoSchoolX); $i++) { - $this->Rect($aNoSchoolX[$i], $yDays, $dayWid, $bottomY - $yDays, 'FD'); - } - - for ($i = 0; $i < $dayCounter; $i++) { - $this->WriteAt($dayListX[$i], $yDays + 1, $dayListNum[$i]); - } - - // Draw heavy lines to delimit the Months and totals - $this->SetLineWidth(0.5); - $this->Line($nameX, $yMonths, $rightEdgeX, $yMonths); - $this->Line($nameX, $yMonths + $yIncrement, $rightEdgeX, $yMonths + $yIncrement); - $this->Line($nameX, $yMonths + 2 * $yIncrement, $rightEdgeX, $yMonths + 2 * $yIncrement); - $yBottom = $yMonths + (($numMembers + $extraLines + 2) * $yIncrement); - $this->Line($nameX, $yBottom, $rightEdgeX, $yBottom); - $this->Line($nameX, $yBottom + $yIncrement, $rightEdgeX, $yBottom + $yIncrement); - // - // add in horizontal lines between names - // - $y = $yTop; - for ($s = $pRowStart; $s < $pRowEnd + 4; $s++) { - $this->Line($nameX, $y, $rightEdgeX, $y); - $y += $yIncrement; - } - - //$this->AddPage(); - } - - return $bottomY; + for ($i = 0; $i < $extraLines; $i++) { + $NameList[$aNameCount] = ' '; + $imgList[$aNameCount++] = ''; + } + + $numMembers = count($NameList); + $nPages = ceil($numMembers / $MaxLinesPerPage); + + // echo "nPages = {$nPages} \n\r"; + // + // Main loop which draws each page + // + for ($p = 0; $p < $nPages; $p++) { + // + // Paint the title section- class name and year on the top, then teachers/liaison + // + if ($p > 0) { + $this->AddPage(); + } + $this->SetFont('Times', 'B', $fontTitleTitle); + $this->WriteAt($nameX, $yTitle, $rptHeader); + + $this->SetLineWidth(0.5); + //$this->Line($nameX-5, $yTeachers - 0.45, 195, $yTeachers - 0.45); // unusefull + $yMonths = $yTop; + $yDays = $yTop + $yIncrement; + $y = $yDays + $yIncrement; + // + // put title on the page + // + $this->SetFont('Times', 'B', $fontTitleNormal); + $this->WriteAt($nameX, $yDays + 1, $tTitle); + $this->SetFont('Times', '', $fontTitleNormal); + + // + // calculate the starting and ending rows for the page + // + $pRowStart = $p * $MaxLinesPerPage; + $pRowEnd = min(($p + 1) * $MaxLinesPerPage, $numMembers); + // echo "pRowStart = {$pRowStart} and pRowEnd= {$pRowEnd}\n\r"; + // + // Write the names down the page and draw lines between + // + + $this->SetLineWidth(0.25); + for ($row = $pRowStart; $row < $pRowEnd; $row++) { + $this->WriteAt($nameX, $y + (($with_img == true) ? 3 : 1), $NameList[$row]); + + if ($with_img == true) { + //$this->SetLineWidth(0.5); + $this->Line($nameX - $yIncrement, $y, $nameX, $y); + $this->Line($nameX - $yIncrement, $y + $yIncrement, $nameX, $y + $yIncrement); + $this->Line($nameX - $yIncrement, $y, $nameX, $y); + $this->Line($nameX - $yIncrement, $y, $nameX - $yIncrement, $y + $yIncrement); + + // we build the cross in the case of there's no photo + //$this->SetLineWidth(0.25); + $this->Line($nameX - $yIncrement, $y + $yIncrement, $nameX, $y); + $this->Line($nameX - $yIncrement, $y, $nameX, $y + $yIncrement); + + if ($NameList[$row] != ' ' && strlen($imgList[$row]) > 5 && file_exists($imgList[$row])) { + list($width, $height) = getimagesize($imgList[$row]); + $factor = $yIncrement / $height; + $nw = $width * $factor; + $nh = $yIncrement; + + $this->Image($imgList[$row], $nameX - $nw, $y, $nw, $nh, 'JPG'); + } + } + + $y += $yIncrement; + } + // + // write a totals text at the bottom + // + $this->SetFont('Times', 'B', $fontTitleNormal); + $this->WriteAt($nameX, $y + 1, gettext('Totals')); + $this->SetFont('Times', '', $fontTitleNormal); + + $bottomY = $y + $yIncrement; + // + // Paint the calendar grid + // + $dayCounter = 0; + $monthCounter = 0; + $dayX = $startMonthX; + $monthX = $startMonthX; + $noSchoolCnt = 0; + $heavyVerticalXCnt = 0; + $lightVerticalXCnt = 0; + + $tWhichSunday = $tFirstSunday; + $dWhichSunday = strtotime($tWhichSunday); + + $dWhichMonthDate = $dWhichSunday; + $whichMonth = date('n', $dWhichMonthDate); + + $doneFlag = false; + + while (!$doneFlag) { + $dayListX[$dayCounter] = $dayX; + + $dayListNum[$dayCounter] = date('d', $dWhichSunday); + + if ($tWhichSunday == $tNoSchool1) { + $aNoSchoolX[$noSchoolCnt++] = $dayX; + } + if ($tWhichSunday == $tNoSchool2) { + $aNoSchoolX[$noSchoolCnt++] = $dayX; + } + if ($tWhichSunday == $tNoSchool3) { + $aNoSchoolX[$noSchoolCnt++] = $dayX; + } + if ($tWhichSunday == $tNoSchool4) { + $aNoSchoolX[$noSchoolCnt++] = $dayX; + } + if ($tWhichSunday == $tNoSchool5) { + $aNoSchoolX[$noSchoolCnt++] = $dayX; + } + if ($tWhichSunday == $tNoSchool6) { + $aNoSchoolX[$noSchoolCnt++] = $dayX; + } + if ($tWhichSunday == $tNoSchool7) { + $aNoSchoolX[$noSchoolCnt++] = $dayX; + } + if ($tWhichSunday == $tNoSchool8) { + $aNoSchoolX[$noSchoolCnt++] = $dayX; + } + + if (date('n', $dWhichSunday) != $whichMonth) { // Finish the previous month + $this->WriteAt($monthX, $yMonths + 1, mb_substr(gettext(date('F', $dWhichMonthDate)), 0, 3)); + $aHeavyVerticalX[$heavyVerticalXCnt++] = $monthX; + $whichMonth = date('n', $dWhichSunday); + $dWhichMonthDate = $dWhichSunday; + $monthX = $dayX; + } else { + $aLightVerticalX[$lightVerticalXCnt++] = $dayX; + } + $dayX += $dayWid; + $dayCounter++; + + // if ($tWhichSunday == $tLastSunday) $doneFlag = true; + // + // replaced this conditional to correct a problem where begin and end dates were not the same + // day of week + // + if (strtotime($tWhichSunday) >= strtotime($tLastSunday)) { + $doneFlag = true; + } + + // Increment the date by one week + // + $sundayDay = date('d', $dWhichSunday); + $sundayMonth = date('m', $dWhichSunday); + $sundayYear = date('Y', $dWhichSunday); + $dWhichSunday = mktime(0, 0, 0, $sundayMonth, $sundayDay + 7, $sundayYear); + $tWhichSunday = date('Y-m-d', $dWhichSunday); + } + $aHeavyVerticalX[$heavyVerticalXCnt++] = $monthX; + $this->WriteAt($monthX, $yMonths + 1, substr(gettext(date('F', $dWhichMonthDate)), 0, 3)); + + $rightEdgeX = $dayX; + + // Draw vertical lines now that we know how far down the list goes + + // Draw the left-most vertical line heavy, through the month row + $this->SetLineWidth(0.5); + $this->Line($nameX, $yMonths, $nameX, $bottomY); + + // Draw the left-most line between the people and the calendar + $lineTopY = $yMonths; + $this->Line($startMonthX, $lineTopY, $startMonthX, $bottomY); + + // Draw the vertical lines in the grid based on X coords stored above + $this->SetLineWidth(0.5); + for ($i = 0; $i < $heavyVerticalXCnt; $i++) { + $this->Line($aHeavyVerticalX[$i], $lineTopY, $aHeavyVerticalX[$i], $bottomY); + } + + $lineTopY = $yDays; + $this->SetLineWidth(0.25); + for ($i = 0; $i < $lightVerticalXCnt; $i++) { + $this->Line($aLightVerticalX[$i], $lineTopY, $aLightVerticalX[$i], $bottomY); + } + + // Draw the right-most vertical line heavy, through the month row + $this->SetLineWidth(0.5); + $this->Line($dayX, $yMonths, $dayX, $bottomY); + + // Fill the no-school days + $this->SetFillColor(200, 200, 200); + $this->SetLineWidth(0.25); + for ($i = 0; $i < count($aNoSchoolX); $i++) { + $this->Rect($aNoSchoolX[$i], $yDays, $dayWid, $bottomY - $yDays, 'FD'); + } + + for ($i = 0; $i < $dayCounter; $i++) { + $this->WriteAt($dayListX[$i], $yDays + 1, $dayListNum[$i]); + } + + // Draw heavy lines to delimit the Months and totals + $this->SetLineWidth(0.5); + $this->Line($nameX, $yMonths, $rightEdgeX, $yMonths); + $this->Line($nameX, $yMonths + $yIncrement, $rightEdgeX, $yMonths + $yIncrement); + $this->Line($nameX, $yMonths + 2 * $yIncrement, $rightEdgeX, $yMonths + 2 * $yIncrement); + $yBottom = $yMonths + (($numMembers + $extraLines + 2) * $yIncrement); + $this->Line($nameX, $yBottom, $rightEdgeX, $yBottom); + $this->Line($nameX, $yBottom + $yIncrement, $rightEdgeX, $yBottom + $yIncrement); + // + // add in horizontal lines between names + // + $y = $yTop; + for ($s = $pRowStart; $s < $pRowEnd + 4; $s++) { + $this->Line($nameX, $y, $rightEdgeX, $y); + $y += $yIncrement; + } + + //$this->AddPage(); + } + + return $bottomY; } } diff --git a/src/ChurchCRM/Reports/PDF_DepositReport.php b/src/ChurchCRM/Reports/PDF_DepositReport.php index 17db0924df..fc4b0b4830 100644 --- a/src/ChurchCRM/Reports/PDF_DepositReport.php +++ b/src/ChurchCRM/Reports/PDF_DepositReport.php @@ -5,18 +5,18 @@ class PDF_DepositReport extends ChurchInfoReport { // Private properties - public $_Char_Size = 10; // Character size - public $_Font = 'Courier'; + public $_Char_Size = 10; // Character size + public $_Font = 'Courier'; - // Sets the character size - // This changes the line height too - public function Set_Char_Size($pt) - { - if ($pt > 3) { - $this->_Char_Size = $pt; - $this->SetFont($this->_Font, '', $this->_Char_Size); - } - } + // Sets the character size + // This changes the line height too + public function Set_Char_Size($pt) + { + if ($pt > 3) { + $this->_Char_Size = $pt; + $this->SetFont($this->_Font, '', $this->_Char_Size); + } + } public function PrintRightJustified($x, $y, $str) { @@ -26,15 +26,15 @@ public function PrintRightJustified($x, $y, $str) $this->Write(8, $str); } - // Constructor - public function __construct() - { - parent::__construct('P', 'mm', $this->paperFormat); + // Constructor + public function __construct() + { + parent::__construct('P', 'mm', $this->paperFormat); // - $this->SetFont('courier'); - $this->SetMargins(0, 0); - $this->Set_Char_Size(10); - $this->SetAutoPageBreak(false); - } + $this->SetFont('courier'); + $this->SetMargins(0, 0); + $this->Set_Char_Size(10); + $this->SetAutoPageBreak(false); + } } diff --git a/src/ChurchCRM/Reports/PDF_Directory.php b/src/ChurchCRM/Reports/PDF_Directory.php index 0bcbe3593e..b586c2e40e 100644 --- a/src/ChurchCRM/Reports/PDF_Directory.php +++ b/src/ChurchCRM/Reports/PDF_Directory.php @@ -3,9 +3,9 @@ namespace ChurchCRM\Reports; use ChurchCRM\dto\SystemConfig; -use ChurchCRM\Utils\MiscUtils; use ChurchCRM\FamilyQuery; use ChurchCRM\PersonQuery; +use ChurchCRM\Utils\MiscUtils; class PDF_Directory extends ChurchInfoReport { @@ -56,7 +56,7 @@ public function Footer() if ($bDirUseTitlePage) { $iPageNumber--; } - $this->Cell(0, 10, gettext('Page').' '.$iPageNumber.' '.date(SystemConfig::getValue("sDateTimeFormat"), time()), 0, 0, 'C'); // in 2.6.0, create a new config for time formatting also + $this->Cell(0, 10, gettext('Page').' '.$iPageNumber.' '.date(SystemConfig::getValue('sDateTimeFormat'), time()), 0, 0, 'C'); // in 2.6.0, create a new config for time formatting also } } @@ -75,7 +75,7 @@ public function TitlePage() //Move to the right $this->MultiCell(197, 10, "\n\n\n".SystemConfig::getValue('sChurchName')."\n\n".gettext('Directory')."\n\n", 0, 'C'); $this->Ln(5); - $today = date(SystemConfig::getValue("sDateFormatLong")); + $today = date(SystemConfig::getValue('sDateFormatLong')); $this->MultiCell(197, 10, $today."\n\n", 0, 'C'); $sContact = sprintf("%s\n%s, %s %s\n\n%s\n\n", SystemConfig::getValue('sChurchAddress'), SystemConfig::getValue('sChurchCity'), SystemConfig::getValue('sChurchState'), SystemConfig::getValue('sChurchZip'), SystemConfig::getValue('sChurchPhone')); @@ -208,7 +208,7 @@ public function Add_Header($sLetter) $this->SetTextColor(255); $this->SetFont($this->_Font, 'B', $this->_Char_Size); // $_PosX = $this->_Column == 0 ? $this->_Margin_Left : $this->w - $this->_Margin_Left - $this->_ColWidth; - $_PosX = ($this->_Column * ($this->_ColWidth + $this->_Gutter)) + $this->_Margin_Left; + $_PosX = ($this->_Column * ($this->_ColWidth + $this->_Gutter)) + $this->_Margin_Left; $_PosY = $this->GetY(); $this->SetXY($_PosX, $_PosY); // $this->Cell($this->_ColWidth, 5, $sLetter, 1, 1, "C", 1) ; @@ -216,7 +216,7 @@ public function Add_Header($sLetter) $this->SetTextColor(0); $this->SetFont($this->_Font, '', $this->_Char_Size); // $this->SetY($this->GetY() + 5); - $this->SetY($this->GetY() + $this->_LS); + $this->SetY($this->GetY() + $this->_LS); } // This prints the family name in BOLD @@ -224,13 +224,13 @@ public function Print_Name($sName) { $this->SetFont($this->_Font, 'BU', $this->_Char_Size); // $_PosX = $this->_Column == 0 ? $this->_Margin_Left : $this->w - $this->_Margin_Left - $this->_ColWidth; - $_PosX = ($this->_Column * ($this->_ColWidth + $this->_Gutter)) + $this->_Margin_Left; + $_PosX = ($this->_Column * ($this->_ColWidth + $this->_Gutter)) + $this->_Margin_Left; $_PosY = $this->GetY(); $this->SetXY($_PosX, $_PosY); // $this->MultiCell($this->_ColWidth, 5, $sName); - $this->MultiCell($this->_ColWidth, $this->_LS, $sName); + $this->MultiCell($this->_ColWidth, $this->_LS, $sName); // $this->SetY($_PosY + $this->NbLines($this->_ColWidth, $sName) * 5); - $this->SetY($_PosY + $this->NbLines($this->_ColWidth, $sName) * $this->_LS); + $this->SetY($_PosY + $this->NbLines($this->_ColWidth, $sName) * $this->_LS); $this->SetFont($this->_Font, '', $this->_Char_Size); } @@ -266,10 +266,11 @@ public function sGetCustomString($rsCustomFields, $aRow) public function getBirthdayString($bDirBirthday, $per_BirthMonth, $per_BirthDay, $per_BirthYear, $per_Flags) { - if ($bDirBirthday && $per_BirthDay > 0 && $per_BirthMonth > 0) { - return MiscUtils::FormatBirthDate($per_BirthYear, $per_BirthMonth, $per_BirthDay, "/", $per_Flags); - } - return ''; + if ($bDirBirthday && $per_BirthDay > 0 && $per_BirthMonth > 0) { + return MiscUtils::FormatBirthDate($per_BirthYear, $per_BirthMonth, $per_BirthDay, '/', $per_Flags); + } + + return ''; } // This function formats the string for the family info @@ -289,9 +290,9 @@ public function sGetFamilyString($aRow) if ($bDirAddress) { // if (strlen($fam_Address1)) { $sFamilyStr .= $fam_Address1 . "\n"; } // if (strlen($fam_Address2)) { $sFamilyStr .= $fam_Address2 . "\n"; } - if (strlen($fam_Address1)) { - $sFamilyStr .= $fam_Address1; - } + if (strlen($fam_Address1)) { + $sFamilyStr .= $fam_Address1; + } if (strlen($fam_Address2)) { $sFamilyStr .= ' '.$fam_Address2; } @@ -314,7 +315,7 @@ public function sGetFamilyString($aRow) $sFamilyStr .= ' '.gettext('Email').': '.$fam_Email."\n"; } if ($bDirWedding && ($fam_WeddingDate > 0)) { - $sFamilyStr .= ' '.gettext('Wedding').': '.date(SystemConfig::getValue("sDateFormatShort"), strtotime($fam_WeddingDate))."\n"; + $sFamilyStr .= ' '.gettext('Wedding').': '.date(SystemConfig::getValue('sDateFormatShort'), strtotime($fam_WeddingDate))."\n"; } return $sFamilyStr; @@ -370,7 +371,7 @@ public function sGetHeadString($rsCustomFields, $aHead) $iTempLen = strlen($sHeadStr); - $sHeadStr .= " " . $this->getBirthdayString($bDirBirthday, $per_BirthMonth, $per_BirthDay, $per_BirthYear, $per_Flags) . "\n"; + $sHeadStr .= ' '.$this->getBirthdayString($bDirBirthday, $per_BirthMonth, $per_BirthDay, $per_BirthYear, $per_Flags)."\n"; $sCountry = SelectWhichInfo($per_Country, $fam_Country, false); @@ -427,7 +428,7 @@ public function sGetMemberString($aRow) $sMemberStr .= ' '.$per_Suffix; } - $sMemberStr .= " " . $this->getBirthdayString($bDirBirthday, $per_BirthMonth, $per_BirthDay, $per_BirthYear, $per_Flags) . "\n"; + $sMemberStr .= ' '.$this->getBirthdayString($bDirBirthday, $per_BirthMonth, $per_BirthDay, $per_BirthYear, $per_Flags)."\n"; $sCountry = SelectWhichInfo($per_Country, $fam_Country, false); @@ -457,17 +458,17 @@ public function sGetMemberString($aRow) public function Add_Record($sName, $text, $numlines, $fid, $pid) { $dirimg = ''; - if(!is_null($fid)){ - $family = FamilyQuery::create()->findOneById($fid); - if($family && !($family->getPhoto()->isInitials()) && file_exists($family->getPhoto()->getPhotoURI())) { - $dirimg = $family->getPhoto()->getPhotoURI(); - } - } - if(!is_null($pid)){ - $person = PersonQuery::create()->findOneById($pid); - if ($person && !($person->getPhoto()->isInitials()) && file_exists($person->getPhoto()->getPhotoURI())) { - $dirimg = $person->getPhoto()->getPhotoURI(); - } + if (!is_null($fid)) { + $family = FamilyQuery::create()->findOneById($fid); + if ($family && !$family->getPhoto()->isInitials() && file_exists($family->getPhoto()->getPhotoURI())) { + $dirimg = $family->getPhoto()->getPhotoURI(); + } + } + if (!is_null($pid)) { + $person = PersonQuery::create()->findOneById($pid); + if ($person && !$person->getPhoto()->isInitials() && file_exists($person->getPhoto()->getPhotoURI())) { + $dirimg = $person->getPhoto()->getPhotoURI(); + } } $this->Check_Lines($numlines, $dirimg); diff --git a/src/ChurchCRM/Reports/PDF_GroupDirectory.php b/src/ChurchCRM/Reports/PDF_GroupDirectory.php index 885ec11a64..32135933ef 100644 --- a/src/ChurchCRM/Reports/PDF_GroupDirectory.php +++ b/src/ChurchCRM/Reports/PDF_GroupDirectory.php @@ -41,7 +41,7 @@ public function Footer() //Select Arial italic 8 $this->SetFont($this->_Font, 'I', 8); //Print centered page number - $this->Cell(0, 10, 'Page '.($this->PageNo()), 0, 0, 'C'); + $this->Cell(0, 10, 'Page '.$this->PageNo(), 0, 0, 'C'); } // Sets the character size @@ -94,20 +94,20 @@ public function Check_Lines($numlines) // This function prints out the heading when a letter // changes. -/* function Add_Header($sLetter) - { - $this->Check_Lines(2); - $this->SetTextColor(255); - $this->SetFont($this->_Font,'B',12); - $_PosX = $this->_Margin_Left+($this->_Column*108); - $_PosY = $this->_Margin_Top+($this->_CurLine*5); - $this->SetXY($_PosX, $_PosY); - $this->Cell(80, 5, $sLetter, 1, 1, "C", 1) ; - $this->SetTextColor(0); - $this->SetFont($this->_Font,'',$this->_Char_Size); - $this->_CurLine+=2; - } -*/ + /* function Add_Header($sLetter) + { + $this->Check_Lines(2); + $this->SetTextColor(255); + $this->SetFont($this->_Font,'B',12); + $_PosX = $this->_Margin_Left+($this->_Column*108); + $_PosY = $this->_Margin_Top+($this->_CurLine*5); + $this->SetXY($_PosX, $_PosY); + $this->Cell(80, 5, $sLetter, 1, 1, "C", 1) ; + $this->SetTextColor(0); + $this->SetFont($this->_Font,'',$this->_Char_Size); + $this->_CurLine+=2; + } + */ // This prints the name in BOLD public function Print_Name($sName) diff --git a/src/ChurchCRM/SQLUtils.php b/src/ChurchCRM/SQLUtils.php index 199a6aa3b0..1f1308bc8a 100644 --- a/src/ChurchCRM/SQLUtils.php +++ b/src/ChurchCRM/SQLUtils.php @@ -1,154 +1,153 @@ 0) { - self::query($row, $mysqli); - } - - fclose($fileHandle); - } - /** - * Remove comments from sql. - * - * @param string sql - * @param bool is multicomment line - * - * @return string - */ - private static function clearSQL($sql, &$isMultiComment) - { - if ($isMultiComment) { - if (preg_match('#\*/#sUi', $sql)) { - $sql = preg_replace('#^.*\*/\s*#sUi', '', $sql); - $isMultiComment = false; + // 4. separate sql queries by delimiter + $offset = 0; + while (strpos($row, $delimiter, $offset) !== false) { + $delimiterOffset = strpos($row, $delimiter, $offset); + if (self::isQuoted($delimiterOffset, $row)) { + $offset = $delimiterOffset + strlen($delimiter); } else { + $sql = trim($sql.' '.trim(mb_substr($row, 0, $delimiterOffset))); + self::query($sql, $mysqli); + $row = mb_substr($row, $delimiterOffset + strlen($delimiter)); + $offset = 0; $sql = ''; } - if (trim($sql) == '') { - return $sql; - } } + $sql = trim($sql.' '.$row); + } + if (strlen($sql) > 0) { + self::query($row, $mysqli); + } - $offset = 0; - while (preg_match('{--\s|#|/\*[^!]}sUi', $sql, $matched, PREG_OFFSET_CAPTURE, $offset)) { - list($comment, $foundOn) = $matched[0]; - if (self::isQuoted($foundOn, $sql)) { - $offset = $foundOn + strlen($comment); - } else { - if (mb_substr($comment, 0, 2) == '/*') { - $closedOn = strpos($sql, '*/', $foundOn); - if ($closedOn !== false) { - $sql = mb_substr($sql, 0, $foundOn).mb_substr($sql, $closedOn + 2); - } else { - $sql = mb_substr($sql, 0, $foundOn); - $isMultiComment = true; - } + fclose($fileHandle); + } + + /** + * Remove comments from sql. + * + * @param string sql + * @param bool is multicomment line + * + * @return string + */ + private static function clearSQL($sql, &$isMultiComment) + { + if ($isMultiComment) { + if (preg_match('#\*/#sUi', $sql)) { + $sql = preg_replace('#^.*\*/\s*#sUi', '', $sql); + $isMultiComment = false; + } else { + $sql = ''; + } + if (trim($sql) == '') { + return $sql; + } + } + + $offset = 0; + while (preg_match('{--\s|#|/\*[^!]}sUi', $sql, $matched, PREG_OFFSET_CAPTURE, $offset)) { + list($comment, $foundOn) = $matched[0]; + if (self::isQuoted($foundOn, $sql)) { + $offset = $foundOn + strlen($comment); + } else { + if (mb_substr($comment, 0, 2) == '/*') { + $closedOn = strpos($sql, '*/', $foundOn); + if ($closedOn !== false) { + $sql = mb_substr($sql, 0, $foundOn).mb_substr($sql, $closedOn + 2); } else { $sql = mb_substr($sql, 0, $foundOn); - break; + $isMultiComment = true; } + } else { + $sql = mb_substr($sql, 0, $foundOn); + break; } } - - return $sql; } - /** - * Check if "offset" position is quoted. - * - * @param int $offset - * @param string $text - * - * @return bool - */ - private static function isQuoted($offset, $text) - { - if ($offset > strlen($text)) { - $offset = strlen($text); - } - - $isQuoted = false; - for ($i = 0; $i < $offset; $i++) { - if ($text[$i] == "'") { - $isQuoted = !$isQuoted; - } - if ($text[$i] == '\\' && $isQuoted) { - $i++; - } - } + return $sql; + } - return $isQuoted; + /** + * Check if "offset" position is quoted. + * + * @param int $offset + * @param string $text + * + * @return bool + */ + private static function isQuoted($offset, $text) + { + if ($offset > strlen($text)) { + $offset = strlen($text); } - private static function query($sql, $mysqli) - { - if (preg_match("/DEFINER\s*=.*@.*/", $sql)) { - return; + $isQuoted = false; + for ($i = 0; $i < $offset; $i++) { + if ($text[$i] == "'") { + $isQuoted = !$isQuoted; } - if (!$query = $mysqli->query($sql)) { - throw new \Exception("Cannot execute request to the database {$sql}: ".$mysqli->error); + if ($text[$i] == '\\' && $isQuoted) { + $i++; } } + + return $isQuoted; + } + + private static function query($sql, $mysqli) + { + if (preg_match("/DEFINER\s*=.*@.*/", $sql)) { + return; + } + if (!$query = $mysqli->query($sql)) { + throw new \Exception("Cannot execute request to the database {$sql}: ".$mysqli->error); + } } } diff --git a/src/ChurchCRM/Search/AddressSearchResultProvider.php b/src/ChurchCRM/Search/AddressSearchResultProvider.php index 00c8c71801..1bff751cc5 100644 --- a/src/ChurchCRM/Search/AddressSearchResultProvider.php +++ b/src/ChurchCRM/Search/AddressSearchResultProvider.php @@ -2,45 +2,47 @@ namespace ChurchCRM\Search; +use ChurchCRM\dto\SystemConfig; use ChurchCRM\FamilyQuery; -use Propel\Runtime\ActiveQuery\Criteria; use ChurchCRM\Utils\LoggerUtils; -use ChurchCRM\Search\SearchResult; -use ChurchCRM\Search\BaseSearchResultProvider; -use ChurchCRM\dto\SystemConfig; +use Propel\Runtime\ActiveQuery\Criteria; -class AddressSearchResultProvider extends BaseSearchResultProvider { +class AddressSearchResultProvider extends BaseSearchResultProvider +{ public function __construct() { - $this->pluralNoun = "Address"; + $this->pluralNoun = 'Address'; parent::__construct(); } - public function getSearchResults(string $SearchQuery) { - if (SystemConfig::getBooleanValue("bSearchIncludeAddresses")) { - $this->addSearchResults($this->getPersonSearchResultsByPartialAddress($SearchQuery)); + public function getSearchResults(string $SearchQuery) + { + if (SystemConfig::getBooleanValue('bSearchIncludeAddresses')) { + $this->addSearchResults($this->getPersonSearchResultsByPartialAddress($SearchQuery)); } + return $this->formatSearchGroup(); } - private function getPersonSearchResultsByPartialAddress(string $SearchQuery) { - $searchResults = array(); + private function getPersonSearchResultsByPartialAddress(string $SearchQuery) + { + $searchResults = []; $id = 0; - try { - $searchLikeString = '%' . $SearchQuery . '%'; + try { + $searchLikeString = '%'.$SearchQuery.'%'; $addresses = FamilyQuery::create()-> filterByCity($searchLikeString, Criteria::LIKE)-> _or()->filterByAddress1($searchLikeString, Criteria::LIKE)-> _or()->filterByAddress2($searchLikeString, Criteria::LIKE)-> _or()->filterByZip($searchLikeString, Criteria::LIKE)-> _or()->filterByState($searchLikeString, Criteria::LIKE)-> - limit(SystemConfig::getValue("bSearchIncludeAddressesMax"))->find(); + limit(SystemConfig::getValue('bSearchIncludeAddressesMax'))->find(); if (!empty($addresses)) { $id++; foreach ($addresses as $address) { - array_push($searchResults, new SearchResult("person-address-".$id, $address->getFamilyString(SystemConfig::getBooleanValue("bSearchIncludeFamilyHOH")),$address->getViewURI())); + array_push($searchResults, new SearchResult('person-address-'.$id, $address->getFamilyString(SystemConfig::getBooleanValue('bSearchIncludeFamilyHOH')), $address->getViewURI())); } } } catch (Exception $e) { @@ -49,9 +51,4 @@ private function getPersonSearchResultsByPartialAddress(string $SearchQuery) { return $searchResults; } - - - - - } diff --git a/src/ChurchCRM/Search/BaseSearchResultProvider.php b/src/ChurchCRM/Search/BaseSearchResultProvider.php index 4f425159c3..eebba41fa0 100644 --- a/src/ChurchCRM/Search/BaseSearchResultProvider.php +++ b/src/ChurchCRM/Search/BaseSearchResultProvider.php @@ -2,25 +2,31 @@ namespace ChurchCRM\Search; -use ChurchCRM\Search\SearchResult; - -abstract class BaseSearchResultProvider { +abstract class BaseSearchResultProvider +{ /* @var string */ protected $pluralNoun; /* @var ChurchCRM\Search\SearchResult[] */ protected $searchResults; - public abstract function getSearchResults(string $SearchQuery); - protected function formatSearchGroup() { + + abstract public function getSearchResults(string $SearchQuery); + + protected function formatSearchGroup() + { if (!empty($this->searchResults)) { - return new SearchResultGroup(gettext($this->pluralNoun)." (". count($this->searchResults).")", $this->searchResults); + return new SearchResultGroup(gettext($this->pluralNoun).' ('.count($this->searchResults).')', $this->searchResults); } + return []; } - protected function addSearchResults(array $results) { + + protected function addSearchResults(array $results) + { $this->searchResults = array_merge($this->searchResults, $results); } + protected function __construct() { - $this->searchResults = array(); + $this->searchResults = []; } -} \ No newline at end of file +} diff --git a/src/ChurchCRM/Search/CalendarEventSearchResultProvider.php b/src/ChurchCRM/Search/CalendarEventSearchResultProvider.php index be911c2ea8..764d668ada 100644 --- a/src/ChurchCRM/Search/CalendarEventSearchResultProvider.php +++ b/src/ChurchCRM/Search/CalendarEventSearchResultProvider.php @@ -3,29 +3,32 @@ namespace ChurchCRM\Search; use ChurchCRM\Base\EventQuery; -use Propel\Runtime\ActiveQuery\Criteria; -use ChurchCRM\Utils\LoggerUtils; -use ChurchCRM\Search\SearchResult; -use ChurchCRM\Search\SearchResultGroup; use ChurchCRM\dto\SystemConfig; +use ChurchCRM\Utils\LoggerUtils; +use Propel\Runtime\ActiveQuery\Criteria; -class CalendarEventSearchResultProvider extends BaseSearchResultProvider { +class CalendarEventSearchResultProvider extends BaseSearchResultProvider +{ public function __construct() { - $this->pluralNoun = "Calendar Events"; + $this->pluralNoun = 'Calendar Events'; parent::__construct(); } - public function getSearchResults(string $SearchQuery) { - if (SystemConfig::getBooleanValue("bSearchIncludeCalendarEvents")) { + public function getSearchResults(string $SearchQuery) + { + if (SystemConfig::getBooleanValue('bSearchIncludeCalendarEvents')) { $this->addSearchResults($this->getCalendarEventSearchResultsByPartialName($SearchQuery)); } + return $this->formatSearchGroup(); } - private function getCalendarEventSearchResultsByPartialName(string $SearchQuery) { - $searchResults = array(); + private function getCalendarEventSearchResultsByPartialName(string $SearchQuery) + { + $searchResults = []; $id = 0; + try { $events = EventQuery::create() ->filterByTitle("%$SearchQuery%", Criteria::LIKE) @@ -33,17 +36,18 @@ private function getCalendarEventSearchResultsByPartialName(string $SearchQuery) ->filterByText("%$SearchQuery%", Criteria::LIKE) ->_or() ->filterByDesc("%$SearchQuery%", Criteria::LIKE) - ->limit(SystemConfig::getValue("bSearchIncludeGroupsMax")) + ->limit(SystemConfig::getValue('bSearchIncludeGroupsMax')) ->find(); if (!empty($events)) { $id++; foreach ($events as $event) { - array_push($searchResults, new SearchResult("event-name-".$id, $event->getTitle(),$event->getViewURI())); + array_push($searchResults, new SearchResult('event-name-'.$id, $event->getTitle(), $event->getViewURI())); } } } catch (Exception $e) { LoggerUtils::getAppLogger()->warning($e->getMessage()); } + return $searchResults; } } diff --git a/src/ChurchCRM/Search/FamilySearchResultProvider.php b/src/ChurchCRM/Search/FamilySearchResultProvider.php index 7eb085df8f..5b382f5511 100644 --- a/src/ChurchCRM/Search/FamilySearchResultProvider.php +++ b/src/ChurchCRM/Search/FamilySearchResultProvider.php @@ -2,36 +2,38 @@ namespace ChurchCRM\Search; -use ChurchCRM\FamilyQuery; +use ChurchCRM\dto\SystemConfig; use ChurchCRM\FamilyCustomMasterQuery; -use Propel\Runtime\ActiveQuery\Criteria; +use ChurchCRM\FamilyQuery; use ChurchCRM\Utils\LoggerUtils; -use ChurchCRM\Search\SearchResult; -use ChurchCRM\Search\SearchResultGroup; -use ChurchCRM\dto\SystemConfig; +use Propel\Runtime\ActiveQuery\Criteria; -class FamilySearchResultProvider extends BaseSearchResultProvider { +class FamilySearchResultProvider extends BaseSearchResultProvider +{ public function __construct() { - $this->pluralNoun = "Families"; + $this->pluralNoun = 'Families'; parent::__construct(); } - public function getSearchResults(string $SearchQuery) { - $searchResults = array(); - if (SystemConfig::getBooleanValue("bSearchIncludeFamilies")) { + public function getSearchResults(string $SearchQuery) + { + $searchResults = []; + if (SystemConfig::getBooleanValue('bSearchIncludeFamilies')) { $this->addSearchResults($this->getFamilySearchResultsByPartialName($SearchQuery)); } - if (SystemConfig::getBooleanValue("bSearchIncludeFamilyCustomProperties")) { + if (SystemConfig::getBooleanValue('bSearchIncludeFamilyCustomProperties')) { $this->addSearchResults($this->getFamilySearchResultsByCustomProperties($SearchQuery)); } return $this->formatSearchGroup(); } - private function getFamilySearchResultsByPartialName(string $SearchQuery) { - $searchResults = array(); + private function getFamilySearchResultsByPartialName(string $SearchQuery) + { + $searchResults = []; $id = 0; + try { $families = FamilyQuery::create()-> filterByName("%$SearchQuery%", Criteria::LIKE)-> @@ -39,14 +41,12 @@ private function getFamilySearchResultsByPartialName(string $SearchQuery) { _or()->filterByEmail("%$SearchQuery%", Criteria::LIKE)-> _or()->filterByCellPhone("%$SearchQuery%", Criteria::LIKE)-> _or()->filterByWorkPhone("%$SearchQuery%", Criteria::LIKE)-> - limit(SystemConfig::getValue("bSearchIncludeFamiliesMax"))->find(); - - + limit(SystemConfig::getValue('bSearchIncludeFamiliesMax'))->find(); if (!empty($families)) { $id++; foreach ($families as $family) { - array_push($searchResults, new SearchResult("family-name-".$id, $family->getFamilyString(SystemConfig::getBooleanValue("bSearchIncludeFamilyHOH")),$family->getViewURI())); + array_push($searchResults, new SearchResult('family-name-'.$id, $family->getFamilyString(SystemConfig::getBooleanValue('bSearchIncludeFamilyHOH')), $family->getViewURI())); } } @@ -55,28 +55,31 @@ private function getFamilySearchResultsByPartialName(string $SearchQuery) { LoggerUtils::getAppLogger()->warning($e->getMessage()); } } - private function getFamilySearchResultsByCustomProperties(string $SearchQuery) { - $searchResults = array(); + + private function getFamilySearchResultsByCustomProperties(string $SearchQuery) + { + $searchResults = []; $id = 0; + try { $customFields = FamilyCustomMasterQuery::create()->find(); $familyQuery = FamilyQuery::create() ->joinFamilyCustom() ->useFamilyCustomQuery(); - foreach($customFields as $customField) - { + foreach ($customFields as $customField) { // search the `family_custom` table for the supplied query using all available `c_` fields obtained from `family_custom_master` - $familyQuery->where($customField->getField()." LIKE ?","%$SearchQuery%",\PDO::PARAM_STR ); + $familyQuery->where($customField->getField().' LIKE ?', "%$SearchQuery%", \PDO::PARAM_STR); $familyQuery->_or(); } $families = $familyQuery->endUse()->find(); foreach ($families as $family) { $id++; - array_push($searchResults, new SearchResult("family-custom-prop-".$id, $family->getFamilyString(SystemConfig::getBooleanValue("bSearchIncludeFamilyHOH")),$family->getViewURI())); + array_push($searchResults, new SearchResult('family-custom-prop-'.$id, $family->getFamilyString(SystemConfig::getBooleanValue('bSearchIncludeFamilyHOH')), $family->getViewURI())); } } catch (Exception $e) { LoggerUtils::getAppLogger()->warning($e->getMessage()); } + return $searchResults; } } diff --git a/src/ChurchCRM/Search/FinanceDepositSearchResultProvider.php b/src/ChurchCRM/Search/FinanceDepositSearchResultProvider.php index 5943ac1900..83a99f0faf 100644 --- a/src/ChurchCRM/Search/FinanceDepositSearchResultProvider.php +++ b/src/ChurchCRM/Search/FinanceDepositSearchResultProvider.php @@ -2,52 +2,55 @@ namespace ChurchCRM\Search; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\DepositQuery; -use Propel\Runtime\ActiveQuery\Criteria; -use ChurchCRM\Utils\LoggerUtils; -use ChurchCRM\Search\SearchResult; -use ChurchCRM\Search\SearchResultGroup; use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; -use ChurchCRM\Authentication\AuthenticationManager; +use ChurchCRM\Utils\LoggerUtils; +use Propel\Runtime\ActiveQuery\Criteria; -class FinanceDepositSearchResultProvider extends BaseSearchResultProvider { +class FinanceDepositSearchResultProvider extends BaseSearchResultProvider +{ public function __construct() { - $this->pluralNoun = "Deposits"; + $this->pluralNoun = 'Deposits'; parent::__construct(); } - public function getSearchResults(string $SearchQuery) { + public function getSearchResults(string $SearchQuery) + { if (AuthenticationManager::GetCurrentUser()->isFinanceEnabled()) { - if (SystemConfig::getBooleanValue("bSearchIncludeDeposits")) { + if (SystemConfig::getBooleanValue('bSearchIncludeDeposits')) { $this->addSearchResults($this->getDepositSearchResults($SearchQuery)); } - } + return $this->formatSearchGroup(); } - private function getDepositSearchResults(string $SearchQuery) { - $searchResults = array(); + private function getDepositSearchResults(string $SearchQuery) + { + $searchResults = []; $id = 0; + try { $Deposits = DepositQuery::create()->filterByComment("%$SearchQuery%", Criteria::LIKE) ->_or() ->filterById($SearchQuery) ->withColumn('CONCAT("#",Deposit.Id," ",Deposit.Comment)', 'displayName') - ->withColumn('CONCAT("' . SystemURLs::getRootPath() . '/DepositSlipEditor.php?DepositSlipID=",Deposit.Id)', 'uri') - ->limit(SystemConfig::getValue("bSearchIncludeDepositsMax"))->find(); + ->withColumn('CONCAT("'.SystemURLs::getRootPath().'/DepositSlipEditor.php?DepositSlipID=",Deposit.Id)', 'uri') + ->limit(SystemConfig::getValue('bSearchIncludeDepositsMax'))->find(); if (!empty($Deposits)) { $id++; foreach ($Deposits->toArray() as $Deposit) { - array_push($searchResults, new SearchResult("finance-deposit-".$id, $Deposit['displayName'], $Deposit['uri'])); + array_push($searchResults, new SearchResult('finance-deposit-'.$id, $Deposit['displayName'], $Deposit['uri'])); } } } catch (Exception $e) { LoggerUtils::getAppLogger()->warning($e->getMessage()); } + return $searchResults; } } diff --git a/src/ChurchCRM/Search/FinancePaymentSearchResultProvider.php b/src/ChurchCRM/Search/FinancePaymentSearchResultProvider.php index 3b11273ff5..2643003904 100644 --- a/src/ChurchCRM/Search/FinancePaymentSearchResultProvider.php +++ b/src/ChurchCRM/Search/FinancePaymentSearchResultProvider.php @@ -2,48 +2,50 @@ namespace ChurchCRM\Search; -use ChurchCRM\Utils\LoggerUtils; -use ChurchCRM\Search\SearchResult; -use ChurchCRM\Search\SearchResultGroup; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\dto\SystemConfig; +use ChurchCRM\dto\SystemURLs; use ChurchCRM\PledgeQuery; +use ChurchCRM\Utils\LoggerUtils; use Propel\Runtime\ActiveQuery\Criteria; -use ChurchCRM\dto\SystemURLs; -use ChurchCRM\Authentication\AuthenticationManager; -class FinancePaymentSearchResultProvider extends BaseSearchResultProvider { +class FinancePaymentSearchResultProvider extends BaseSearchResultProvider +{ public function __construct() { - $this->pluralNoun = "Payments"; + $this->pluralNoun = 'Payments'; parent::__construct(); } - public function getSearchResults(string $SearchQuery) { + public function getSearchResults(string $SearchQuery) + { if (AuthenticationManager::GetCurrentUser()->isFinanceEnabled()) { - if (SystemConfig::getBooleanValue("bSearchIncludePayments")) { + if (SystemConfig::getBooleanValue('bSearchIncludePayments')) { $this->addSearchResults($this->getPaymentSearchResults($SearchQuery)); - if (count(explode("-",$SearchQuery)) == 2 ) { - $range = explode("-",$SearchQuery); - $this->addSearchResults($this->getPaymentsWithValuesInRange((int)$range[0],(int)$range[1])); + if (count(explode('-', $SearchQuery)) == 2) { + $range = explode('-', $SearchQuery); + $this->addSearchResults($this->getPaymentsWithValuesInRange((int) $range[0], (int) $range[1])); } } } + return $this->formatSearchGroup(); } - private function getPaymentsWithValuesInRange(int $min, int $max) { - $searchResults = array(); + private function getPaymentsWithValuesInRange(int $min, int $max) + { + $searchResults = []; $id = 0; - if ($max == 0) - { + if ($max == 0) { $max = PHP_INT_MAX; } + try { $Payments = PledgeQuery::create() ->withColumn('SUM(Pledge.Amount)', 'GroupAmount') ->withColumn('CONCAT("#",Pledge.Id)', 'displayName') - ->withColumn('CONCAT("' . SystemURLs::getRootPath() . '/DepositSlipEditor.php?DepositSlipID=",Pledge.DepId)', 'uri') - #->limit(SystemConfig::getValue("bSearchIncludePaymentsMax")) // this can't be limited here due to how Propel ORM doesn't handle HAVING clause nicely, so we do it in PHP + ->withColumn('CONCAT("'.SystemURLs::getRootPath().'/DepositSlipEditor.php?DepositSlipID=",Pledge.DepId)', 'uri') + //->limit(SystemConfig::getValue("bSearchIncludePaymentsMax")) // this can't be limited here due to how Propel ORM doesn't handle HAVING clause nicely, so we do it in PHP ->groupByGroupKey() ->find(); @@ -52,40 +54,42 @@ private function getPaymentsWithValuesInRange(int $min, int $max) { foreach ($Payments as $Payment) { // I can't seem to get the SQL HAVING clause to work through Propel ORM to use // both MIN and MAX value. Just filter it in PHP - if ($Payment->getVirtualColumn("GroupAmount") >= $min && $Payment->getVirtualColumn("GroupAmount") <= $max){ - array_push($searchResults, new SearchResult("finance-payment-".$id, "\$".$Payment->getVirtualColumn("GroupAmount")." Payment on Deposit " . $Payment->getDepid(), $Payment->getVirtualColumn('uri'))); + if ($Payment->getVirtualColumn('GroupAmount') >= $min && $Payment->getVirtualColumn('GroupAmount') <= $max) { + array_push($searchResults, new SearchResult('finance-payment-'.$id, '$'.$Payment->getVirtualColumn('GroupAmount').' Payment on Deposit '.$Payment->getDepid(), $Payment->getVirtualColumn('uri'))); } } } - } catch (Exception $e) { LoggerUtils::getAppLogger()->warning($e->getMessage()); } - return array_slice($searchResults,0,SystemConfig::getValue("bSearchIncludePaymentsMax")); // since Propel ORM won't handle limit() nicely, do it in PHP + + return array_slice($searchResults, 0, SystemConfig::getValue('bSearchIncludePaymentsMax')); // since Propel ORM won't handle limit() nicely, do it in PHP } - private function getPaymentSearchResults(string $SearchQuery) { - $searchResults = array(); + private function getPaymentSearchResults(string $SearchQuery) + { + $searchResults = []; $id = 0; + try { $Payments = PledgeQuery::create() ->filterByCheckNo("$SearchQuery", Criteria::EQUAL) ->withColumn('CONCAT("#",Pledge.Id)', 'displayName') - ->withColumn('CONCAT("' . SystemURLs::getRootPath() . '/DepositSlipEditor.php?DepositSlipID=",Pledge.DepId)', 'uri') - ->limit(SystemConfig::getValue("bSearchIncludePaymentsMax")) + ->withColumn('CONCAT("'.SystemURLs::getRootPath().'/DepositSlipEditor.php?DepositSlipID=",Pledge.DepId)', 'uri') + ->limit(SystemConfig::getValue('bSearchIncludePaymentsMax')) ->groupByGroupKey() ->find(); if (!empty($Payments)) { $id++; foreach ($Payments as $Payment) { - array_push($searchResults, new SearchResult("finance-payment-".$id, "Check ".$Payment->getCheckNo()." on Deposit " . $Payment->getDepId(), $Payment->getVirtualColumn('uri'))); + array_push($searchResults, new SearchResult('finance-payment-'.$id, 'Check '.$Payment->getCheckNo().' on Deposit '.$Payment->getDepId(), $Payment->getVirtualColumn('uri'))); } } - } catch (Exception $e) { LoggerUtils::getAppLogger()->warning($e->getMessage()); } + return $searchResults; } } diff --git a/src/ChurchCRM/Search/GroupSearchResultProvider.php b/src/ChurchCRM/Search/GroupSearchResultProvider.php index 5ca70c3473..138d61884f 100644 --- a/src/ChurchCRM/Search/GroupSearchResultProvider.php +++ b/src/ChurchCRM/Search/GroupSearchResultProvider.php @@ -2,45 +2,48 @@ namespace ChurchCRM\Search; +use ChurchCRM\dto\SystemConfig; use ChurchCRM\GroupQuery; - -use Propel\Runtime\ActiveQuery\Criteria; use ChurchCRM\Utils\LoggerUtils; -use ChurchCRM\Search\SearchResult; -use ChurchCRM\Search\SearchResultGroup; -use ChurchCRM\dto\SystemConfig; +use Propel\Runtime\ActiveQuery\Criteria; -class GroupSearchResultProvider extends BaseSearchResultProvider { +class GroupSearchResultProvider extends BaseSearchResultProvider +{ public function __construct() { - $this->pluralNoun = "Groups"; + $this->pluralNoun = 'Groups'; parent::__construct(); } - public function getSearchResults(string $SearchQuery) { - if (SystemConfig::getBooleanValue("bSearchIncludeGroups")) { + public function getSearchResults(string $SearchQuery) + { + if (SystemConfig::getBooleanValue('bSearchIncludeGroups')) { $this->addSearchResults($this->getPersonSearchResultsByPartialName($SearchQuery)); } + return $this->formatSearchGroup(); } - private function getPersonSearchResultsByPartialName(string $SearchQuery) { - $searchResults = array(); + private function getPersonSearchResultsByPartialName(string $SearchQuery) + { + $searchResults = []; $id = 0; + try { $groups = GroupQuery::create() ->filterByName("%$SearchQuery%", Criteria::LIKE) - ->limit(SystemConfig::getValue("bSearchIncludeGroupsMax")) + ->limit(SystemConfig::getValue('bSearchIncludeGroupsMax')) ->find(); if (!empty($groups)) { $id++; foreach ($groups as $group) { - array_push($searchResults, new SearchResult("group-name-".$id, $group->getName(),$group->getViewURI())); + array_push($searchResults, new SearchResult('group-name-'.$id, $group->getName(), $group->getViewURI())); } } } catch (Exception $e) { LoggerUtils::getAppLogger()->warning($e->getMessage()); } + return $searchResults; } } diff --git a/src/ChurchCRM/Search/PersonSearchResultProvider.php b/src/ChurchCRM/Search/PersonSearchResultProvider.php index b8726af064..57a0f77437 100644 --- a/src/ChurchCRM/Search/PersonSearchResultProvider.php +++ b/src/ChurchCRM/Search/PersonSearchResultProvider.php @@ -2,33 +2,35 @@ namespace ChurchCRM\Search; +use ChurchCRM\dto\SystemConfig; use ChurchCRM\PersonQuery; -use ChurchCRM\Person; -use Propel\Runtime\ActiveQuery\Criteria; use ChurchCRM\Utils\LoggerUtils; -use ChurchCRM\Search\SearchResult; -use ChurchCRM\Search\SearchResultGroup; -use ChurchCRM\dto\SystemConfig; +use Propel\Runtime\ActiveQuery\Criteria; -class PersonSearchResultProvider extends BaseSearchResultProvider { +class PersonSearchResultProvider extends BaseSearchResultProvider +{ public function __construct() { - $this->pluralNoun = "Persons"; + $this->pluralNoun = 'Persons'; parent::__construct(); } - public function getSearchResults(string $SearchQuery) { - if (SystemConfig::getBooleanValue("bSearchIncludePersons")) { + public function getSearchResults(string $SearchQuery) + { + if (SystemConfig::getBooleanValue('bSearchIncludePersons')) { $this->addSearchResults($this->getPersonSearchResultsByPartialName($SearchQuery)); } + return $this->formatSearchGroup(); } - private function getPersonSearchResultsByPartialName(string $SearchQuery) { - $searchResults = array(); + private function getPersonSearchResultsByPartialName(string $SearchQuery) + { + $searchResults = []; $id = 0; + try { - $searchLikeString = '%' . $SearchQuery . '%'; + $searchLikeString = '%'.$SearchQuery.'%'; $people = PersonQuery::create()-> filterByFirstName($searchLikeString, Criteria::LIKE)-> _or()->filterByLastName($searchLikeString, Criteria::LIKE)-> @@ -37,17 +39,18 @@ private function getPersonSearchResultsByPartialName(string $SearchQuery) { _or()->filterByHomePhone($searchLikeString, Criteria::LIKE)-> _or()->filterByCellPhone($searchLikeString, Criteria::LIKE)-> _or()->filterByWorkPhone($searchLikeString, Criteria::LIKE)-> - limit(SystemConfig::getValue("bSearchIncludePersonsMax"))->find(); + limit(SystemConfig::getValue('bSearchIncludePersonsMax'))->find(); if (!empty($people)) { $id++; foreach ($people as $person) { - array_push($searchResults, new SearchResult("person-name-".$id, $person->getFullName(),$person->getViewURI())); + array_push($searchResults, new SearchResult('person-name-'.$id, $person->getFullName(), $person->getViewURI())); } } } catch (Exception $e) { LoggerUtils::getAppLogger()->warning($e->getMessage()); } + return $searchResults; } } diff --git a/src/ChurchCRM/Search/SearchResult.php b/src/ChurchCRM/Search/SearchResult.php index c4073f9da2..7fae57d540 100644 --- a/src/ChurchCRM/Search/SearchResult.php +++ b/src/ChurchCRM/Search/SearchResult.php @@ -2,13 +2,16 @@ namespace ChurchCRM\Search; -class SearchResult { +class SearchResult +{ public $id; public $text; public $uri; - public function __construct(string $id, string $text, string $uri) { + + public function __construct(string $id, string $text, string $uri) + { $this->id = $id; $this->text = $text; $this->uri = $uri; } -} \ No newline at end of file +} diff --git a/src/ChurchCRM/Search/SearchResultGroup.php b/src/ChurchCRM/Search/SearchResultGroup.php index 7ba9160945..b4de052eae 100644 --- a/src/ChurchCRM/Search/SearchResultGroup.php +++ b/src/ChurchCRM/Search/SearchResultGroup.php @@ -2,19 +2,22 @@ namespace ChurchCRM\Search; -class SearchResultGroup implements \JsonSerializable { +class SearchResultGroup implements \JsonSerializable +{ public $groupName; public $results; - public function __construct(string $groupName, array $results) { + public function __construct(string $groupName, array $results) + { $this->groupName = $groupName; $this->results = $results; } - public function jsonSerialize() { + public function jsonSerialize() + { return @[ - "text" => $this->groupName, - "children" => $this->results + 'text' => $this->groupName, + 'children' => $this->results, ]; } -} \ No newline at end of file +} diff --git a/src/ChurchCRM/Service/AppIntegrityService.php b/src/ChurchCRM/Service/AppIntegrityService.php index 7ba1dd1280..5129c1283b 100644 --- a/src/ChurchCRM/Service/AppIntegrityService.php +++ b/src/ChurchCRM/Service/AppIntegrityService.php @@ -2,222 +2,218 @@ namespace ChurchCRM\Service; -use ChurchCRM\dto\SystemURLs; use ChurchCRM\dto\Prerequisite; +use ChurchCRM\dto\SystemURLs; use ChurchCRM\Utils\LoggerUtils; class AppIntegrityService { - private static $IntegrityCheckDetails; + private static $IntegrityCheckDetails; - private static function getIntegrityCheckData() { - $integrityCheckFile = SystemURLs::getDocumentRoot().'/integrityCheck.json'; - if (is_null(AppIntegrityService::$IntegrityCheckDetails)) + private static function getIntegrityCheckData() { - LoggerUtils::getAppLogger()->debug('Integrity check results not cached; reloading from file'); - if (file_exists($integrityCheckFile)) { - LoggerUtils::getAppLogger()->info('Integrity check result file found at: ' . $integrityCheckFile); - AppIntegrityService::$IntegrityCheckDetails = json_decode(file_get_contents($integrityCheckFile)); - if (is_null(AppIntegrityService::$IntegrityCheckDetails)) - { - LoggerUtils::getAppLogger()->warning("Error decoding integrity check result file: " . $integrityCheckFile); - AppIntegrityService::$IntegrityCheckDetails->status = 'failure'; - AppIntegrityService::$IntegrityCheckDetails->message = gettext("Error decoding integrity check result file"); + $integrityCheckFile = SystemURLs::getDocumentRoot().'/integrityCheck.json'; + if (is_null(AppIntegrityService::$IntegrityCheckDetails)) { + LoggerUtils::getAppLogger()->debug('Integrity check results not cached; reloading from file'); + if (file_exists($integrityCheckFile)) { + LoggerUtils::getAppLogger()->info('Integrity check result file found at: '.$integrityCheckFile); + AppIntegrityService::$IntegrityCheckDetails = json_decode(file_get_contents($integrityCheckFile)); + if (is_null(AppIntegrityService::$IntegrityCheckDetails)) { + LoggerUtils::getAppLogger()->warning('Error decoding integrity check result file: '.$integrityCheckFile); + AppIntegrityService::$IntegrityCheckDetails->status = 'failure'; + AppIntegrityService::$IntegrityCheckDetails->message = gettext('Error decoding integrity check result file'); + } + } else { + LoggerUtils::getAppLogger()->debug('Integrity check result file not found at: '.$integrityCheckFile); + AppIntegrityService::$IntegrityCheckDetails = new \stdClass(); + AppIntegrityService::$IntegrityCheckDetails->status = 'failure'; + AppIntegrityService::$IntegrityCheckDetails->message = gettext('integrityCheck.json file missing'); + } + } else { + LoggerUtils::getAppLogger()->debug('Integrity check results already cached; not reloading from file'); } - } else { - LoggerUtils::getAppLogger()->debug('Integrity check result file not found at: ' . $integrityCheckFile); - AppIntegrityService::$IntegrityCheckDetails = new \StdClass; - AppIntegrityService::$IntegrityCheckDetails->status = 'failure'; - AppIntegrityService::$IntegrityCheckDetails->message = gettext("integrityCheck.json file missing"); - } - } - else { - LoggerUtils::getAppLogger()->debug('Integrity check results already cached; not reloading from file'); - } - return AppIntegrityService::$IntegrityCheckDetails; - - } + return AppIntegrityService::$IntegrityCheckDetails; + } - public static function getIntegrityCheckStatus () { - if (AppIntegrityService::getIntegrityCheckData()->status == "failure") + public static function getIntegrityCheckStatus() { - return gettext("Failed"); + if (AppIntegrityService::getIntegrityCheckData()->status == 'failure') { + return gettext('Failed'); + } else { + return gettext('Passed'); + } } - else { - return gettext("Passed"); + + public static function getIntegrityCheckMessage() + { + if (AppIntegrityService::getIntegrityCheckData()->status != 'failure') { + AppIntegrityService::$IntegrityCheckDetails->message = gettext('The previous integrity check passed. All system file hashes match the expected values.'); + } + + return AppIntegrityService::$IntegrityCheckDetails->message; } - } - public static function getIntegrityCheckMessage() { - if (AppIntegrityService::getIntegrityCheckData()->status != "failure") + public static function getFilesFailingIntegrityCheck() { - AppIntegrityService::$IntegrityCheckDetails->message = gettext('The previous integrity check passed. All system file hashes match the expected values.'); + if (isset(AppIntegrityService::getIntegrityCheckData()->files)) { + return AppIntegrityService::getIntegrityCheckData()->files; + } else { + return @[]; + } } - return AppIntegrityService::$IntegrityCheckDetails->message; + public static function verifyApplicationIntegrity() + { + $signatureFile = SystemURLs::getDocumentRoot().'/signatures.json'; + $signatureFailures = []; + if (file_exists($signatureFile)) { + LoggerUtils::getAppLogger()->info('Signature file found at: '.$signatureFile); + $signatureData = json_decode(file_get_contents($signatureFile)); + if (is_null($signatureData)) { + LoggerUtils::getAppLogger()->warning('Error decoding signature definition file: '.$signatureFile); + + return ['status' => 'failure', 'message' => gettext('Error decoding signature definition file')]; + } + if (sha1(json_encode($signatureData->files, JSON_UNESCAPED_SLASHES)) == $signatureData->sha1) { + foreach ($signatureData->files as $file) { + $currentFile = SystemURLs::getDocumentRoot().'/'.$file->filename; + if (file_exists($currentFile)) { + $actualHash = sha1_file($currentFile); + if ($actualHash != $file->sha1) { + LoggerUtils::getAppLogger()->warning('File hash mismatch: '.$file->filename.'. Expected: '.$file->sha1.'; Got: '.$actualHash); + array_push($signatureFailures, ['filename' => $file->filename, 'status' => 'Hash Mismatch', 'expectedhash' => $file->sha1, 'actualhash' => $actualHash]); + } + } else { + LoggerUtils::getAppLogger()->warning('File Missing: '.$file->filename); + array_push($signatureFailures, ['filename' => $file->filename, 'status' => 'File Missing']); + } + } + } else { + LoggerUtils::getAppLogger()->warning('Signature definition file signature failed validation'); + + return ['status' => 'failure', 'message' => gettext('Signature definition file signature failed validation')]; + } + } else { + LoggerUtils::getAppLogger()->warning('Signature definition file not found at: '.$signatureFile); - } + return ['status' => 'failure', 'message' => gettext('Signature definition File Missing')]; + } - public static function getFilesFailingIntegrityCheck() { - if (isset(AppIntegrityService::getIntegrityCheckData()->files)) { - return AppIntegrityService::getIntegrityCheckData()->files; + if (count($signatureFailures) > 0) { + return ['status' => 'failure', 'message' => gettext('One or more files failed signature validation'), 'files' => $signatureFailures]; + } else { + return ['status' => 'success']; + } } - else{ - return @[]; + + private static function testImagesWriteable() + { + return is_writable(SystemURLs::getDocumentRoot().'/Images/') && + is_writable(SystemURLs::getDocumentRoot().'/Images/Family') && + is_writable(SystemURLs::getDocumentRoot().'/Images/Person'); } - } - public static function verifyApplicationIntegrity() - { - $signatureFile = SystemURLs::getDocumentRoot() . '/signatures.json'; - $signatureFailures = []; - if (file_exists($signatureFile)) { - LoggerUtils::getAppLogger()->info('Signature file found at: ' . $signatureFile); - $signatureData = json_decode(file_get_contents($signatureFile)); - if (is_null($signatureData)){ - LoggerUtils::getAppLogger()->warning('Error decoding signature definition file: ' . $signatureFile); - return ['status' => 'failure', 'message' => gettext('Error decoding signature definition file')]; - } - if (sha1(json_encode($signatureData->files, JSON_UNESCAPED_SLASHES)) == $signatureData->sha1) { - foreach ($signatureData->files as $file) { - $currentFile = SystemURLs::getDocumentRoot() . '/' . $file->filename; - if (file_exists($currentFile)) { - $actualHash = sha1_file($currentFile); - if ($actualHash != $file->sha1) { - LoggerUtils::getAppLogger()->warning('File hash mismatch: ' . $file->filename . ". Expected: " . $file->sha1. "; Got: " . $actualHash); - array_push($signatureFailures, ['filename' => $file->filename, 'status' => 'Hash Mismatch', 'expectedhash' => $file->sha1, 'actualhash' => $actualHash]); - } - } else { - LoggerUtils::getAppLogger()->warning('File Missing: ' . $file->filename); - array_push($signatureFailures, ['filename' => $file->filename, 'status' => 'File Missing']); - } - } - } else { - LoggerUtils::getAppLogger()->warning('Signature definition file signature failed validation'); - return ['status' => 'failure', 'message' => gettext('Signature definition file signature failed validation')]; - } - } else { - LoggerUtils::getAppLogger()->warning('Signature definition file not found at: ' . $signatureFile); - return ['status' => 'failure', 'message' => gettext('Signature definition File Missing')]; + + public static function getApplicationPrerequisites() + { + $prerequisites = [ + new Prerequisite('PHP 7.4+', function () { return version_compare(PHP_VERSION, '7.4.0', '>='); }), + new Prerequisite('PCRE and UTF-8 Support', function () { return function_exists('preg_match') && @preg_match('/^.$/u', 'ñ') && @preg_match('/^\pL$/u', 'ñ'); }), + new Prerequisite('Multibyte Encoding', function () { return extension_loaded('mbstring'); }), + new Prerequisite('PHP Phar', function () { return extension_loaded('phar'); }), + new Prerequisite('PHP Session', function () { return extension_loaded('session'); }), + new Prerequisite('PHP XML', function () { return extension_loaded('xml'); }), + new Prerequisite('PHP EXIF', function () { return extension_loaded('exif'); }), + new Prerequisite('PHP iconv', function () { return extension_loaded('iconv'); }), + new Prerequisite('Mod Rewrite or Equivalent', function () { return AppIntegrityService::hasModRewrite(); }), + new Prerequisite('GD Library for image manipulation', function () { return extension_loaded('gd') && function_exists('gd_info'); }), + new Prerequisite('FreeType Library', function () { return function_exists('imagettftext'); }), + new Prerequisite('FileInfo Extension for image manipulation', function () { return extension_loaded('fileinfo'); }), + new Prerequisite('cURL', function () { return function_exists('curl_version'); }), + new Prerequisite('locale gettext', function () { return function_exists('bindtextdomain') && function_exists('gettext'); }), + new Prerequisite('Include/Config file is writeable', function () { return is_writable(SystemURLs::getDocumentRoot().'/Include/') || is_writable(SystemURLs::getDocumentRoot().'/Include/Config.php'); }), + new Prerequisite('Images directory is writeable', function () { return AppIntegrityService::testImagesWriteable(); }), + new Prerequisite('PHP ZipArchive', function () { return extension_loaded('zip'); }), + new Prerequisite('Mysqli Functions', function () { return function_exists('mysqli_connect'); }), + ]; + + return $prerequisites; } - if (count($signatureFailures) > 0) { - return ['status' => 'failure', 'message' => gettext('One or more files failed signature validation'), 'files' => $signatureFailures]; - } else { - return ['status' => 'success']; + public static function getUnmetPrerequisites() + { + return array_filter(AppIntegrityService::getApplicationPrerequisites(), function ($prereq) { + return !$prereq->IsPrerequisiteMet(); + }); } - } - - private static function testImagesWriteable() - { - return is_writable(SystemURLs::getDocumentRoot().'/Images/') && - is_writable(SystemURLs::getDocumentRoot().'/Images/Family') && - is_writable(SystemURLs::getDocumentRoot().'/Images/Person'); - - } - - public static function getApplicationPrerequisites() - { - - $prerequisites = array( - new Prerequisite('PHP 7.4+', function() { return version_compare(PHP_VERSION, '7.4.0', '>='); }), - new Prerequisite('PCRE and UTF-8 Support', function() { return function_exists('preg_match') && @preg_match('/^.$/u', 'ñ') && @preg_match('/^\pL$/u', 'ñ'); }), - new Prerequisite('Multibyte Encoding', function() { return extension_loaded('mbstring'); }), - new Prerequisite('PHP Phar', function() { return extension_loaded('phar'); }), - new Prerequisite('PHP Session', function() { return extension_loaded('session'); }), - new Prerequisite('PHP XML', function() { return extension_loaded('xml'); }), - new Prerequisite('PHP EXIF', function() { return extension_loaded('exif'); }), - new Prerequisite('PHP iconv', function() { return extension_loaded('iconv'); }), - new Prerequisite('Mod Rewrite or Equivalent', function() { return AppIntegrityService::hasModRewrite(); }), - new Prerequisite('GD Library for image manipulation', function() { return (extension_loaded('gd') && function_exists('gd_info')); }), - new Prerequisite('FreeType Library', function() { return function_exists('imagettftext'); }), - new Prerequisite('FileInfo Extension for image manipulation', function() { return extension_loaded('fileinfo'); }), - new Prerequisite('cURL', function() { return function_exists('curl_version'); }), - new Prerequisite('locale gettext', function() { return (function_exists('bindtextdomain') && function_exists("gettext")); }), - new Prerequisite('Include/Config file is writeable', function() { return is_writable(SystemURLs::getDocumentRoot().'/Include/') || is_writable(SystemURLs::getDocumentRoot().'/Include/Config.php'); }), - new Prerequisite('Images directory is writeable', function() { return AppIntegrityService::testImagesWriteable(); }), - new Prerequisite('PHP ZipArchive', function() { return extension_loaded('zip'); }), - new Prerequisite('Mysqli Functions', function() { return function_exists('mysqli_connect'); }) - ); - - return $prerequisites; - } - - public static function getUnmetPrerequisites() - { - return array_filter(AppIntegrityService::getApplicationPrerequisites(), function ($prereq) { - return ! $prereq->IsPrerequisiteMet(); - }); - } - - public static function arePrerequisitesMet() - { - return count(AppIntegrityService::getUnmetPrerequisites()) === 0; - } - - public static function hasApacheModule($module) - { - if (function_exists('apache_get_modules')) { - LoggerUtils::getAppLogger()->debug("looking for apache module $module using PHP's apache_get_modules"); - return in_array($module, apache_get_modules()); - } - return false; - } - - public static function hasModRewrite() - { - // mod_rewrite can be tricky to detect properly. - // First check if it's loaded as an apache module - // Second check (if supported) if apache cli lists the module - // Third, finally try calling a known invalid URL on this installation - // and check for a header that would only be present if .htaccess was processed. - // This header comes from index.php (which is the target of .htaccess for invalid URLs) - - $check = false; - $logger = LoggerUtils::getAppLogger(); - - if (stristr($_SERVER["SERVER_SOFTWARE"],"apache") != false) { - $logger->debug("PHP is running through Apache; look for mod_rewrite"); - $check = AppIntegrityService::hasApacheModule('mod_rewrite'); - $logger->debug("Apache mod_rewrite check status: $check"); + + public static function arePrerequisitesMet() + { + return count(AppIntegrityService::getUnmetPrerequisites()) === 0; } - else { - $logger->debug("PHP is not running through Apache"); + + public static function hasApacheModule($module) + { + if (function_exists('apache_get_modules')) { + LoggerUtils::getAppLogger()->debug("looking for apache module $module using PHP's apache_get_modules"); + + return in_array($module, apache_get_modules()); + } + + return false; } - if ($check == false){ - $logger->debug("Previous rewrite checks failed"); - if ( function_exists('curl_version')) { - $ch = curl_init(); - $request_url_parser = parse_url($_SERVER['HTTP_REFERER']); - $request_scheme = isset($request_url_parser['scheme']) ? $request_url_parser['scheme'] : 'http'; - $rewrite_chk_url = $request_scheme ."://". $_SERVER['SERVER_ADDR'] . SystemURLs::getRootPath()."/INVALID"; - $logger->debug("Testing CURL loopback check to: $rewrite_chk_url"); - curl_setopt($ch, CURLOPT_URL, $rewrite_chk_url); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 1); - curl_setopt($ch, CURLOPT_NOBODY, 1); - $output = curl_exec($ch); - curl_close($ch); - $headers=array(); - $data=explode("\n",$output); - $headers['status']=$data[0]; - array_shift($data); - foreach($data as $part){ - if (strpos($part, ":")) - { - $middle=explode(":",$part); - $headers[trim($middle[0])] = trim($middle[1]); - } - } - $check = $headers['CRM'] == "would redirect"; - $logger->debug("CURL loopback check headers observed: ".($check?'true':'false')); + public static function hasModRewrite() + { + // mod_rewrite can be tricky to detect properly. + // First check if it's loaded as an apache module + // Second check (if supported) if apache cli lists the module + // Third, finally try calling a known invalid URL on this installation + // and check for a header that would only be present if .htaccess was processed. + // This header comes from index.php (which is the target of .htaccess for invalid URLs) + + $check = false; + $logger = LoggerUtils::getAppLogger(); + + if (stristr($_SERVER['SERVER_SOFTWARE'], 'apache') != false) { + $logger->debug('PHP is running through Apache; look for mod_rewrite'); + $check = AppIntegrityService::hasApacheModule('mod_rewrite'); + $logger->debug("Apache mod_rewrite check status: $check"); + } else { + $logger->debug('PHP is not running through Apache'); } - } - return $check; - } + if ($check == false) { + $logger->debug('Previous rewrite checks failed'); + if (function_exists('curl_version')) { + $ch = curl_init(); + $request_url_parser = parse_url($_SERVER['HTTP_REFERER']); + $request_scheme = isset($request_url_parser['scheme']) ? $request_url_parser['scheme'] : 'http'; + $rewrite_chk_url = $request_scheme.'://'.$_SERVER['SERVER_ADDR'].SystemURLs::getRootPath().'/INVALID'; + $logger->debug("Testing CURL loopback check to: $rewrite_chk_url"); + curl_setopt($ch, CURLOPT_URL, $rewrite_chk_url); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 1); + curl_setopt($ch, CURLOPT_NOBODY, 1); + $output = curl_exec($ch); + curl_close($ch); + $headers = []; + $data = explode("\n", $output); + $headers['status'] = $data[0]; + array_shift($data); + foreach ($data as $part) { + if (strpos($part, ':')) { + $middle = explode(':', $part); + $headers[trim($middle[0])] = trim($middle[1]); + } + } + $check = $headers['CRM'] == 'would redirect'; + $logger->debug('CURL loopback check headers observed: '.($check ? 'true' : 'false')); + } + } + + return $check; + } } -?> diff --git a/src/ChurchCRM/Service/DashboardService.php b/src/ChurchCRM/Service/DashboardService.php index 30816135b2..51502be261 100644 --- a/src/ChurchCRM/Service/DashboardService.php +++ b/src/ChurchCRM/Service/DashboardService.php @@ -7,23 +7,25 @@ class DashboardService { - public function getAgeStats(){ - $ageStats = []; - $people = PersonQuery::create()->find(); - foreach($people as $person) { - $personNumericAge = (int)$person->getNumericAge(); - if ($personNumericAge == 0) - { - continue; - } - if(!array_key_exists($personNumericAge,$ageStats)){ - $ageStats[$personNumericAge] = 0; + public function getAgeStats() + { + $ageStats = []; + $people = PersonQuery::create()->find(); + foreach ($people as $person) { + $personNumericAge = (int) $person->getNumericAge(); + if ($personNumericAge == 0) { + continue; + } + if (!array_key_exists($personNumericAge, $ageStats)) { + $ageStats[$personNumericAge] = 0; + } + $ageStats[$personNumericAge]++; } - $ageStats[$personNumericAge]++; + ksort($ageStats); + + return $ageStats; } - ksort($ageStats); - return $ageStats; - } + public function getFamilyCount() { $familyCount = FamilyQuery::Create() @@ -37,7 +39,7 @@ public function getFamilyCount() public function getPersonCount() { $personCount = PersonQuery::Create('per') - ->useFamilyQuery('fam','left join') + ->useFamilyQuery('fam', 'left join') ->filterByDateDeactivated(null) ->endUse() ->count(); @@ -61,6 +63,7 @@ public function getPersonStats() return $data; } + public function getGroupStats() { $sSQL = 'select @@ -82,8 +85,10 @@ public function getGroupStats() } /** - * Return last edited members. Only from active families selected + * Return last edited members. Only from active families selected. + * * @param int $limit + * * @return array|\ChurchCRM\Person[]|mixed|\Propel\Runtime\ActiveRecord\ActiveRecordInterface[]|\Propel\Runtime\Collection\ObjectCollection */ public function getUpdatedMembers($limit = 12) @@ -97,8 +102,10 @@ public function getUpdatedMembers($limit = 12) } /** - * Newly added members. Only from Active families selected + * Newly added members. Only from Active families selected. + * * @param int $limit + * * @return array|\ChurchCRM\Person[]|mixed|\Propel\Runtime\ActiveRecord\ActiveRecordInterface[]|\Propel\Runtime\Collection\ObjectCollection */ public function getLatestMembers($limit = 12) diff --git a/src/ChurchCRM/Service/FinancialService.php b/src/ChurchCRM/Service/FinancialService.php index fed92d0c2c..de78cb700c 100644 --- a/src/ChurchCRM/Service/FinancialService.php +++ b/src/ChurchCRM/Service/FinancialService.php @@ -5,16 +5,15 @@ $bSuppressSessionTests = true; // DO NOT MOVE require_once dirname(dirname(__FILE__)).'/../Include/Functions.php'; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; +use ChurchCRM\FamilyQuery; use ChurchCRM\MICRReader; use ChurchCRM\PledgeQuery; -use ChurchCRM\FamilyQuery; -use ChurchCRM\Authentication\AuthenticationManager; class FinancialService { - public function deletePayment($groupKey) { requireUserGroupMembership('bFinance'); @@ -27,17 +26,17 @@ public function getMemberByScanString($sstrnig) if (SystemConfig::getValue('bUseScannedChecks')) { require '../Include/MICRFunctions.php'; $micrObj = new MICRReader(); // Instantiate the MICR class - $routeAndAccount = $micrObj->FindRouteAndAccount($tScanString); // use routing and account number for matching - if ($routeAndAccount) { - $sSQL = 'SELECT fam_ID, fam_Name FROM family_fam WHERE fam_scanCheck="'.$routeAndAccount.'"'; - $rsFam = RunQuery($sSQL); - extract(mysqli_fetch_array($rsFam)); - $iCheckNo = $micrObj->FindCheckNo($tScanString); - - return '{"ScanString": "'.$tScanString.'" , "RouteAndAccount": "'.$routeAndAccount.'" , "CheckNumber": "'.$iCheckNo.'" ,"fam_ID": "'.$fam_ID.'" , "fam_Name": "'.$fam_Name.'"}'; - } else { - throw new \Exception('error in locating family'); - } + $routeAndAccount = $micrObj->FindRouteAndAccount($tScanString); // use routing and account number for matching + if ($routeAndAccount) { + $sSQL = 'SELECT fam_ID, fam_Name FROM family_fam WHERE fam_scanCheck="'.$routeAndAccount.'"'; + $rsFam = RunQuery($sSQL); + extract(mysqli_fetch_array($rsFam)); + $iCheckNo = $micrObj->FindCheckNo($tScanString); + + return '{"ScanString": "'.$tScanString.'" , "RouteAndAccount": "'.$routeAndAccount.'" , "CheckNumber": "'.$iCheckNo.'" ,"fam_ID": "'.$fam_ID.'" , "fam_Name": "'.$fam_Name.'"}'; + } else { + throw new \Exception('error in locating family'); + } } else { throw new \Exception('Scanned Checks is disabled'); } @@ -50,7 +49,7 @@ public function setDeposit($depositType, $depositComment, $depositDate, $iDeposi $bGetKeyBack = false; if ($depositClosed && ($depositType == 'CreditCard' || $depositType == 'BankDraft')) { // Delete any failed transactions on this deposit slip now that it is closing - $q = 'DELETE FROM pledge_plg WHERE plg_depID = '.$iDepositSlipID.' AND plg_PledgeOrPayment="Payment" AND plg_aut_Cleared=0'; + $q = 'DELETE FROM pledge_plg WHERE plg_depID = '.$iDepositSlipID.' AND plg_PledgeOrPayment="Payment" AND plg_aut_Cleared=0'; RunQuery($q); } RunQuery($sSQL); @@ -74,8 +73,8 @@ public function getDepositTotal($id, $type = null) if ($type) { $sqlClause = "AND plg_method = '".$type."'"; } - // Get deposit total - $sSQL = "SELECT SUM(plg_amount) AS deposit_total FROM pledge_plg WHERE plg_depID = '$id' AND plg_PledgeOrPayment = 'Payment' ".$sqlClause; + // Get deposit total + $sSQL = "SELECT SUM(plg_amount) AS deposit_total FROM pledge_plg WHERE plg_depID = '$id' AND plg_PledgeOrPayment = 'Payment' ".$sqlClause; $rsDepositTotal = RunQuery($sSQL); list($deposit_total) = mysqli_fetch_row($rsDepositTotal); @@ -154,37 +153,37 @@ public function getViewURI($Id) private function validateDate($payment) { // Validate Date - if (strlen($payment->Date) > 0) { - list($iYear, $iMonth, $iDay) = sscanf($payment->Date, '%04d-%02d-%02d'); - if (!checkdate($iMonth, $iDay, $iYear)) { - throw new \Exception('Invalid Date'); + if (strlen($payment->Date) > 0) { + list($iYear, $iMonth, $iDay) = sscanf($payment->Date, '%04d-%02d-%02d'); + if (!checkdate($iMonth, $iDay, $iYear)) { + throw new \Exception('Invalid Date'); + } } } - } private function validateFund($payment) { //Validate that the fund selection is valid: - //If a single fund is selected, that fund must exist, and not equal the default "Select a Fund" selection. - //If a split is selected, at least one fund must be non-zero, the total must add up to the total of all funds, and all funds in the split must be valid funds. - $FundSplit = json_decode($payment->FundSplit); + //If a single fund is selected, that fund must exist, and not equal the default "Select a Fund" selection. + //If a split is selected, at least one fund must be non-zero, the total must add up to the total of all funds, and all funds in the split must be valid funds. + $FundSplit = json_decode($payment->FundSplit); if (count($FundSplit) >= 1 and $FundSplit[0]->FundID != 'None') { // split - $nonZeroFundAmountEntered = 0; + $nonZeroFundAmountEntered = 0; foreach ($FundSplit as $fun_id => $fund) { //$fun_active = $fundActive[$fun_id]; - if ($fund->Amount > 0) { - ++$nonZeroFundAmountEntered; - } + if ($fund->Amount > 0) { + $nonZeroFundAmountEntered++; + } if (SystemConfig::getValue('bEnableNonDeductible') && isset($fund->NonDeductible)) { //Validate the NonDeductible Amount - if ($fund->NonDeductible > $fund->Amount) { //Validate the NonDeductible Amount - throw new \Exception(gettext("NonDeductible amount can't be greater than total amount.")); - } + if ($fund->NonDeductible > $fund->Amount) { //Validate the NonDeductible Amount + throw new \Exception(gettext("NonDeductible amount can't be greater than total amount.")); + } } } // end foreach - if (!$nonZeroFundAmountEntered) { - throw new \Exception(gettext('At least one fund must have a non-zero amount.')); - } + if (!$nonZeroFundAmountEntered) { + throw new \Exception(gettext('At least one fund must have a non-zero amount.')); + } } else { throw new \Exception('Must select a valid fund'); } @@ -204,21 +203,21 @@ public function locateFamilyCheck($checkNumber, $fam_ID) public function validateChecks($payment) { requireUserGroupMembership('bFinance'); - //validate that the payment options are valid - //If the payment method is a check, then the check number must be present, and it must not already have been used for this family - //if the payment method is cash, there must not be a check number - if ($payment->type == 'Payment' and $payment->iMethod == 'CHECK' and !isset($payment->iCheckNo)) { - throw new \Exception(gettext('Must specify non-zero check number')); - } - // detect check inconsistencies - if ($payment->type == 'Payment' and isset($payment->iCheckNo)) { - if ($payment->iMethod == 'CASH') { - throw new \Exception(gettext("Check number not valid for 'CASH' payment")); - } //build routine to make sure this check number hasn't been used by this family yet (look at group key) - elseif ($payment->iMethod == 'CHECK' and $this->locateFamilyCheck($payment->iCheckNo, $payment->FamilyID)) { - throw new \Exception("Check number '".$payment->iCheckNo."' for selected family already exists."); - } - } + //validate that the payment options are valid + //If the payment method is a check, then the check number must be present, and it must not already have been used for this family + //if the payment method is cash, there must not be a check number + if ($payment->type == 'Payment' and $payment->iMethod == 'CHECK' and !isset($payment->iCheckNo)) { + throw new \Exception(gettext('Must specify non-zero check number')); + } + // detect check inconsistencies + if ($payment->type == 'Payment' and isset($payment->iCheckNo)) { + if ($payment->iMethod == 'CASH') { + throw new \Exception(gettext("Check number not valid for 'CASH' payment")); + } //build routine to make sure this check number hasn't been used by this family yet (look at group key) + elseif ($payment->iMethod == 'CHECK' and $this->locateFamilyCheck($payment->iCheckNo, $payment->FamilyID)) { + throw new \Exception("Check number '".$payment->iCheckNo."' for selected family already exists."); + } + } } public function processCurrencyDenominations($payment, $groupKey) @@ -237,29 +236,29 @@ public function processCurrencyDenominations($payment, $groupKey) public function insertPledgeorPayment($payment) { requireUserGroupMembership('bFinance'); - // Only set PledgeOrPayment when the record is first created - // loop through all funds and create non-zero amount pledge records - unset($sGroupKey); + // Only set PledgeOrPayment when the record is first created + // loop through all funds and create non-zero amount pledge records + unset($sGroupKey); $FundSplit = json_decode($payment->FundSplit); foreach ($FundSplit as $Fund) { if ($Fund->Amount > 0) { //Only insert a row in the pledge table if this fund has a non zero amount. - if (!isset($sGroupKey)) { //a GroupKey references a single familie's payment, and transcends the fund splits. Sharing the same Group Key for this payment helps clean up reports. - if ($payment->iMethod == 'CHECK') { - $sGroupKey = genGroupKey($payment->iCheckNo, $payment->FamilyID, $Fund->FundID, $payment->Date); - } elseif ($payment->iMethod == 'BANKDRAFT') { - if (!$iAutID) { - $iAutID = 'draft'; - } - $sGroupKey = genGroupKey($iAutID, $payment->FamilyID, $Fund->FundID, $payment->Date); - } elseif ($payment->iMethod == 'CREDITCARD') { - if (!$iAutID) { - $iAutID = 'credit'; - } - $sGroupKey = genGroupKey($iAutID, $payment->FamilyID, $Fund->FundID, $payment->Date); - } else { - $sGroupKey = genGroupKey('cash', $payment->FamilyID, $Fund->FundID, $payment->Date); - } - } + if (!isset($sGroupKey)) { //a GroupKey references a single familie's payment, and transcends the fund splits. Sharing the same Group Key for this payment helps clean up reports. + if ($payment->iMethod == 'CHECK') { + $sGroupKey = genGroupKey($payment->iCheckNo, $payment->FamilyID, $Fund->FundID, $payment->Date); + } elseif ($payment->iMethod == 'BANKDRAFT') { + if (!$iAutID) { + $iAutID = 'draft'; + } + $sGroupKey = genGroupKey($iAutID, $payment->FamilyID, $Fund->FundID, $payment->Date); + } elseif ($payment->iMethod == 'CREDITCARD') { + if (!$iAutID) { + $iAutID = 'credit'; + } + $sGroupKey = genGroupKey($iAutID, $payment->FamilyID, $Fund->FundID, $payment->Date); + } else { + $sGroupKey = genGroupKey('cash', $payment->FamilyID, $Fund->FundID, $payment->Date); + } + } $sSQL = "INSERT INTO pledge_plg (plg_famID, plg_FYID, @@ -342,7 +341,7 @@ public function getPledgeorPayment($GroupKey) $onePlgID = $aRow['plg_plgID']; $oneFundID = $aRow['plg_fundID']; $iOriginalSelectedFund = $oneFundID; // remember the original fund in case we switch to splitting - $fund2PlgIds[$oneFundID] = $onePlgID; + $fund2PlgIds[$oneFundID] = $onePlgID; } $payment->total = $total; @@ -352,12 +351,12 @@ public function getPledgeorPayment($GroupKey) private function generateBankDepositSlip($thisReport) { // -------------------------------- - // BEGIN FRONT OF BANK DEPOSIT SLIP - $thisReport->pdf->AddPage('L', [187, 84]); + // BEGIN FRONT OF BANK DEPOSIT SLIP + $thisReport->pdf->AddPage('L', [187, 84]); $thisReport->pdf->SetFont('Courier', '', 18); - // Print Deposit Slip portion of report + // Print Deposit Slip portion of report - $thisReport->pdf->SetXY($thisReport->date1X, $thisReport->date1Y); + $thisReport->pdf->SetXY($thisReport->date1X, $thisReport->date1Y); $thisReport->pdf->Write(8, $thisReport->deposit->dep_Date); $thisReport->pdf->SetXY($thisReport->customerName1X, $thisReport->customerName1Y); @@ -387,22 +386,22 @@ private function generateBankDepositSlip($thisReport) $thisReport->pdf->SetXY($thisReport->topTotalX, $thisReport->topTotalY); $thisReport->pdf->Cell(46, 7, $grandTotalStr, 1, 1, 'R'); - // -------------------------------- - // BEGIN BACK OF BANK DEPOSIT SLIP + // -------------------------------- + // BEGIN BACK OF BANK DEPOSIT SLIP - $thisReport->pdf->AddPage('P', [84, 187]); + $thisReport->pdf->AddPage('P', [84, 187]); $numItems = 0; foreach ($thisReport->payments as $payment) { // List all the checks and total the cash - if ($payment->plg_method == 'CHECK') { - $plgSumStr = sprintf('%.2f', $payment->plg_amount); - $thisReport->pdf->SetFontSize(14); - $thisReport->pdf->SetXY($thisReport->depositSlipBackCheckNosX, $thisReport->depositSlipBackCheckNosY + $numItems * $thisReport->depositSlipBackCheckNosHeight); - $thisReport->pdf->Cell($thisReport->depositSlipBackCheckNosWidth, $thisReport->depositSlipBackCheckNosHeight, $payment->plg_CheckNo, 1, 0, 'L'); - $thisReport->pdf->SetFontSize(18); - $thisReport->pdf->Cell($thisReport->depositSlipBackDollarsWidth, $thisReport->depositSlipBackDollarsHeight, $plgSumStr, 1, 1, 'R'); - $numItems += 1; - } + if ($payment->plg_method == 'CHECK') { + $plgSumStr = sprintf('%.2f', $payment->plg_amount); + $thisReport->pdf->SetFontSize(14); + $thisReport->pdf->SetXY($thisReport->depositSlipBackCheckNosX, $thisReport->depositSlipBackCheckNosY + $numItems * $thisReport->depositSlipBackCheckNosHeight); + $thisReport->pdf->Cell($thisReport->depositSlipBackCheckNosWidth, $thisReport->depositSlipBackCheckNosHeight, $payment->plg_CheckNo, 1, 0, 'L'); + $thisReport->pdf->SetFontSize(18); + $thisReport->pdf->Cell($thisReport->depositSlipBackDollarsWidth, $thisReport->depositSlipBackDollarsHeight, $plgSumStr, 1, 1, 'R'); + $numItems += 1; + } } } @@ -457,49 +456,49 @@ private function generateDepositSummary($thisReport) $totalAmount = 0; - //while ($aRow = mysqli_fetch_array($rsPledges)) - foreach ($thisReport->payments as $payment) { - $thisReport->pdf->SetFont('Times', '', 10); + //while ($aRow = mysqli_fetch_array($rsPledges)) + foreach ($thisReport->payments as $payment) { + $thisReport->pdf->SetFont('Times', '', 10); - // Format Data - if (strlen($payment->plg_CheckNo) > 8) { - $payment->plg_CheckNo = '...'.mb_substr($payment->plg_CheckNo, -8, 8); - } - if (strlen($payment->fun_Name) > 20) { - $payment->fun_Name = mb_substr($payment->fun_Name, 0, 20).'...'; - } - if (strlen($payment->plg_comment) > 40) { - $payment->plg_comment = mb_substr($payment->plg_comment, 0, 38).'...'; - } - if (strlen($payment->familyName) > 25) { - $payment->familyName = mb_substr($payment->familyName, 0, 24).'...'; - } + // Format Data + if (strlen($payment->plg_CheckNo) > 8) { + $payment->plg_CheckNo = '...'.mb_substr($payment->plg_CheckNo, -8, 8); + } + if (strlen($payment->fun_Name) > 20) { + $payment->fun_Name = mb_substr($payment->fun_Name, 0, 20).'...'; + } + if (strlen($payment->plg_comment) > 40) { + $payment->plg_comment = mb_substr($payment->plg_comment, 0, 38).'...'; + } + if (strlen($payment->familyName) > 25) { + $payment->familyName = mb_substr($payment->familyName, 0, 24).'...'; + } - $thisReport->pdf->PrintRightJustified($thisReport->curX + 2, $thisReport->curY, $payment->plg_CheckNo); + $thisReport->pdf->PrintRightJustified($thisReport->curX + 2, $thisReport->curY, $payment->plg_CheckNo); - $thisReport->pdf->SetXY($thisReport->curX + $thisReport->depositSummaryParameters->summary->FundX, $thisReport->curY); - $thisReport->pdf->Write(8, $payment->fun_Name); + $thisReport->pdf->SetXY($thisReport->curX + $thisReport->depositSummaryParameters->summary->FundX, $thisReport->curY); + $thisReport->pdf->Write(8, $payment->fun_Name); - $thisReport->pdf->SetXY($thisReport->curX + $thisReport->depositSummaryParameters->summary->MethodX, $thisReport->curY); - $thisReport->pdf->Write(8, $payment->plg_method); + $thisReport->pdf->SetXY($thisReport->curX + $thisReport->depositSummaryParameters->summary->MethodX, $thisReport->curY); + $thisReport->pdf->Write(8, $payment->plg_method); - $thisReport->pdf->SetXY($thisReport->curX + $thisReport->depositSummaryParameters->summary->FromX, $thisReport->curY); - $thisReport->pdf->Write(8, $payment->familyName); + $thisReport->pdf->SetXY($thisReport->curX + $thisReport->depositSummaryParameters->summary->FromX, $thisReport->curY); + $thisReport->pdf->Write(8, $payment->familyName); - $thisReport->pdf->SetXY($thisReport->curX + $thisReport->depositSummaryParameters->summary->MemoX, $thisReport->curY); - $thisReport->pdf->Write(8, $payment->plg_comment); + $thisReport->pdf->SetXY($thisReport->curX + $thisReport->depositSummaryParameters->summary->MemoX, $thisReport->curY); + $thisReport->pdf->Write(8, $payment->plg_comment); - $thisReport->pdf->SetFont('Courier', '', 8); + $thisReport->pdf->SetFont('Courier', '', 8); - $thisReport->pdf->PrintRightJustified($thisReport->curX + $thisReport->depositSummaryParameters->summary->AmountX, $thisReport->curY, $payment->plg_amount); + $thisReport->pdf->PrintRightJustified($thisReport->curX + $thisReport->depositSummaryParameters->summary->AmountX, $thisReport->curY, $payment->plg_amount); - $thisReport->curY += $thisReport->depositSummaryParameters->summary->intervalY; + $thisReport->curY += $thisReport->depositSummaryParameters->summary->intervalY; - if ($thisReport->curY >= 250) { - $thisReport->pdf->AddPage(); - $thisReport->curY = $thisReport->topY; + if ($thisReport->curY >= 250) { + $thisReport->pdf->AddPage(); + $thisReport->curY = $thisReport->topY; + } } - } $thisReport->curY += $thisReport->depositSummaryParameters->summary->intervalY; @@ -509,8 +508,8 @@ private function generateDepositSummary($thisReport) $grandTotalStr = sprintf('%.2f', $thisReport->deposit->dep_Total); $thisReport->pdf->PrintRightJustified($thisReport->curX + $thisReport->depositSummaryParameters->summary->AmountX, $thisReport->curY, $grandTotalStr); - // Now print deposit totals by fund - $thisReport->curY += 2 * $thisReport->depositSummaryParameters->summary->intervalY; + // Now print deposit totals by fund + $thisReport->curY += 2 * $thisReport->depositSummaryParameters->summary->intervalY; if ($thisReport->depositSummaryParameters->displayBillCounts) { $this->generateCashDenominations($thisReport); } @@ -573,8 +572,8 @@ public function getDepositCSV($depID) $CSVReturn = new \stdClass(); $CSVReturn->content = $retstring; - // Export file - $CSVReturn->header = 'Content-Disposition: attachment; filename=ChurchCRM-DepositCSV-'.$depID.'-'.date(SystemConfig::getValue("sDateFilenameFormat")).'.csv'; + // Export file + $CSVReturn->header = 'Content-Disposition: attachment; filename=ChurchCRM-DepositCSV-'.$depID.'-'.date(SystemConfig::getValue('sDateFilenameFormat')).'.csv'; return $CSVReturn; } @@ -582,8 +581,8 @@ public function getDepositCSV($depID) public function getCurrencyTypeOnDeposit($currencyID, $depositID) { $currencies = []; - // Get the list of Currency denominations - $sSQL = 'select sum(pdem_denominationQuantity) from pledge_denominations_pdem + // Get the list of Currency denominations + $sSQL = 'select sum(pdem_denominationQuantity) from pledge_denominations_pdem where plg_depID = '.$depositID.' AND pdem_denominationID = '.$currencyID; @@ -595,8 +594,8 @@ public function getCurrencyTypeOnDeposit($currencyID, $depositID) public function getCurrency() { $currencies = []; - // Get the list of Currency denominations - $sSQL = 'SELECT * FROM currency_denominations_cdem'; + // Get the list of Currency denominations + $sSQL = 'SELECT * FROM currency_denominations_cdem'; $rscurrencyDenomination = RunQuery($sSQL); mysqli_data_seek($rscurrencyDenomination, 0); while ($row = mysqli_fetch_array($rscurrencyDenomination)) { @@ -607,7 +606,8 @@ public function getCurrency() $currency->cClass = $row['cdem_denominationClass']; array_push($currencies, $currency); } // end while - return $currencies; + + return $currencies; } public function getActiveFunds() @@ -616,7 +616,7 @@ public function getActiveFunds() $funds = []; $sSQL = 'SELECT fun_ID,fun_Name,fun_Description,fun_Active FROM donationfund_fun'; $sSQL .= " WHERE fun_Active = 'true'"; // New donations should show only active funds. - $rsFunds = RunQuery($sSQL); + $rsFunds = RunQuery($sSQL); mysqli_data_seek($rsFunds, 0); while ($aRow = mysqli_fetch_array($rsFunds)) { $fund = new \stdClass(); @@ -625,6 +625,7 @@ public function getActiveFunds() $fund->Description = $aRow['fun_Description']; array_push($funds, $fund); } // end while - return $funds; + + return $funds; } } diff --git a/src/ChurchCRM/Service/GroupService.php b/src/ChurchCRM/Service/GroupService.php index 9dac586b1e..3461e16cc1 100644 --- a/src/ChurchCRM/Service/GroupService.php +++ b/src/ChurchCRM/Service/GroupService.php @@ -6,7 +6,6 @@ class GroupService { - /** * removeUserFromGroup. * @@ -119,8 +118,6 @@ public function getGroupRoles($groupID) return $groupRoles; } - - public function setGroupRoleOrder($groupID, $groupRoleID, $groupRoleOrder) { requireUserGroupMembership('bManageGroups'); @@ -315,21 +312,18 @@ public function getGroupMembers($groupID, $personID = null) WHERE p2g2r_grp_ID ='.$groupID.' '.$whereClause; $result = mysqli_query($cnInfoCentral, $sSQL); while ($row = mysqli_fetch_assoc($result)) { - //on teste si les propriétés sont bonnes - if (array_key_exists('p2g2r_per_ID',$row) && array_key_exists('lst_OptionName',$row)) - { - $dbPerson = PersonQuery::create()->findPk($row['p2g2r_per_ID']); - - if (array_key_exists('displayName',$dbPerson)) - { - $person['displayName'] = $dbPerson->getFullName(); - $person['groupRole'] = $row['lst_OptionName']; - array_push($members, $person); - } - } + //on teste si les propriétés sont bonnes + if (array_key_exists('p2g2r_per_ID', $row) && array_key_exists('lst_OptionName', $row)) { + $dbPerson = PersonQuery::create()->findPk($row['p2g2r_per_ID']); + + if (array_key_exists('displayName', $dbPerson)) { + $person['displayName'] = $dbPerson->getFullName(); + $person['groupRole'] = $row['lst_OptionName']; + array_push($members, $person); + } + } } return $members; } - } diff --git a/src/ChurchCRM/Service/MailChimpService.php b/src/ChurchCRM/Service/MailChimpService.php index a5800b9e27..d36f631b8e 100644 --- a/src/ChurchCRM/Service/MailChimpService.php +++ b/src/ChurchCRM/Service/MailChimpService.php @@ -3,9 +3,9 @@ namespace ChurchCRM\Service; use ChurchCRM\dto\SystemConfig; -use \DrewM\MailChimp\MailChimp; -use ChurchCRM\Utils\LoggerUtils; use ChurchCRM\Utils\ExecutionTime; +use ChurchCRM\Utils\LoggerUtils; +use DrewM\MailChimp\MailChimp; use PHPMailer\PHPMailer\Exception; class MailChimpService @@ -28,47 +28,53 @@ public function isActive() return true; } if ($this->hasKey) { - $rootAPI = $this->myMailchimp->get(""); - if ( $rootAPI["total_subscribers"] > 0 ) { + $rootAPI = $this->myMailchimp->get(''); + if ($rootAPI['total_subscribers'] > 0) { $this->isActive = true; + return true; } } + return false; } private function getListsFromCache() { if (!isset($_SESSION['MailChimpLists'])) { - LoggerUtils::getAppLogger()->debug("Updating MailChimp List Cache"); - $time = new ExecutionTime; - $lists = $this->myMailchimp->get("lists")['lists']; - LoggerUtils::getAppLogger()->debug("MailChimp list enumeration took: " . $time->getMilliseconds() . " ms. Found " . count($lists) . " lists"); + LoggerUtils::getAppLogger()->debug('Updating MailChimp List Cache'); + $time = new ExecutionTime(); + $lists = $this->myMailchimp->get('lists')['lists']; + LoggerUtils::getAppLogger()->debug('MailChimp list enumeration took: '.$time->getMilliseconds().' ms. Found '.count($lists).' lists'); foreach ($lists as &$list) { $list['members'] = []; - $listmembers = $this->myMailchimp->get('lists/' . $list['id'] . '/members', + $listmembers = $this->myMailchimp->get( + 'lists/'.$list['id'].'/members', [ - 'count' => $list['stats']["member_count"], - "fields" => "members.id,members.email_address,members.status,members.merge_fields", - "status" => "subscribed" - ]); + 'count' => $list['stats']['member_count'], + 'fields' => 'members.id,members.email_address,members.status,members.merge_fields', + 'status' => 'subscribed', + ] + ); foreach ($listmembers['members'] as $member) { - array_push($list['members'], [ - "email" => strtolower($member["email_address"]), - "first" => $member["merge_fields"]["FNAME"], - "last" => $member["merge_fields"]["LNAME"], - "status" => $member["status"] + array_push( + $list['members'], + [ + 'email' => strtolower($member['email_address']), + 'first' => $member['merge_fields']['FNAME'], + 'last' => $member['merge_fields']['LNAME'], + 'status' => $member['status'], ] ); } - LoggerUtils::getAppLogger()->debug("MailChimp list ". $list['id'] . " membership ". count($list['members'])); - + LoggerUtils::getAppLogger()->debug('MailChimp list '.$list['id'].' membership '.count($list['members'])); } - LoggerUtils::getAppLogger()->debug("MailChimp list and membership update took: " . $time->getMilliseconds() . " ms"); + LoggerUtils::getAppLogger()->debug('MailChimp list and membership update took: '.$time->getMilliseconds().' ms'); $_SESSION['MailChimpLists'] = $lists; } else { - LoggerUtils::getAppLogger()->debug("Using cached MailChimp List"); + LoggerUtils::getAppLogger()->debug('Using cached MailChimp List'); } + return $_SESSION['MailChimpLists']; } @@ -85,10 +91,11 @@ public function isEmailInMailChimp($email) $lists = $this->getListsFromCache(); $listsStatus = []; foreach ($lists as $list) { - $data = $this->myMailchimp->get("lists/" . $list["id"] . "/members/" . md5($email)); - LoggerUtils::getAppLogger()->debug($email . " is " . $data["status"] . " to " . $list["name"]); - array_push($listsStatus, ["name" => $list["name"], "status" => $data["status"], "stats" => $data["stats"]]); + $data = $this->myMailchimp->get('lists/'.$list['id'].'/members/'.md5($email)); + LoggerUtils::getAppLogger()->debug($email.' is '.$data['status'].' to '.$list['name']); + array_push($listsStatus, ['name' => $list['name'], 'status' => $data['status'], 'stats' => $data['stats']]); } + return $listsStatus; } @@ -97,13 +104,15 @@ public function getLists() if (!$this->isActive()) { return new Exception(gettext('Mailchimp is not active')); } + return $this->getListsFromCache(); } - public function getList($listId) { + public function getList($listId) + { $mailchimpLists = $this->getLists(); foreach ($mailchimpLists as $mailchimpList) { - if ($listId == $mailchimpList["id"]) { + if ($listId == $mailchimpList['id']) { return $mailchimpList; } } diff --git a/src/ChurchCRM/Service/NewDashboardService.php b/src/ChurchCRM/Service/NewDashboardService.php index 94f888eae7..a77c7965e7 100644 --- a/src/ChurchCRM/Service/NewDashboardService.php +++ b/src/ChurchCRM/Service/NewDashboardService.php @@ -1,32 +1,33 @@ TTL) ) { - $_SESSION['SystemNotifications'] = $TempNotificaions; - $_SESSION['SystemNotifications']->expires = new \DateTime(); - $_SESSION['SystemNotifications']->expires->add(new \DateInterval("PT".$_SESSION['SystemNotifications']->TTL."S")); - } - } catch (\Exception $ex) { - //a failure here should never prevent the page from loading. - //Possibly log an exception when a unified logger is implemented. - //for now, do nothing. + public static function updateNotifications() + { + /* Get the latest notifications from the source. Store in session variable + * + */ + try { + $TempNotificaions = json_decode(file_get_contents(SystemConfig::getValue('sNotificationsURL'))); + if (isset($TempNotificaions->TTL)) { + $_SESSION['SystemNotifications'] = $TempNotificaions; + $_SESSION['SystemNotifications']->expires = new \DateTime(); + $_SESSION['SystemNotifications']->expires->add(new \DateInterval('PT'.$_SESSION['SystemNotifications']->TTL.'S')); + } + } catch (\Exception $ex) { + //a failure here should never prevent the page from loading. + //Possibly log an exception when a unified logger is implemented. + //for now, do nothing. + } } - } - public static function getNotifications() - { - /* retrieve active notifications from the session variable for display - * - */ - if (isset($_SESSION['SystemNotifications'])) + public static function getNotifications() { - $notifications = array(); - foreach ($_SESSION['SystemNotifications']->messages as $message) - { - if($message->targetVersion == $_SESSION['sSoftwareInstalledVersion']) - { - if (! $message->adminOnly || AuthenticationManager::GetCurrentUser()->isAdmin()) - { - array_push($notifications, $message); - } + /* retrieve active notifications from the session variable for display + * + */ + if (isset($_SESSION['SystemNotifications'])) { + $notifications = []; + foreach ($_SESSION['SystemNotifications']->messages as $message) { + if ($message->targetVersion == $_SESSION['sSoftwareInstalledVersion']) { + if (!$message->adminOnly || AuthenticationManager::GetCurrentUser()->isAdmin()) { + array_push($notifications, $message); + } + } + } + + return $notifications; } - } - return $notifications; } - } - public static function hasActiveNotifications() - { - return count(NotificationService::getNotifications()) > 0; - } - - public static function isUpdateRequired() - { - /* - * If session does not contain notifications, or if the notification TTL has expired, return true - * otherwise return false. - */ - if (!isset($_SESSION['SystemNotifications']) || $_SESSION['SystemNotifications']->expires < new \DateTime()) + public static function hasActiveNotifications() { - return true; + return count(NotificationService::getNotifications()) > 0; } - return false; - } + public static function isUpdateRequired() + { + /* + * If session does not contain notifications, or if the notification TTL has expired, return true + * otherwise return false. + */ + if (!isset($_SESSION['SystemNotifications']) || $_SESSION['SystemNotifications']->expires < new \DateTime()) { + return true; + } + + return false; + } } diff --git a/src/ChurchCRM/Service/PersonService.php b/src/ChurchCRM/Service/PersonService.php index 3ffddbc282..fbbd4575cd 100644 --- a/src/ChurchCRM/Service/PersonService.php +++ b/src/ChurchCRM/Service/PersonService.php @@ -7,7 +7,7 @@ class PersonService { - public function search($searchTerm, $includeFamilyRole=true) + public function search($searchTerm, $includeFamilyRole = true) { $searchLikeString = '%'.$searchTerm.'%'; $people = PersonQuery::create()-> @@ -29,14 +29,14 @@ public function search($searchTerm, $includeFamilyRole=true) $values['role'] = $person->getFamilyRoleName(); if ($includeFamilyRole) { - $familyRole = "("; + $familyRole = '('; if ($values['familyID']) { if ($person->getFamilyRole()) { $familyRole .= $person->getFamilyRoleName(); } else { $familyRole .= gettext('Part'); } - $familyRole .= gettext(' of the') . ' ' . $person->getFamily()->getName() . ' ' . gettext('family') . ' )'; + $familyRole .= gettext(' of the').' '.$person->getFamily()->getName().' '.gettext('family').' )'; } else { $familyRole = gettext('(No assigned family)'); } diff --git a/src/ChurchCRM/Service/SundaySchoolService.php b/src/ChurchCRM/Service/SundaySchoolService.php index 6aeedd37bf..ce97ee1b35 100644 --- a/src/ChurchCRM/Service/SundaySchoolService.php +++ b/src/ChurchCRM/Service/SundaySchoolService.php @@ -75,15 +75,15 @@ public function getKidsGender($groupId) foreach ($kids as $kid) { switch ($kid['per_Gender']) { - case 1: - $boys++; - break; - case 2: - $girls++; - break; - default: - $unknown++; - } + case 1: + $boys++; + break; + case 2: + $girls++; + break; + default: + $unknown++; + } } return ['Boys' => $boys, 'Girls' => $girls, 'Unknown' => $unknown]; @@ -107,64 +107,64 @@ public function getKidsBirthdayMonth($groupId) foreach ($kids as $kid) { switch ($kid['per_BirthMonth']) { - case 1: - $Jan++; - break; - case 2: - $Feb++; - break; - case 3: - $Mar++; - break; - case 4: - $Apr++; - break; - case 5: - $May++; - break; - case 6: - $June++; - break; - case 7: - $July++; - break; - case 8: - $Aug++; - break; - case 9: - $Sept++; - break; - case 10: - $Oct++; - break; - case 11: - $Nov++; - break; - case 12: - $Dec++; - break; - } + case 1: + $Jan++; + break; + case 2: + $Feb++; + break; + case 3: + $Mar++; + break; + case 4: + $Apr++; + break; + case 5: + $May++; + break; + case 6: + $June++; + break; + case 7: + $July++; + break; + case 8: + $Aug++; + break; + case 9: + $Sept++; + break; + case 10: + $Oct++; + break; + case 11: + $Nov++; + break; + case 12: + $Dec++; + break; + } } - return ['Jan' => $Jan, - 'Feb' => $Feb, - 'Mar' => $Mar, - 'Apr' => $Apr, - 'May' => $May, - 'June' => $June, - 'July' => $July, - 'Aug' => $Aug, - 'Sept' => $Sept, - 'Oct' => $Oct, - 'Nov' => $Nov, - 'Dec' => $Dec, - ]; + return ['Jan' => $Jan, + 'Feb' => $Feb, + 'Mar' => $Mar, + 'Apr' => $Apr, + 'May' => $May, + 'June' => $June, + 'July' => $July, + 'Aug' => $Aug, + 'Sept' => $Sept, + 'Oct' => $Oct, + 'Nov' => $Nov, + 'Dec' => $Dec, + ]; } public function getKidsFullDetails($groupId) { // Get all the groups - $sSQL = 'select grp.grp_Name sundayschoolClass, kid.per_ID kidId, kid.per_Gender kidGender, + $sSQL = 'select grp.grp_Name sundayschoolClass, kid.per_ID kidId, kid.per_Gender kidGender, kid.per_FirstName firstName, kid.per_Email kidEmail, kid.per_LastName LastName, kid.per_BirthDay birthDay, kid.per_BirthMonth birthMonth, kid.per_BirthYear birthYear, kid.per_CellPhone mobilePhone, kid.per_Flags flags, diff --git a/src/ChurchCRM/Service/SystemService.php b/src/ChurchCRM/Service/SystemService.php index 4ff6c4fa39..0bb87bfa05 100644 --- a/src/ChurchCRM/Service/SystemService.php +++ b/src/ChurchCRM/Service/SystemService.php @@ -12,25 +12,22 @@ use PDO; use Propel\Runtime\Propel; -require SystemURLs::getDocumentRoot() . '/vendor/ifsnop/mysqldump-php/src/Ifsnop/Mysqldump/Mysqldump.php'; - +require SystemURLs::getDocumentRoot().'/vendor/ifsnop/mysqldump-php/src/Ifsnop/Mysqldump/Mysqldump.php'; class SystemService { - - - static public function getInstalledVersion() + public static function getInstalledVersion() { - $composerFile = file_get_contents(SystemURLs::getDocumentRoot() . '/composer.json'); + $composerFile = file_get_contents(SystemURLs::getDocumentRoot().'/composer.json'); $composerJson = json_decode($composerFile, true); $version = $composerJson['version']; return $version; } - static public function getCopyrightDate() + public static function getCopyrightDate() { - return (new \DateTime())->format("Y"); + return (new \DateTime())->format('Y'); } public function getConfigurationSetting($settingName, $settingValue) @@ -43,7 +40,7 @@ public function setConfigurationSetting($settingName, $settingValue) requireUserGroupMembership('bAdmin'); } - static public function getDBVersion() + public static function getDBVersion() { $connection = Propel::getConnection(); $query = 'Select * from version_ver order by ver_update_end desc limit 1'; @@ -51,33 +48,31 @@ static public function getDBVersion() $statement->execute(); $results = $statement->fetchAll(\PDO::FETCH_ASSOC); rsort($results); + return $results[0]['ver_version']; } public static function getDBServerVersion() { - try{ - return Propel::getServiceContainer()->getConnection()->getAttribute(PDO::ATTR_SERVER_VERSION); - } - catch (\Exception $exc) - { - return "Could not obtain DB Server Version"; - } + try { + return Propel::getServiceContainer()->getConnection()->getAttribute(PDO::ATTR_SERVER_VERSION); + } catch (\Exception $exc) { + return 'Could not obtain DB Server Version'; + } } - static public function getPrerequisiteStatus() { - if (AppIntegrityService::arePrerequisitesMet()) - { - return "All Prerequisites met"; - } - else - { - $unmet = AppIntegrityService::getUnmetPrerequisites(); - $unmetNames = array_map(function($o) { - return (string)($o->GetName()); - }, $unmet); - return "Missing Prerequisites: ".json_encode(array_values($unmetNames)); - } + public static function getPrerequisiteStatus() + { + if (AppIntegrityService::arePrerequisitesMet()) { + return 'All Prerequisites met'; + } else { + $unmet = AppIntegrityService::getUnmetPrerequisites(); + $unmetNames = array_map(function ($o) { + return (string) $o->GetName(); + }, $unmet); + + return 'Missing Prerequisites: '.json_encode(array_values($unmetNames)); + } } public function reportIssue($data) @@ -86,23 +81,23 @@ public function reportIssue($data) $headers = []; $headers[] = 'Content-type: application/json'; - $issueDescription = $data->issueDescription . "\r\n\r\n\r\n" . - "Collected Value Title | Data \r\n" . - "----------------------|----------------\r\n" . - 'Page Name |' . $data->pageName . "\r\n" . - 'Screen Size |' . $data->screenSize->height . 'x' . $data->screenSize->width . "\r\n" . - 'Window Size |' . $data->windowSize->height . 'x' . $data->windowSize->width . "\r\n" . - 'Page Size |' . $data->pageSize->height . 'x' . $data->pageSize->width . "\r\n" . - 'Platform Information | ' . php_uname($mode = 'a') . "\r\n" . - 'PHP Version | ' . phpversion() . "\r\n" . - 'SQL Version | ' . self::getDBServerVersion() . "\r\n" . - 'ChurchCRM Version |' . $_SESSION['sSoftwareInstalledVersion'] . "\r\n" . - 'Reporting Browser |' . $_SERVER['HTTP_USER_AGENT'] . "\r\n". - 'Prerequisite Status |' . self::getPrerequisiteStatus()."\r\n". - 'Integrity check status |' . file_get_contents(SystemURLs::getDocumentRoot() . '/integrityCheck.json')."\r\n"; + $issueDescription = $data->issueDescription."\r\n\r\n\r\n". + "Collected Value Title | Data \r\n". + "----------------------|----------------\r\n". + 'Page Name |'.$data->pageName."\r\n". + 'Screen Size |'.$data->screenSize->height.'x'.$data->screenSize->width."\r\n". + 'Window Size |'.$data->windowSize->height.'x'.$data->windowSize->width."\r\n". + 'Page Size |'.$data->pageSize->height.'x'.$data->pageSize->width."\r\n". + 'Platform Information | '.php_uname($mode = 'a')."\r\n". + 'PHP Version | '.phpversion()."\r\n". + 'SQL Version | '.self::getDBServerVersion()."\r\n". + 'ChurchCRM Version |'.$_SESSION['sSoftwareInstalledVersion']."\r\n". + 'Reporting Browser |'.$_SERVER['HTTP_USER_AGENT']."\r\n". + 'Prerequisite Status |'.self::getPrerequisiteStatus()."\r\n". + 'Integrity check status |'.file_get_contents(SystemURLs::getDocumentRoot().'/integrityCheck.json')."\r\n"; if (function_exists('apache_get_modules')) { - $issueDescription .= 'Apache Modules |' . implode(',', apache_get_modules()); + $issueDescription .= 'Apache Modules |'.implode(',', apache_get_modules()); } $postdata = new \stdClass(); @@ -127,117 +122,109 @@ public function reportIssue($data) private static function IsTimerThresholdExceeded(string $LastTime, int $ThresholdHours) { - if (empty($LastTime)) { - return true; - } - $tz = new \DateTimeZone(SystemConfig::getValue('sTimeZone')); - $now = new \DateTime("now", $tz); //get the current time - $previous = \DateTime::createFromFormat(SystemConfig::getValue('sDateFilenameFormat'),$LastTime, $tz); // get a DateTime object for the last time a backup was done. - if ($previous === false) - { - return true; - } - $diff = abs($now->getTimestamp() - $previous->getTimestamp()) / 60 / 60 ; - return $diff >= $ThresholdHours; + if (empty($LastTime)) { + return true; + } + $tz = new \DateTimeZone(SystemConfig::getValue('sTimeZone')); + $now = new \DateTime('now', $tz); //get the current time + $previous = \DateTime::createFromFormat(SystemConfig::getValue('sDateFilenameFormat'), $LastTime, $tz); // get a DateTime object for the last time a backup was done. + if ($previous === false) { + return true; + } + $diff = abs($now->getTimestamp() - $previous->getTimestamp()) / 60 / 60; + + return $diff >= $ThresholdHours; } public static function runTimerJobs() { - LoggerUtils::getAppLogger()->debug("Starting background job processing"); + LoggerUtils::getAppLogger()->debug('Starting background job processing'); //start the external backup timer job if (SystemConfig::getBooleanValue('bEnableExternalBackupTarget') && SystemConfig::getValue('sExternalBackupAutoInterval') > 0) { //if remote backups are enabled, and the interval is greater than zero - try { - if (self::IsTimerThresholdExceeded(SystemConfig::getValue('sLastBackupTimeStamp'), SystemConfig::getValue('sExternalBackupAutoInterval'))) { - // if there was no previous backup, or if the interval suggests we do a backup now. - LoggerUtils::getAppLogger()->info("Starting a backup job. Last backup run: ".SystemConfig::getValue('sLastBackupTimeStamp')); - $BaseName = preg_replace('/[^a-zA-Z0-9\-_]/','', SystemConfig::getValue('sChurchName')). "-" . date(SystemConfig::getValue("sDateFilenameFormat")); - $Backup = new BackupJob($BaseName, BackupType::FullBackup, SystemConfig::getValue('bBackupExtraneousImages'),false,''); - $Backup->Execute(); - $Backup->CopyToWebDAV(SystemConfig::getValue('sExternalBackupEndpoint'), SystemConfig::getValue('sExternalBackupUsername'), SystemConfig::getValue('sExternalBackupPassword')); - $now = new \DateTime(); // update the LastBackupTimeStamp. - SystemConfig::setValue('sLastBackupTimeStamp', $now->format(SystemConfig::getValue('sDateFilenameFormat'))); - LoggerUtils::getAppLogger()->info("Backup job successful"); - } - else { - LoggerUtils::getAppLogger()->info("Not starting a backup job. Last backup run: ".SystemConfig::getValue('sLastBackupTimeStamp')."."); + try { + if (self::IsTimerThresholdExceeded(SystemConfig::getValue('sLastBackupTimeStamp'), SystemConfig::getValue('sExternalBackupAutoInterval'))) { + // if there was no previous backup, or if the interval suggests we do a backup now. + LoggerUtils::getAppLogger()->info('Starting a backup job. Last backup run: '.SystemConfig::getValue('sLastBackupTimeStamp')); + $BaseName = preg_replace('/[^a-zA-Z0-9\-_]/', '', SystemConfig::getValue('sChurchName')).'-'.date(SystemConfig::getValue('sDateFilenameFormat')); + $Backup = new BackupJob($BaseName, BackupType::FullBackup, SystemConfig::getValue('bBackupExtraneousImages'), false, ''); + $Backup->Execute(); + $Backup->CopyToWebDAV(SystemConfig::getValue('sExternalBackupEndpoint'), SystemConfig::getValue('sExternalBackupUsername'), SystemConfig::getValue('sExternalBackupPassword')); + $now = new \DateTime(); // update the LastBackupTimeStamp. + SystemConfig::setValue('sLastBackupTimeStamp', $now->format(SystemConfig::getValue('sDateFilenameFormat'))); + LoggerUtils::getAppLogger()->info('Backup job successful'); + } else { + LoggerUtils::getAppLogger()->info('Not starting a backup job. Last backup run: '.SystemConfig::getValue('sLastBackupTimeStamp').'.'); + } + } catch (\Exception $exc) { + // an error in the auto-backup shouldn't prevent the page from loading... + LoggerUtils::getAppLogger()->warning('Failure executing backup job: '.$exc->getMessage()); } - } catch (\Exception $exc) { - // an error in the auto-backup shouldn't prevent the page from loading... - LoggerUtils::getAppLogger()->warning("Failure executing backup job: ". $exc->getMessage() ); - } } if (SystemConfig::getBooleanValue('bEnableIntegrityCheck') && SystemConfig::getValue('iIntegrityCheckInterval') > 0) { - if (self::IsTimerThresholdExceeded(SystemConfig::getValue('sLastIntegrityCheckTimeStamp'),SystemConfig::getValue('iIntegrityCheckInterval'))) { + if (self::IsTimerThresholdExceeded(SystemConfig::getValue('sLastIntegrityCheckTimeStamp'), SystemConfig::getValue('iIntegrityCheckInterval'))) { // if there was no integrity check, or if the interval suggests we do one now. - LoggerUtils::getAppLogger()->info("Starting application integrity check"); - $integrityCheckFile = SystemURLs::getDocumentRoot() . '/integrityCheck.json'; + LoggerUtils::getAppLogger()->info('Starting application integrity check'); + $integrityCheckFile = SystemURLs::getDocumentRoot().'/integrityCheck.json'; $appIntegrity = AppIntegrityService::verifyApplicationIntegrity(); file_put_contents($integrityCheckFile, json_encode($appIntegrity)); $now = new \DateTime(); // update the LastBackupTimeStamp. SystemConfig::setValue('sLastIntegrityCheckTimeStamp', $now->format(SystemConfig::getValue('sDateFilenameFormat'))); - if ($appIntegrity['status'] == 'success') - { - LoggerUtils::getAppLogger()->info("Application integrity check passed"); - } - else - { - LoggerUtils::getAppLogger()->warning("Application integrity check failed: ".$appIntegrity['message']); + if ($appIntegrity['status'] == 'success') { + LoggerUtils::getAppLogger()->info('Application integrity check passed'); + } else { + LoggerUtils::getAppLogger()->warning('Application integrity check failed: '.$appIntegrity['message']); } + } else { + LoggerUtils::getAppLogger()->debug('Not starting application integrity check. Last application integrity check run: '.SystemConfig::getValue('sLastIntegrityCheckTimeStamp')); } - else { - LoggerUtils::getAppLogger()->debug("Not starting application integrity check. Last application integrity check run: ".SystemConfig::getValue('sLastIntegrityCheckTimeStamp')); - } } - if (self::IsTimerThresholdExceeded(SystemConfig::getValue('sLastSoftwareUpdateCheckTimeStamp'),SystemConfig::getValue('iSoftwareUpdateCheckInterval'))) { - // Since checking for updates from GitHub is a potentially expensive operation, - // Run this task as part of the "background jobs" API call - // Inside ChurchCRMReleaseManager, the restults are stored to the $_SESSION - ChurchCRMReleaseManager::checkForUpdates(); - $now = new \DateTime(); // update the LastBackupTimeStamp. - SystemConfig::setValue('sLastSoftwareUpdateCheckTimeStamp', $now->format(SystemConfig::getValue('sDateFilenameFormat'))); + if (self::IsTimerThresholdExceeded(SystemConfig::getValue('sLastSoftwareUpdateCheckTimeStamp'), SystemConfig::getValue('iSoftwareUpdateCheckInterval'))) { + // Since checking for updates from GitHub is a potentially expensive operation, + // Run this task as part of the "background jobs" API call + // Inside ChurchCRMReleaseManager, the restults are stored to the $_SESSION + ChurchCRMReleaseManager::checkForUpdates(); + $now = new \DateTime(); // update the LastBackupTimeStamp. + SystemConfig::setValue('sLastSoftwareUpdateCheckTimeStamp', $now->format(SystemConfig::getValue('sDateFilenameFormat'))); } - LoggerUtils::getAppLogger()->debug("Finished background job processing"); + LoggerUtils::getAppLogger()->debug('Finished background job processing'); } - - - - // Returns a file size limit in bytes based on the PHP upload_max_filesize + // Returns a file size limit in bytes based on the PHP upload_max_filesize // and post_max_size - public static function getMaxUploadFileSize($humanFormat=true) { - //select maximum upload size - $max_upload = SystemService::parse_size(ini_get('upload_max_filesize')); - //select post limit - $max_post = SystemService::parse_size(ini_get('post_max_size')); - //select memory limit - $memory_limit = SystemService::parse_size(ini_get('memory_limit')); - // return the smallest of them, this defines the real limit - if ($humanFormat) - { - return SystemService::human_filesize(min($max_upload, $max_post, $memory_limit)); - } - else - { - return min($max_upload, $max_post, $memory_limit); - } + public static function getMaxUploadFileSize($humanFormat = true) + { + //select maximum upload size + $max_upload = SystemService::parse_size(ini_get('upload_max_filesize')); + //select post limit + $max_post = SystemService::parse_size(ini_get('post_max_size')); + //select memory limit + $memory_limit = SystemService::parse_size(ini_get('memory_limit')); + // return the smallest of them, this defines the real limit + if ($humanFormat) { + return SystemService::human_filesize(min($max_upload, $max_post, $memory_limit)); + } else { + return min($max_upload, $max_post, $memory_limit); + } } - public static function parse_size($size) { - $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. - $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. - if ($unit) { - // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. - return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); - } - else { - return round($size); - } + public static function parse_size($size) + { + $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. + $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. + if ($unit) { + // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. + return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); + } else { + return round($size); + } } - static function human_filesize($bytes, $decimals = 2) { - $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB'); - $factor = floor((strlen($bytes) - 1) / 3); - return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor]; + public static function human_filesize($bytes, $decimals = 2) + { + $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + $factor = floor((strlen($bytes) - 1) / 3); + + return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)).@$size[$factor]; } } diff --git a/src/ChurchCRM/Service/TaskService.php b/src/ChurchCRM/Service/TaskService.php index 8c2bfdcab1..92de024da2 100644 --- a/src/ChurchCRM/Service/TaskService.php +++ b/src/ChurchCRM/Service/TaskService.php @@ -2,28 +2,28 @@ namespace ChurchCRM\Service; -use ChurchCRM\dto\Notification\UiNotification; use ChurchCRM\Authentication\AuthenticationManager; +use ChurchCRM\dto\Notification\UiNotification; +use ChurchCRM\Tasks\CheckExecutionTimeTask; use ChurchCRM\Tasks\CheckUploadSizeTask; use ChurchCRM\Tasks\ChurchAddress; use ChurchCRM\Tasks\ChurchNameTask; use ChurchCRM\Tasks\EmailTask; use ChurchCRM\Tasks\HttpsTask; use ChurchCRM\Tasks\IntegrityCheckTask; +use ChurchCRM\Tasks\iPreUpgradeTask; use ChurchCRM\Tasks\iTask; use ChurchCRM\Tasks\LatestReleaseTask; use ChurchCRM\Tasks\PersonClassificationDataCheck; use ChurchCRM\Tasks\PersonGenderDataCheck; use ChurchCRM\Tasks\PersonRoleDataCheck; -use ChurchCRM\Tasks\PrerequisiteCheckTask; -use ChurchCRM\Tasks\RegisteredTask; -use ChurchCRM\Tasks\UpdateFamilyCoordinatesTask; -use ChurchCRM\Tasks\CheckExecutionTimeTask; -use ChurchCRM\Tasks\iPreUpgradeTask; use ChurchCRM\Tasks\PHPPendingDeprecationVersionCheckTask; -use ChurchCRM\Tasks\UnsupportedDepositCheck; use ChurchCRM\Tasks\PHPZipArchiveCheckTask; +use ChurchCRM\Tasks\PrerequisiteCheckTask; +use ChurchCRM\Tasks\RegisteredTask; use ChurchCRM\Tasks\SecretsConfigurationCheckTask; +use ChurchCRM\Tasks\UnsupportedDepositCheck; +use ChurchCRM\Tasks\UpdateFamilyCoordinatesTask; class TaskService { @@ -53,11 +53,11 @@ public function __construct() new UnsupportedDepositCheck(), new SecretsConfigurationCheckTask(), new PHPPendingDeprecationVersionCheckTask(), - new PHPZipArchiveCheckTask() + new PHPZipArchiveCheckTask(), ]; $this->notificationClasses = [ - // new LatestReleaseTask() + // new LatestReleaseTask() ]; } @@ -67,11 +67,12 @@ public function getCurrentUserTasks() foreach ($this->taskClasses as $taskClass) { if ($taskClass->isActive() && (!$taskClass->isAdmin() || ($taskClass->isAdmin() && AuthenticationManager::GetCurrentUser()->isAdmin()))) { array_push($tasks, ['title' => $taskClass->getTitle(), - 'link' => $taskClass->getLink(), - 'admin' => $taskClass->isAdmin(), - 'desc' => $taskClass->getDesc()]); + 'link' => $taskClass->getLink(), + 'admin' => $taskClass->isAdmin(), + 'desc' => $taskClass->getDesc()]); } } + return $tasks; } @@ -80,17 +81,20 @@ public function getTaskNotifications() $tasks = []; foreach ($this->notificationClasses as $taskClass) { if ($taskClass->isActive()) { - array_push($tasks, - new UiNotification($taskClass->getTitle(), "wrench", $taskClass->getLink(), $taskClass->getDesc(), ($taskClass->isAdmin() ? "warning" : "info"), "12000", "bottom", "left")); + array_push( + $tasks, + new UiNotification($taskClass->getTitle(), 'wrench', $taskClass->getLink(), $taskClass->getDesc(), $taskClass->isAdmin() ? 'warning' : 'info', '12000', 'bottom', 'left') + ); } } + return $tasks; } - public function getActivePreUpgradeTasks() { - return array_filter($this->taskClasses, function($k) { + public function getActivePreUpgradeTasks() + { + return array_filter($this->taskClasses, function ($k) { return $k instanceof iPreUpgradeTask && $k->isActive(); }); } - } diff --git a/src/ChurchCRM/Service/TimelineService.php b/src/ChurchCRM/Service/TimelineService.php index 85f5a14968..70f24e6d20 100644 --- a/src/ChurchCRM/Service/TimelineService.php +++ b/src/ChurchCRM/Service/TimelineService.php @@ -2,12 +2,12 @@ namespace ChurchCRM\Service; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\EventAttendQuery; use ChurchCRM\Note; use ChurchCRM\NoteQuery; use ChurchCRM\Person; use ChurchCRM\PersonQuery; -use ChurchCRM\Authentication\AuthenticationManager; class TimelineService { @@ -47,13 +47,20 @@ private function eventsForPerson($personID) foreach ($eventsByPerson as $personEvent) { $event = $personEvent->getEvent(); if ($event != null) { - $item = $this->createTimeLineItem($event->getId(), 'cal', + $item = $this->createTimeLineItem( + $event->getId(), + 'cal', $event->getStart('Y-m-d h:i:s'), - $event->getTitle(), '', - $event->getDesc(), '', ''); + $event->getTitle(), + '', + $event->getDesc(), + '', + '' + ); $timeline[$item['key']] = $item; } } + return $timeline; } @@ -116,7 +123,7 @@ public function noteToTimelineItem($dbNote) $displayEditedBy = gettext('Unknown'); if ($dbNote->getDisplayEditedBy() == Person::SELF_REGISTER) { $displayEditedBy = gettext('Self Registration'); - } else if ($dbNote->getDisplayEditedBy() == Person::SELF_VERIFY) { + } elseif ($dbNote->getDisplayEditedBy() == Person::SELF_VERIFY) { $displayEditedBy = gettext('Self Verification'); } else { $editor = PersonQuery::create()->findPk($dbNote->getDisplayEditedBy()); @@ -124,9 +131,17 @@ public function noteToTimelineItem($dbNote) $displayEditedBy = $editor->getFullName(); } } - $item = $this->createTimeLineItem($dbNote->getId(), $dbNote->getType(), $dbNote->getDisplayEditedDate(), - $dbNote->getDisplayEditedDate("Y"),gettext('by') . ' ' . $displayEditedBy, '', $dbNote->getText(), - $dbNote->getEditLink(), $dbNote->getDeleteLink()); + $item = $this->createTimeLineItem( + $dbNote->getId(), + $dbNote->getType(), + $dbNote->getDisplayEditedDate(), + $dbNote->getDisplayEditedDate('Y'), + gettext('by').' '.$displayEditedBy, + '', + $dbNote->getText(), + $dbNote->getEditLink(), + $dbNote->getDeleteLink() + ); } return $item; diff --git a/src/ChurchCRM/Service/UpgradeService.php b/src/ChurchCRM/Service/UpgradeService.php index 73e56f7388..4432b6e8c1 100644 --- a/src/ChurchCRM/Service/UpgradeService.php +++ b/src/ChurchCRM/Service/UpgradeService.php @@ -3,81 +3,79 @@ * Created by PhpStorm. * User: georg * Date: 11/25/2017 - * Time: 1:28 PM + * Time: 1:28 PM. */ namespace ChurchCRM\Service; use ChurchCRM\dto\SystemURLs; -use ChurchCRM\Version; -use ChurchCRM\Utils\LoggerUtils; use ChurchCRM\SQLUtils; +use ChurchCRM\Utils\LoggerUtils; +use ChurchCRM\Version; use Propel\Runtime\Propel; class UpgradeService { - static public function upgradeDatabaseVersion() + public static function upgradeDatabaseVersion() { $logger = LoggerUtils::getAppLogger(); $db_version = SystemService::getDBVersion(); - $logger->info("Current Version: " .$db_version); + $logger->info('Current Version: '.$db_version); if ($db_version == $_SESSION['sSoftwareInstalledVersion']) { return true; } //the database isn't at the current version. Start the upgrade try { - $dbUpdatesFile = file_get_contents(SystemURLs::getDocumentRoot() . '/mysql/upgrade.json'); - $dbUpdates = json_decode($dbUpdatesFile, true); - $errorFlag = false; - $connection = Propel::getConnection(); - $upgradeScriptsExecuted = 0; - foreach ($dbUpdates as $dbUpdate) { - try { - if (in_array(SystemService::getDBVersion(), $dbUpdate['versions'])) { - $version = new Version(); - $version->setVersion($dbUpdate['dbVersion']); - $version->setUpdateStart(new \DateTime()); - $logger->info("New Version: " .$version->getVersion()); - foreach ($dbUpdate['scripts'] as $dbScript) { - $scriptName = SystemURLs::getDocumentRoot() . $dbScript; - $logger->info("Upgrade DB - " . $scriptName); - if (pathinfo($scriptName, PATHINFO_EXTENSION) == "sql") { - SQLUtils::sqlImport($scriptName, $connection); - } elseif (pathinfo($scriptName, PATHINFO_EXTENSION) == "php") { - require_once ($scriptName); - } - else { - throw new \Exception(gettext("Invalid upgrade file specified").": " . $scriptName); - } - } - if (!$errorFlag) { - $version->setUpdateEnd(new \DateTime()); - $version->save(); - sleep(2); - } - // increment the number of scripts executed. - // If no scripts run, then there is no supported upgrade path defined in the JSON file - $upgradeScriptsExecuted ++; - } + $dbUpdatesFile = file_get_contents(SystemURLs::getDocumentRoot().'/mysql/upgrade.json'); + $dbUpdates = json_decode($dbUpdatesFile, true); + $errorFlag = false; + $connection = Propel::getConnection(); + $upgradeScriptsExecuted = 0; + foreach ($dbUpdates as $dbUpdate) { + try { + if (in_array(SystemService::getDBVersion(), $dbUpdate['versions'])) { + $version = new Version(); + $version->setVersion($dbUpdate['dbVersion']); + $version->setUpdateStart(new \DateTime()); + $logger->info('New Version: '.$version->getVersion()); + foreach ($dbUpdate['scripts'] as $dbScript) { + $scriptName = SystemURLs::getDocumentRoot().$dbScript; + $logger->info('Upgrade DB - '.$scriptName); + if (pathinfo($scriptName, PATHINFO_EXTENSION) == 'sql') { + SQLUtils::sqlImport($scriptName, $connection); + } elseif (pathinfo($scriptName, PATHINFO_EXTENSION) == 'php') { + require_once $scriptName; + } else { + throw new \Exception(gettext('Invalid upgrade file specified').': '.$scriptName); + } + } + if (!$errorFlag) { + $version->setUpdateEnd(new \DateTime()); + $version->save(); + sleep(2); + } + // increment the number of scripts executed. + // If no scripts run, then there is no supported upgrade path defined in the JSON file + $upgradeScriptsExecuted++; + } + } catch (\Exception $exc) { + $logger->error(gettext('Failure executing upgrade script').': '.$scriptName.': '.$exc->getMessage()); + + throw $exc; + } } - catch (\Exception $exc) { - $logger->error(gettext("Failure executing upgrade script").": ".$scriptName.": ".$exc->getMessage()); - throw $exc; + if ($upgradeScriptsExecuted === 0) { + $logger->warning('No upgrade path for '.SystemService::getDBVersion().' to '.$_SESSION['sSoftwareInstalledVersion']); } - } - if( $upgradeScriptsExecuted === 0 ) { - $logger->warning("No upgrade path for " . SystemService::getDBVersion() . " to " . $_SESSION['sSoftwareInstalledVersion']); - } - // always rebuild the views - SQLUtils::sqlImport(SystemURLs::getDocumentRoot() . '/mysql/upgrade/rebuild_views.sql', $connection); + // always rebuild the views + SQLUtils::sqlImport(SystemURLs::getDocumentRoot().'/mysql/upgrade/rebuild_views.sql', $connection); - return true; - } - catch (\Exception $exc){ - $logger->error(gettext("Database upgrade failed").": " . $exc->getMessage()); - throw $exc; //allow the method requesting the upgrade to handle this failure also. + return true; + } catch (\Exception $exc) { + $logger->error(gettext('Database upgrade failed').': '.$exc->getMessage()); + + throw $exc; //allow the method requesting the upgrade to handle this failure also. } } - } diff --git a/src/ChurchCRM/Slim/Middleware/AuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/AuthMiddleware.php index b8b0029796..0713e3ff08 100644 --- a/src/ChurchCRM/Slim/Middleware/AuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/AuthMiddleware.php @@ -7,41 +7,42 @@ use Slim\Http\Request; use Slim\Http\Response; -class AuthMiddleware { - - public function __invoke( Request $request, Response $response, callable $next ) +class AuthMiddleware +{ + public function __invoke(Request $request, Response $response, callable $next) { - if (!$this->isPath( $request, "public")) { - $apiKey = $request->getHeader("x-api-key"); + if (!$this->isPath($request, 'public')) { + $apiKey = $request->getHeader('x-api-key'); if (!empty($apiKey)) { - $authenticationResult = AuthenticationManager::Authenticate(new APITokenAuthenticationRequest($apiKey[0])); - if (! $authenticationResult->isAuthenticated) { + if (!$authenticationResult->isAuthenticated) { AuthenticationManager::EndSession(true); + return $response->withStatus(401, gettext('No logged in user')); } } // validate the user session; however, do not update tLastOperation if the requested path is "/background" // since /background operations do not connotate user activity. - else if (AuthenticationManager::ValidateUserSessionIsActive(!$this->isPath( $request, "background"))) { + elseif (AuthenticationManager::ValidateUserSessionIsActive(!$this->isPath($request, 'background'))) { // User with an active browser session is still authenticated. // don't really need to do anything here... - } - else { + } else { return $response->withStatus(401, gettext('No logged in user')); } - return $next( $request, $response )->withHeader( "CRM_USER_ID", AuthenticationManager::GetCurrentUser()->getId()); + return $next($request, $response)->withHeader('CRM_USER_ID', AuthenticationManager::GetCurrentUser()->getId()); } - return $next( $request, $response ); + + return $next($request, $response); } - private function isPath(Request $request, $pathPart) { - $pathAry = explode("/", $request->getUri()->getPath()); + private function isPath(Request $request, $pathPart) + { + $pathAry = explode('/', $request->getUri()->getPath()); if (!empty($pathAry) && $pathAry[0] === $pathPart) { return true; } + return false; } - } diff --git a/src/ChurchCRM/Slim/Middleware/EventsMiddleware.php b/src/ChurchCRM/Slim/Middleware/EventsMiddleware.php index cbcd1ba889..556ee86f74 100644 --- a/src/ChurchCRM/Slim/Middleware/EventsMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/EventsMiddleware.php @@ -10,18 +10,19 @@ class EventsMiddleware { public function __invoke(Request $request, Response $response, callable $next) { - $eventId = $request->getAttribute("route")->getArgument("id"); + $eventId = $request->getAttribute('route')->getArgument('id'); if (empty(trim($eventId))) { - return $response->withStatus(400)->withJson(["message" => gettext("Missing event id")]); + return $response->withStatus(400)->withJson(['message' => gettext('Missing event id')]); } $event = EventQuery::Create() ->findPk($eventId); if (empty($event)) { - return $response->withStatus(404)->withJson(["message" => gettext("Event not found")]); + return $response->withStatus(404)->withJson(['message' => gettext('Event not found')]); } - $request = $request->withAttribute("event", $event); + $request = $request->withAttribute('event', $event); + return $next($request, $response); } } diff --git a/src/ChurchCRM/Slim/Middleware/MailChimpMiddleware.php b/src/ChurchCRM/Slim/Middleware/MailChimpMiddleware.php index 4a9e4833e1..7daca37589 100644 --- a/src/ChurchCRM/Slim/Middleware/MailChimpMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/MailChimpMiddleware.php @@ -6,17 +6,17 @@ use Slim\Http\Request; use Slim\Http\Response; -class MailChimpMiddleware { - - public function __invoke( Request $request, Response $response, callable $next ) +class MailChimpMiddleware +{ + public function __invoke(Request $request, Response $response, callable $next) { $mailchimpService = new MailChimpService(); - if (! $mailchimpService->isActive()) { - return $response->withStatus(412)->withJson(["message" => gettext('Mailchimp is not active')]); + if (!$mailchimpService->isActive()) { + return $response->withStatus(412)->withJson(['message' => gettext('Mailchimp is not active')]); } - $request = $request->withAttribute("mailchimpService", $mailchimpService); - return $next( $request, $response ); - } + $request = $request->withAttribute('mailchimpService', $mailchimpService); + return $next($request, $response); + } } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/AddEventsRoleAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/AddEventsRoleAuthMiddleware.php index 7359db77f8..874e00edd2 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/AddEventsRoleAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/AddEventsRoleAuthMiddleware.php @@ -2,14 +2,14 @@ namespace ChurchCRM\Slim\Middleware\Request\Auth; -class AddEventsRoleAuthMiddleware extends BaseAuthRoleMiddleware { - - function hasRole() +class AddEventsRoleAuthMiddleware extends BaseAuthRoleMiddleware +{ + public function hasRole() { return $this->user->isAddEvent(); } - function noRoleMessage() + public function noRoleMessage() { return gettext('User must have bAddEvent permissions'); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/AdminRoleAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/AdminRoleAuthMiddleware.php index bd29ae0954..6de8e796c9 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/AdminRoleAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/AdminRoleAuthMiddleware.php @@ -4,13 +4,12 @@ class AdminRoleAuthMiddleware extends BaseAuthRoleMiddleware { - - function hasRole() + public function hasRole() { return $this->user->isAdmin(); } - function noRoleMessage() + public function noRoleMessage() { return gettext('User must be an Admin'); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/BaseAuthRoleMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/BaseAuthRoleMiddleware.php index f5ee15e810..44ed1e07c6 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/BaseAuthRoleMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/BaseAuthRoleMiddleware.php @@ -9,9 +9,8 @@ abstract class BaseAuthRoleMiddleware { - /** - * @var User $user + * @var User */ protected $user; @@ -25,10 +24,11 @@ public function __invoke(Request $request, Response $response, callable $next) if (!$this->hasRole()) { return $response->withStatus(403, $this->noRoleMessage()); } + return $next($request, $response); } - abstract function hasRole(); + abstract public function hasRole(); - abstract function noRoleMessage(); + abstract public function noRoleMessage(); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/DeleteRecordRoleAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/DeleteRecordRoleAuthMiddleware.php index 8003ce2ee1..709dd94ebc 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/DeleteRecordRoleAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/DeleteRecordRoleAuthMiddleware.php @@ -2,14 +2,14 @@ namespace ChurchCRM\Slim\Middleware\Request\Auth; -class DeleteRecordRoleAuthMiddleware extends BaseAuthRoleMiddleware { - - function hasRole() +class DeleteRecordRoleAuthMiddleware extends BaseAuthRoleMiddleware +{ + public function hasRole() { return $this->user->isDeleteRecordsEnabled(); } - function noRoleMessage() + public function noRoleMessage() { return gettext('User must have Delete Records permission'); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/EditRecordsRoleAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/EditRecordsRoleAuthMiddleware.php index d5cc810834..a0030df4b2 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/EditRecordsRoleAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/EditRecordsRoleAuthMiddleware.php @@ -2,14 +2,14 @@ namespace ChurchCRM\Slim\Middleware\Request\Auth; -class EditRecordsRoleAuthMiddleware extends BaseAuthRoleMiddleware { - - function hasRole() +class EditRecordsRoleAuthMiddleware extends BaseAuthRoleMiddleware +{ + public function hasRole() { return $this->user->isEditRecordsEnabled(); } - function noRoleMessage() + public function noRoleMessage() { return gettext('User must have Edit Records permission'); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/FinanceRoleAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/FinanceRoleAuthMiddleware.php index 739b8c41b1..dc87643fec 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/FinanceRoleAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/FinanceRoleAuthMiddleware.php @@ -2,14 +2,14 @@ namespace ChurchCRM\Slim\Middleware\Request\Auth; -class FinanceRoleAuthMiddleware extends BaseAuthRoleMiddleware { - - function hasRole() +class FinanceRoleAuthMiddleware extends BaseAuthRoleMiddleware +{ + public function hasRole() { return $this->user->isFinanceEnabled(); } - function noRoleMessage() + public function noRoleMessage() { return gettext('User must have Finance permission'); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/ManageGroupRoleAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/ManageGroupRoleAuthMiddleware.php index 58e278d2f4..5eccbe76d0 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/ManageGroupRoleAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/ManageGroupRoleAuthMiddleware.php @@ -2,14 +2,14 @@ namespace ChurchCRM\Slim\Middleware\Request\Auth; -class ManageGroupRoleAuthMiddleware extends BaseAuthRoleMiddleware { - - function hasRole() +class ManageGroupRoleAuthMiddleware extends BaseAuthRoleMiddleware +{ + public function hasRole() { return $this->user->isManageGroupsEnabled(); } - function noRoleMessage() + public function noRoleMessage() { return gettext('User must have Manage Groups permission'); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/MenuOptionsRoleAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/MenuOptionsRoleAuthMiddleware.php index 5070ce8a81..e03dbe22cb 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/MenuOptionsRoleAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/MenuOptionsRoleAuthMiddleware.php @@ -2,14 +2,14 @@ namespace ChurchCRM\Slim\Middleware\Request\Auth; -class MenuOptionsRoleAuthMiddleware extends BaseAuthRoleMiddleware { - - function hasRole() +class MenuOptionsRoleAuthMiddleware extends BaseAuthRoleMiddleware +{ + public function hasRole() { return $this->user->isMenuOptionsEnabled(); } - function noRoleMessage() + public function noRoleMessage() { return gettext('User must have MenuOptions permission'); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/FamilyAPIMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/FamilyAPIMiddleware.php index 85c4f8fedc..93dc95c3fd 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/FamilyAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/FamilyAPIMiddleware.php @@ -10,19 +10,18 @@ class FamilyAPIMiddleware { public function __invoke(Request $request, Response $response, callable $next) { - - $familyId = $request->getAttribute("route")->getArgument("familyId"); + $familyId = $request->getAttribute('route')->getArgument('familyId'); if (empty(trim($familyId))) { - return $response->withStatus(412, gettext("Missing"). " FamilyId"); + return $response->withStatus(412, gettext('Missing').' FamilyId'); } $family = FamilyQuery::create()->findPk($familyId); if (empty($family)) { - return $response->withStatus(412, "FamilyId: " . $familyId . " ". gettext("not found")); + return $response->withStatus(412, 'FamilyId: '.$familyId.' '.gettext('not found')); } - $request = $request->withAttribute("family", $family); + $request = $request->withAttribute('family', $family); + return $next($request, $response); } - } diff --git a/src/ChurchCRM/Slim/Middleware/Request/GroupAPIMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/GroupAPIMiddleware.php index fb70951b74..7adb3bc6df 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/GroupAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/GroupAPIMiddleware.php @@ -10,19 +10,18 @@ class GroupAPIMiddleware { public function __invoke(Request $request, Response $response, callable $next) { - - $groupId = $request->getAttribute("route")->getArgument("groupId"); + $groupId = $request->getAttribute('route')->getArgument('groupId'); if (empty(trim($groupId))) { - return $response->withStatus(412, gettext("Missing"). " GroupId"); + return $response->withStatus(412, gettext('Missing').' GroupId'); } $group = GroupQuery::create()->findPk($groupId); if (empty($group)) { - return $response->withStatus(412, "GroupId: " . $groupId . " ". gettext("not found")); + return $response->withStatus(412, 'GroupId: '.$groupId.' '.gettext('not found')); } - $request = $request->withAttribute("group", $group); + $request = $request->withAttribute('group', $group); + return $next($request, $response); } - } diff --git a/src/ChurchCRM/Slim/Middleware/Request/PersonAPIMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/PersonAPIMiddleware.php index f55c033e9e..d23bec915c 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/PersonAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/PersonAPIMiddleware.php @@ -10,19 +10,18 @@ class PersonAPIMiddleware { public function __invoke(Request $request, Response $response, callable $next) { - - $personId = $request->getAttribute("route")->getArgument("personId"); + $personId = $request->getAttribute('route')->getArgument('personId'); if (empty(trim($personId))) { - return $response->withStatus(412, gettext("Missing"). " PersonId"); + return $response->withStatus(412, gettext('Missing').' PersonId'); } $person = PersonQuery::create()->findPk($personId); if (empty($person)) { - return $response->withStatus(412, "PersonId : " . $personId . " ". gettext("not found")); + return $response->withStatus(412, 'PersonId : '.$personId.' '.gettext('not found')); } - $request = $request->withAttribute("person", $person); + $request = $request->withAttribute('person', $person); + return $next($request, $response); } - } diff --git a/src/ChurchCRM/Slim/Middleware/Request/PropertyAPIMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/PropertyAPIMiddleware.php index fe175f8927..226f40cdfe 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/PropertyAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/PropertyAPIMiddleware.php @@ -11,31 +11,31 @@ class PropertyAPIMiddleware { protected $type; - public function __construct(String $type) + public function __construct(string $type) { $this->type = $type; } public function __invoke(Request $request, Response $response, callable $next) { - - $propertyId = $request->getAttribute("route")->getArgument("propertyId"); + $propertyId = $request->getAttribute('route')->getArgument('propertyId'); if (empty(trim($propertyId))) { - return $response->withStatus(412, gettext("Missing"). " PropertyId"); + return $response->withStatus(412, gettext('Missing').' PropertyId'); } $property = PropertyQuery::create()->findPk($propertyId); if (empty($property)) { - LoggerUtils::getAppLogger()->debug("Pro Type is " . $property->getPropertyType()->getPrtClass() . " Looking for " . $this->type); - return $response->withStatus(412, "PropertyId : " . $propertyId . " ". gettext("not found")); - } else if ($property->getPropertyType()->getPrtClass() != $this->type) { - return $response->withStatus(500, "PropertyId : " . $propertyId . " ". gettext(" has a type mismatch")); + LoggerUtils::getAppLogger()->debug('Pro Type is '.$property->getPropertyType()->getPrtClass().' Looking for '.$this->type); + + return $response->withStatus(412, 'PropertyId : '.$propertyId.' '.gettext('not found')); + } elseif ($property->getPropertyType()->getPrtClass() != $this->type) { + return $response->withStatus(500, 'PropertyId : '.$propertyId.' '.gettext(' has a type mismatch')); } - $request = $request->withAttribute("property", $property); + $request = $request->withAttribute('property', $property); + return $next($request, $response); } - } diff --git a/src/ChurchCRM/Slim/Middleware/Request/PublicCalendarAPIMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/PublicCalendarAPIMiddleware.php index f720405ef4..2a6c50a9e9 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/PublicCalendarAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/PublicCalendarAPIMiddleware.php @@ -17,25 +17,26 @@ class PublicCalendarAPIMiddleware { public function __invoke(Request $request, Response $response, callable $next) { - if (!SystemConfig::getBooleanValue("bEnableExternalCalendarAPI")) { - return $response->withStatus(403, gettext("External Calendar API is disabled")); + if (!SystemConfig::getBooleanValue('bEnableExternalCalendarAPI')) { + return $response->withStatus(403, gettext('External Calendar API is disabled')); } - $CAT = $request->getAttribute("route")->getArgument("CalendarAccessToken"); + $CAT = $request->getAttribute('route')->getArgument('CalendarAccessToken'); if (empty(trim($CAT))) { - return $response->withStatus(400)->withJson(["message" => gettext("Missing calendar access token")]); + return $response->withStatus(400)->withJson(['message' => gettext('Missing calendar access token')]); } $calendar = CalendarQuery::create() ->filterByAccessToken($CAT) ->findOne(); if (empty($calendar)) { - return $response->withStatus(404)->withJson(["message" => gettext("Calendar access token not found")]); + return $response->withStatus(404)->withJson(['message' => gettext('Calendar access token not found')]); } - $request = $request->withAttribute("calendar", $calendar); + $request = $request->withAttribute('calendar', $calendar); $events = $this->getEvents($request, $calendar); - $request = $request->withAttribute("events", $events); + $request = $request->withAttribute('events', $events); + return $next($request, $response); } @@ -43,7 +44,7 @@ private function getEvents(Request $request, Calendar $calendar) { $params = $request->getQueryParams(); if (isset($params['start'])) { - $start_date = DateTime::createFromFormat("Y-m-d", $params['start']); + $start_date = DateTime::createFromFormat('Y-m-d', $params['start']); } else { $start_date = new DateTime(); } @@ -60,7 +61,7 @@ private function getEvents(Request $request, Calendar $calendar) $events->filterByStart($start_date, Criteria::GREATER_EQUAL); } - if(array_key_exists('max',$params)) { + if (array_key_exists('max', $params)) { $max_events = InputUtils::FilterInt($params['max']); $events->limit($max_events); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Setting/BaseAuthSettingMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Setting/BaseAuthSettingMiddleware.php index 1066744ed5..53bf7c08e3 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Setting/BaseAuthSettingMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Setting/BaseAuthSettingMiddleware.php @@ -8,15 +8,14 @@ abstract class BaseAuthSettingMiddleware { - public function __invoke(Request $request, Response $response, callable $next) { if (!SystemConfig::getBooleanValue($this->getSettingName())) { - return $response->withStatus(403, $this->getSettingName() . " " . gettext("is disabled")); + return $response->withStatus(403, $this->getSettingName().' '.gettext('is disabled')); } return $next($request, $response); } - abstract function getSettingName(); + abstract public function getSettingName(); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Setting/PublicRegistrationAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Setting/PublicRegistrationAuthMiddleware.php index 149ceea3cf..9a9dadade9 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Setting/PublicRegistrationAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Setting/PublicRegistrationAuthMiddleware.php @@ -2,12 +2,10 @@ namespace ChurchCRM\Slim\Middleware\Request\Setting; - class PublicRegistrationAuthMiddleware extends BaseAuthSettingMiddleware { - - function getSettingName() + public function getSettingName() { - return "bEnableSelfRegistration"; + return 'bEnableSelfRegistration'; } -} \ No newline at end of file +} diff --git a/src/ChurchCRM/Slim/Middleware/Request/UserAPIMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/UserAPIMiddleware.php index 2a366e9b20..2571e98c4f 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/UserAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/UserAPIMiddleware.php @@ -11,10 +11,9 @@ class UserAPIMiddleware { public function __invoke(Request $request, Response $response, callable $next) { - - $userId = $request->getAttribute("route")->getArgument("userId"); + $userId = $request->getAttribute('route')->getArgument('userId'); if (empty(trim($userId))) { - return $response->withStatus(412, gettext("Missing"). " UserId"); + return $response->withStatus(412, gettext('Missing').' UserId'); } $loggedInUser = AuthenticationManager::GetCurrentUser(); @@ -23,14 +22,14 @@ public function __invoke(Request $request, Response $response, callable $next) } elseif ($loggedInUser->isAdmin()) { $user = UserQuery::create()->findPk($userId); if (empty($user)) { - return $response->withStatus(412, "User : " . $userId . " ". gettext("not found")); + return $response->withStatus(412, 'User : '.$userId.' '.gettext('not found')); } } else { return $response->withStatus(401); } - $request = $request->withAttribute("user", $user); + $request = $request->withAttribute('user', $user); + return $next($request, $response); } - } diff --git a/src/ChurchCRM/Slim/Middleware/VersionMiddleware.php b/src/ChurchCRM/Slim/Middleware/VersionMiddleware.php index 5f6dacd025..5828737c19 100644 --- a/src/ChurchCRM/Slim/Middleware/VersionMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/VersionMiddleware.php @@ -6,10 +6,10 @@ use Slim\Http\Request; use Slim\Http\Response; -class VersionMiddleware { - - public function __invoke( Request $request, Response $response, callable $next ) - { - return $next( $request, $response )->withHeader( "CRM_VERSION", SystemService::getInstalledVersion()); - } +class VersionMiddleware +{ + public function __invoke(Request $request, Response $response, callable $next) + { + return $next($request, $response)->withHeader('CRM_VERSION', SystemService::getInstalledVersion()); + } } diff --git a/src/ChurchCRM/SystemCalendars/AnniversariesCalendar.php b/src/ChurchCRM/SystemCalendars/AnniversariesCalendar.php index f3cab4912c..68db09751a 100644 --- a/src/ChurchCRM/SystemCalendars/AnniversariesCalendar.php +++ b/src/ChurchCRM/SystemCalendars/AnniversariesCalendar.php @@ -2,67 +2,78 @@ namespace ChurchCRM\SystemCalendars; -use ChurchCRM\Interfaces\SystemCalendar; -use ChurchCRM\FamilyQuery; -use Propel\Runtime\Collection\ObjectCollection; use ChurchCRM\Event; -use ChurchCRM\Calendar; +use ChurchCRM\FamilyQuery; +use ChurchCRM\Interfaces\SystemCalendar; use Propel\Runtime\ActiveQuery\Criteria; +use Propel\Runtime\Collection\ObjectCollection; + +class AnniversariesCalendar implements SystemCalendar +{ + public static function isAvailable() + { + return true; + } + + public function getAccessToken() + { + return false; + } + + public function getBackgroundColor() + { + return '000000'; + } + + public function getForegroundColor() + { + return 'FFFFFF'; + } -class AnniversariesCalendar implements SystemCalendar { - - public static function isAvailable() { - return true; - } - - public function getAccessToken() { - return false; - } + public function getId() + { + return 1; + } + + public function getName() + { + return gettext('Anniversaries'); + } - public function getBackgroundColor() { - return "000000"; - } - - public function getForegroundColor() { - return "FFFFFF"; - } + public function getEvents($start, $end) + { + $families = FamilyQuery::create() + ->filterByWeddingdate('', Criteria::NOT_EQUAL) + ->find(); + + return $this->familyCollectionToEvents($families); + } + + public function getEventById($Id) + { + $families = FamilyQuery::create() + ->filterByWeddingdate('', Criteria::NOT_EQUAL) + ->filterById($Id) + ->find(); + + return $this->familyCollectionToEvents($families); + } - public function getId() { - return 1; - } + private function familyCollectionToEvents(ObjectCollection $Families) + { + $events = new ObjectCollection(); + $events->setModel('ChurchCRM\\Event'); + foreach ($Families as $family) { + $anniversary = new Event(); + $anniversary->setId($family->getId()); + $anniversary->setEditable(false); + $anniversary->setTitle(gettext('Anniversary').': '.$family->getFamilyString()); + $year = date('Y'); + $anniversary->setStart($year.'-'.$family->getWeddingMonth().'-'.$family->getWeddingDay()); + $anniversary->setURL($family->getViewURI()); + $events->push($anniversary); + } - public function getName() { - return gettext("Anniversaries"); - } - - public function getEvents($start,$end) { - $families = FamilyQuery::create() - ->filterByWeddingdate('', Criteria::NOT_EQUAL) - ->find(); - return $this->familyCollectionToEvents($families); - } - - public function getEventById($Id) { - $families = FamilyQuery::create() - ->filterByWeddingdate('', Criteria::NOT_EQUAL) - ->filterById($Id) - ->find(); - return $this->familyCollectionToEvents($families); - } - - private function familyCollectionToEvents(ObjectCollection $Families){ - $events = new ObjectCollection(); - $events->setModel("ChurchCRM\\Event"); - Foreach($Families as $family) { - $anniversary = new Event(); - $anniversary->setId($family->getId()); - $anniversary->setEditable(false); - $anniversary->setTitle(gettext("Anniversary").": ".$family->getFamilyString()); - $year = date('Y'); - $anniversary->setStart($year.'-'.$family->getWeddingMonth().'-'.$family->getWeddingDay()); - $anniversary->setURL($family->getViewURI()); - $events->push($anniversary); + return $events; } - return $events; - } } diff --git a/src/ChurchCRM/SystemCalendars/BirthdaysCalendar.php b/src/ChurchCRM/SystemCalendars/BirthdaysCalendar.php index ca196a9623..4b3b5aa318 100644 --- a/src/ChurchCRM/SystemCalendars/BirthdaysCalendar.php +++ b/src/ChurchCRM/SystemCalendars/BirthdaysCalendar.php @@ -2,68 +2,79 @@ namespace ChurchCRM\SystemCalendars; +use ChurchCRM\Event; use ChurchCRM\Interfaces\SystemCalendar; use ChurchCRM\PersonQuery; -use Propel\Runtime\Collection\ObjectCollection; -use ChurchCRM\Event; -use ChurchCRM\Calendar; use Propel\Runtime\ActiveQuery\Criteria; +use Propel\Runtime\Collection\ObjectCollection; + +class BirthdaysCalendar implements SystemCalendar +{ + public static function isAvailable() + { + return true; + } + + public function getAccessToken() + { + return false; + } + + public function getBackgroundColor() + { + return '0000FF'; + } -class BirthdaysCalendar implements SystemCalendar { - - public static function isAvailable() { - return true; - } - - public function getAccessToken() { - return false; - } + public function getForegroundColor() + { + return 'FFFFFF'; + } + + public function getId() + { + return 0; + } + + public function getName() + { + return gettext('Birthdays'); + } - public function getBackgroundColor() { - return "0000FF"; - } - - public function getForegroundColor() { - return "FFFFFF"; - } + public function getEvents($start, $end) + { + $people = PersonQuery::create() + ->filterByBirthDay('', Criteria::NOT_EQUAL) + ->find(); + + return $this->peopleCollectionToEvents($people); + } + + public function getEventById($Id) + { + $people = PersonQuery::create() + ->filterByBirthDay('', Criteria::NOT_EQUAL) + ->filterById($Id) + ->find(); + + return $this->peopleCollectionToEvents($people); + } - public function getId() { - return 0; - } + private function peopleCollectionToEvents(ObjectCollection $People) + { + $events = new ObjectCollection(); + $events->setModel('ChurchCRM\\Event'); + foreach ($People as $person) { + $birthday = new Event(); + $birthday->setId($person->getId()); + $birthday->setEditable(false); + $year = date('Y'); + $birthday->setStart($year.'-'.$person->getBirthMonth().'-'.$person->getBirthDay()); + $age = $person->getAge($birthday->getStart()); + $birthday->setTitle(gettext('Birthday').': '.$person->getFullName().($age ? ' ('.$age.')' : '')); + $birthday->setURL($person->getViewURI()); + $events->push($birthday); + } - public function getName() { - return gettext("Birthdays"); - } - - public function getEvents($start,$end) { - $people = PersonQuery::create() - ->filterByBirthDay('', Criteria::NOT_EQUAL) - ->find(); - return $this->peopleCollectionToEvents($people); - } - - public function getEventById($Id) { - $people = PersonQuery::create() - ->filterByBirthDay('', Criteria::NOT_EQUAL) - ->filterById($Id) - ->find(); - return $this->peopleCollectionToEvents($people); - } - - private function peopleCollectionToEvents(ObjectCollection $People) { - $events = new ObjectCollection(); - $events->setModel("ChurchCRM\\Event"); - Foreach($People as $person) { - $birthday = new Event(); - $birthday->setId($person->getId()); - $birthday->setEditable(false); - $year = date('Y'); - $birthday->setStart($year.'-'.$person->getBirthMonth().'-'.$person->getBirthDay()); - $age = $person->getAge($birthday->getStart()); - $birthday->setTitle(gettext("Birthday") . ": " . $person->getFullName() . ( $age ? " (".$age.")" : '' )); - $birthday->setURL($person->getViewURI()); - $events->push($birthday); + return $events; } - return $events; - } } diff --git a/src/ChurchCRM/SystemCalendars/HolidayCalendar.php b/src/ChurchCRM/SystemCalendars/HolidayCalendar.php index f6167be456..5365e8e7cf 100644 --- a/src/ChurchCRM/SystemCalendars/HolidayCalendar.php +++ b/src/ChurchCRM/SystemCalendars/HolidayCalendar.php @@ -2,74 +2,79 @@ namespace ChurchCRM\SystemCalendars; +use ChurchCRM\data\Countries; +use ChurchCRM\dto\SystemConfig; +use ChurchCRM\Event; use ChurchCRM\Interfaces\SystemCalendar; -use ChurchCRM\FamilyQuery; use Propel\Runtime\Collection\ObjectCollection; -use ChurchCRM\Event; -use ChurchCRM\Calendar; -use Yasumi\Yasumi; use Yasumi\Holiday; -use Propel\Runtime\ActiveQuery\Criteria; -use ChurchCRM\data\Countries; -use ChurchCRM\data\Country; -use ChurchCRM\dto\SystemConfig; +use Yasumi\Yasumi; -class HolidayCalendar implements SystemCalendar { - - public static function isAvailable() { - $systemCountry = Countries::getCountryByName(SystemConfig::getValue("sChurchCountry")); - if (!empty($systemCountry)) +class HolidayCalendar implements SystemCalendar +{ + public static function isAvailable() { - return $systemCountry->getCountryNameYasumi() !== null; + $systemCountry = Countries::getCountryByName(SystemConfig::getValue('sChurchCountry')); + if (!empty($systemCountry)) { + return $systemCountry->getCountryNameYasumi() !== null; + } } - - } - - public function getAccessToken() { - return false; - } - public function getBackgroundColor() { - return "6dfff5"; - } - - public function getForegroundColor() { - return "000000"; - } + public function getAccessToken() + { + return false; + } + + public function getBackgroundColor() + { + return '6dfff5'; + } + + public function getForegroundColor() + { + return '000000'; + } - public function getId() { - return 2; - } + public function getId() + { + return 2; + } + + public function getName() + { + return gettext('Holidays'); + } + + public function getEvents($start, $end) + { + $Country = Countries::getCountryByName(SystemConfig::getValue('sChurchCountry')); + $year = date('Y'); + $holidays = Yasumi::create($Country->getCountryNameYasumi(), $year); + $events = new ObjectCollection(); + $events->setModel('ChurchCRM\\Event'); + + foreach ($holidays as $holiday) { + $event = $this->yasumiHolidayToEvent($holiday); + $events->push($event); + } + + return $events; + } + + public function getEventById($Id) + { + return false; + } + + private function yasumiHolidayToEvent(Holiday $holiday) + { + $id = crc32($holiday->getName().$holiday->getTimestamp()); + $holidayEvent = new Event(); + $holidayEvent->setId($id); + $holidayEvent->setEditable(false); + $holidayEvent->setTitle($holiday->getName()); + $holidayEvent->setStart($holiday->getTimestamp()); - public function getName() { - return gettext("Holidays"); - } - - public function getEvents($start,$end) { - $Country = Countries::getCountryByName(SystemConfig::getValue("sChurchCountry")); - $year = date('Y'); - $holidays = Yasumi::create($Country->getCountryNameYasumi(),$year); - $events = new ObjectCollection(); - $events->setModel("ChurchCRM\\Event"); - - foreach ($holidays as $holiday){ - $event = $this->yasumiHolidayToEvent($holiday); - $events->push($event); + return $holidayEvent; } - return $events; - } - - public function getEventById($Id) { - return false; - } - - private function yasumiHolidayToEvent(Holiday $holiday){ - $id = crc32($holiday->getName().$holiday->getTimestamp()); - $holidayEvent = new Event(); - $holidayEvent->setId($id); - $holidayEvent->setEditable(false); - $holidayEvent->setTitle($holiday->getName()); - $holidayEvent->setStart($holiday->getTimestamp()); - return $holidayEvent; - } } diff --git a/src/ChurchCRM/SystemCalendars/UnpinnedEvents.php b/src/ChurchCRM/SystemCalendars/UnpinnedEvents.php index bc10a3f070..6f86a43509 100644 --- a/src/ChurchCRM/SystemCalendars/UnpinnedEvents.php +++ b/src/ChurchCRM/SystemCalendars/UnpinnedEvents.php @@ -2,52 +2,59 @@ namespace ChurchCRM\SystemCalendars; -use ChurchCRM\Interfaces\SystemCalendar; -use ChurchCRM\PersonQuery; use ChurchCRM\EventQuery; -use Propel\Runtime\ActiveQuery\Criteria; - -class UnpinnedEvents implements SystemCalendar { - - public static function isAvailable() { - return true; - } - - public function getAccessToken() { - return false; - } - - public function getBackgroundColor() { - return "FF0000"; - } - - public function getForegroundColor() { - return "FFFFFF"; - } - - public function getId() { - return 3; - } - - public function getName() { - return gettext("Unpinned Events"); - } - - public function getEvents($start,$end) { - $Events = EventQuery::create() - ->filterByStart(array("min" => $start)) - ->filterByEnd(array("max" => $end)) - ->useCalendarEventQuery(null,\Propel\Runtime\ActiveQuery\Criteria::LEFT_JOIN) - ->filterByCalendarId(null) - ->endUse() - ->find(); - return $Events; - } - - public function getEventById($Id) { - $Event = EventQuery::create() - ->findOneById($Id); - return $Event; - } - +use ChurchCRM\Interfaces\SystemCalendar; + +class UnpinnedEvents implements SystemCalendar +{ + public static function isAvailable() + { + return true; + } + + public function getAccessToken() + { + return false; + } + + public function getBackgroundColor() + { + return 'FF0000'; + } + + public function getForegroundColor() + { + return 'FFFFFF'; + } + + public function getId() + { + return 3; + } + + public function getName() + { + return gettext('Unpinned Events'); + } + + public function getEvents($start, $end) + { + $Events = EventQuery::create() + ->filterByStart(['min' => $start]) + ->filterByEnd(['max' => $end]) + ->useCalendarEventQuery(null, \Propel\Runtime\ActiveQuery\Criteria::LEFT_JOIN) + ->filterByCalendarId(null) + ->endUse() + ->find(); + + return $Events; + } + + public function getEventById($Id) + { + $Event = EventQuery::create() + ->findOneById($Id); + + return $Event; + } } diff --git a/src/ChurchCRM/data/Countries.php b/src/ChurchCRM/data/Countries.php index 1206a1141b..a4f82ac036 100644 --- a/src/ChurchCRM/data/Countries.php +++ b/src/ChurchCRM/data/Countries.php @@ -1,308 +1,312 @@ new Country('AF','Afghanistan (‫افغانستان‬‎)'), - 'AX' => new Country('AX','Åland Islands (Åland)'), - 'AL' => new Country('AL','Albania (Shqipëri)'), - 'DZ' => new Country('DZ','Algeria (‫الجزائر‬‎)'), - 'AS' => new Country('AS','American Samoa'), - 'AD' => new Country('AD','Andorra'), - 'AO' => new Country('AO','Angola'), - 'AI' => new Country('AI','Anguilla'), - 'AQ' => new Country('AQ','Antarctica'), - 'AG' => new Country('AG','Antigua and Barbuda'), - 'AR' => new Country('AR','Argentina'), - 'AM' => new Country('AM','Armenia (Հայաստան)'), - 'AW' => new Country('AW','Aruba'), - 'AC' => new Country('AC','Ascension Island'), - 'AU' => new Country('AU','Australia','Australia'), - 'AT' => new Country('AT','Austria (Österreich)','Austria'), - 'AZ' => new Country('AZ','Azerbaijan (Azərbaycan)'), - 'BS' => new Country('BS','Bahamas'), - 'BH' => new Country('BH','Bahrain (‫البحرين‬‎)'), - 'BD' => new Country('BD','Bangladesh (বাংলাদেশ)'), - 'BB' => new Country('BB','Barbados'), - 'BY' => new Country('BY','Belarus (Беларусь)'), - 'BE' => new Country('BE','Belgium (België)','Belgium'), - 'BZ' => new Country('BZ','Belize'), - 'BJ' => new Country('BJ','Benin (Bénin)'), - 'BM' => new Country('BM','Bermuda'), - 'BT' => new Country('BT','Bhutan (འབྲུག)'), - 'BO' => new Country('BO','Bolivia'), - 'BA' => new Country('BA','Bosnia and Herzegovina (Босна и Херцеговина)','Bosnia'), - 'BW' => new Country('BW','Botswana'), - 'BV' => new Country('BV','Bouvet Island'), - 'BR' => new Country('BR','Brazil (Brasil)','Brazil'), - 'IO' => new Country('IO','British Indian Ocean Territory'), - 'VG' => new Country('VG','British Virgin Islands'), - 'BN' => new Country('BN','Brunei'), - 'BG' => new Country('BG','Bulgaria (България)'), - 'BF' => new Country('BF','Burkina Faso'), - 'BI' => new Country('BI','Burundi (Uburundi)'), - 'KH' => new Country('KH','Cambodia (កម្ពុជា)'), - 'CM' => new Country('CM','Cameroon (Cameroun)'), - 'CA' => new Country('CA','Canada'), - 'IC' => new Country('IC','Canary Islands (islas Canarias)'), - 'CV' => new Country('CV','Cape Verde (Kabu Verdi)'), - 'BQ' => new Country('BQ','Caribbean Netherlands'), - 'KY' => new Country('KY','Cayman Islands'), - 'CF' => new Country('CF','Central African Republic (République centrafricaine)'), - 'EA' => new Country('EA','Ceuta and Melilla (Ceuta y Melilla)'), - 'TD' => new Country('TD','Chad (Tchad)'), - 'CL' => new Country('CL','Chile'), - 'CN' => new Country('CN','China (中国)'), - 'CX' => new Country('CX','Christmas Island'), - 'CP' => new Country('CP','Clipperton Island'), - 'CC' => new Country('CC','Cocos (Keeling) Islands (Kepulauan Cocos (Keeling))'), - 'CO' => new Country('CO','Colombia'), - 'KM' => new Country('KM','Comoros (‫جزر القمر‬‎)'), - 'CD' => new Country('CD','Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)'), - 'CG' => new Country('CG','Congo (Republic) (Congo-Brazzaville)'), - 'CK' => new Country('CK','Cook Islands'), - 'CR' => new Country('CR','Costa Rica'), - 'CI' => new Country('CI','Côte d’Ivoire'), - 'HR' => new Country('HR','Croatia (Hrvatska)','Croatia'), - 'CU' => new Country('CU','Cuba'), - 'CW' => new Country('CW','Curaçao'), - 'CY' => new Country('CY','Cyprus (Κύπρος)'), - 'CZ' => new Country('CZ','Czech Republic (Česká republika)','CzechRepublic'), - 'DK' => new Country('DK','Denmark (Danmark)','Denmark'), - 'DG' => new Country('DG','Diego Garcia'), - 'DJ' => new Country('DJ','Djibouti'), - 'DM' => new Country('DM','Dominica'), - 'DO' => new Country('DO','Dominican Republic (República Dominicana)'), - 'EC' => new Country('EC','Ecuador'), - 'EG' => new Country('EG','Egypt (‫مصر‬‎)'), - 'SV' => new Country('SV','El Salvador'), - 'GQ' => new Country('GQ','Equatorial Guinea (Guinea Ecuatorial)'), - 'ER' => new Country('ER','Eritrea'), - 'EE' => new Country('EE','Estonia (Eesti)','Estonia'), - 'ET' => new Country('ET','Ethiopia'), - 'FK' => new Country('FK','Falkland Islands (Islas Malvinas)'), - 'FO' => new Country('FO','Faroe Islands (Føroyar)'), - 'FJ' => new Country('FJ','Fiji'), - 'FI' => new Country('FI','Finland (Suomi)','Finland'), - 'FR' => new Country('FR','France','France'), - 'GF' => new Country('GF','French Guiana (Guyane française)'), - 'PF' => new Country('PF','French Polynesia (Polynésie française)'), - 'TF' => new Country('TF','French Southern Territories (Terres australes françaises)'), - 'GA' => new Country('GA','Gabon'), - 'GM' => new Country('GM','Gambia'), - 'GE' => new Country('GE','Georgia (საქართველო)'), - 'DE' => new Country('DE','Germany (Deutschland)','Germany'), - 'GH' => new Country('GH','Ghana (Gaana)'), - 'GI' => new Country('GI','Gibraltar'), - 'GR' => new Country('GR','Greece (Ελλάδα)','Greece'), - 'GL' => new Country('GL','Greenland (Kalaallit Nunaat)'), - 'GD' => new Country('GD','Grenada'), - 'GP' => new Country('GP','Guadeloupe'), - 'GU' => new Country('GU','Guam'), - 'GT' => new Country('GT','Guatemala'), - 'GG' => new Country('GG','Guernsey'), - 'GN' => new Country('GN','Guinea (Guinée)'), - 'GW' => new Country('GW','Guinea-Bissau (Guiné Bissau)'), - 'GY' => new Country('GY','Guyana'), - 'HT' => new Country('HT','Haiti'), - 'HM' => new Country('HM','Heard & McDonald Islands'), - 'HN' => new Country('HN','Honduras'), - 'HK' => new Country('HK','Hong Kong (香港)'), - 'HU' => new Country('HU','Hungary (Magyarország)','Hungary'), - 'IS' => new Country('IS','Iceland (Ísland)'), - 'IN' => new Country('IN','India (भारत)'), - 'ID' => new Country('ID','Indonesia'), - 'IR' => new Country('IR','Iran (‫ایران‬‎)'), - 'IQ' => new Country('IQ','Iraq (‫العراق‬‎)'), - 'IE' => new Country('IE','Ireland','Ireland'), - 'IM' => new Country('IM','Isle of Man'), - 'IL' => new Country('IL','Israel (‫ישראל‬‎)'), - 'IT' => new Country('IT','Italy (Italia)','Italy'), - 'JM' => new Country('JM','Jamaica'), - 'JP' => new Country('JP','Japan (日本)','Japan'), - 'JE' => new Country('JE','Jersey'), - 'JO' => new Country('JO','Jordan (‫الأردن‬‎)'), - 'KZ' => new Country('KZ','Kazakhstan (Казахстан)'), - 'KE' => new Country('KE','Kenya'), - 'KI' => new Country('KI','Kiribati'), - 'XK' => new Country('XK','Kosovo (Kosovë)'), - 'KW' => new Country('KW','Kuwait (‫الكويت‬‎)'), - 'KG' => new Country('KG','Kyrgyzstan (Кыргызстан)'), - 'LA' => new Country('LA','Laos (ລາວ)'), - 'LV' => new Country('LV','Latvia (Latvija)'), - 'LB' => new Country('LB','Lebanon (‫لبنان‬‎)'), - 'LS' => new Country('LS','Lesotho'), - 'LR' => new Country('LR','Liberia'), - 'LY' => new Country('LY','Libya (‫ليبيا‬‎)'), - 'LI' => new Country('LI','Liechtenstein'), - 'LT' => new Country('LT','Lithuania (Lietuva)','Netherlands'), - 'LU' => new Country('LU','Luxembourg'), - 'MO' => new Country('MO','Macau (澳門)'), - 'MK' => new Country('MK','Macedonia (FYROM) (Македонија)'), - 'MG' => new Country('MG','Madagascar (Madagasikara)'), - 'MW' => new Country('MW','Malawi'), - 'MY' => new Country('MY','Malaysia'), - 'MV' => new Country('MV','Maldives'), - 'ML' => new Country('ML','Mali'), - 'MT' => new Country('MT','Malta'), - 'MH' => new Country('MH','Marshall Islands'), - 'MQ' => new Country('MQ','Martinique'), - 'MR' => new Country('MR','Mauritania (‫موريتانيا‬‎)'), - 'MU' => new Country('MU','Mauritius (Moris)'), - 'YT' => new Country('YT','Mayotte'), - 'MX' => new Country('MX','Mexico (México)'), - 'FM' => new Country('FM','Micronesia'), - 'MD' => new Country('MD','Moldova (Republica Moldova)'), - 'MC' => new Country('MC','Monaco'), - 'MN' => new Country('MN','Mongolia (Монгол)'), - 'ME' => new Country('ME','Montenegro (Crna Gora)'), - 'MS' => new Country('MS','Montserrat'), - 'MA' => new Country('MA','Morocco (‫المغرب‬‎)'), - 'MZ' => new Country('MZ','Mozambique (Moçambique)'), - 'MM' => new Country('MM','Myanmar (Burma) (မြန်မာ)'), - 'NA' => new Country('NA','Namibia (Namibië)'), - 'NR' => new Country('NR','Nauru'), - 'NP' => new Country('NP','Nepal (नेपाल)'), - 'NL' => new Country('NL','Netherlands (Nederland)','Netherlands'), - 'NC' => new Country('NC','New Caledonia (Nouvelle-Calédonie)'), - 'NZ' => new Country('NZ','New Zealand','NewZealand'), - 'NI' => new Country('NI','Nicaragua'), - 'NE' => new Country('NE','Niger (Nijar)'), - 'NG' => new Country('NG','Nigeria'), - 'NU' => new Country('NU','Niue'), - 'NF' => new Country('NF','Norfolk Island'), - 'MP' => new Country('MP','Northern Mariana Islands'), - 'KP' => new Country('KP','North Korea (조선 민주주의 인민 공화국)'), - 'NO' => new Country('NO','Norway (Norge)','Norway'), - 'OM' => new Country('OM','Oman (‫عُمان‬‎)'), - 'PK' => new Country('PK','Pakistan (‫پاکستان‬‎)'), - 'PW' => new Country('PW','Palau'), - 'PS' => new Country('PS','Palestine (‫فلسطين‬‎)'), - 'PA' => new Country('PA','Panama (Panamá)'), - 'PG' => new Country('PG','Papua New Guinea'), - 'PY' => new Country('PY','Paraguay'), - 'PE' => new Country('PE','Peru (Perú)'), - 'PH' => new Country('PH','Philippines'), - 'PN' => new Country('PN','Pitcairn Islands'), - 'PL' => new Country('PL','Poland (Polska)','Poland'), - 'PT' => new Country('PT','Portugal','Portugal'), - 'PR' => new Country('PR','Puerto Rico'), - 'QA' => new Country('QA','Qatar (‫قطر‬‎)'), - 'RE' => new Country('RE','Réunion (La Réunion)'), - 'RO' => new Country('RO','Romania (România)','Romania'), - 'RU' => new Country('RU','Russia (Россия)','Russia'), - 'RW' => new Country('RW','Rwanda'), - 'BL' => new Country('BL','Saint Barthélemy (Saint-Barthélemy)'), - 'SH' => new Country('SH','Saint Helena'), - 'KN' => new Country('KN','Saint Kitts and Nevis'), - 'LC' => new Country('LC','Saint Lucia'), - 'MF' => new Country('MF','Saint Martin (Saint-Martin (partie française))'), - 'PM' => new Country('PM','Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)'), - 'WS' => new Country('WS','Samoa'), - 'SM' => new Country('SM','San Marino'), - 'ST' => new Country('ST','São Tomé and Príncipe (São Tomé e Príncipe)'), - 'SA' => new Country('SA','Saudi Arabia (‫المملكة العربية السعودية‬‎)'), - 'SN' => new Country('SN','Senegal (Sénégal)'), - 'RS' => new Country('RS','Serbia (Србија)'), - 'SC' => new Country('SC','Seychelles'), - 'SL' => new Country('SL','Sierra Leone'), - 'SG' => new Country('SG','Singapore'), - 'SX' => new Country('SX','Sint Maarten'), - 'SK' => new Country('SK','Slovakia (Slovensko)','Slovakia'), - 'SI' => new Country('SI','Slovenia (Slovenija)','Slovakia'), - 'SB' => new Country('SB','Solomon Islands'), - 'SO' => new Country('SO','Somalia (Soomaaliya)'), - 'ZA' => new Country('ZA','South Africa','SouthAfrica'), - 'GS' => new Country('GS','South Georgia & South Sandwich Islands'), - 'KR' => new Country('KR','South Korea (대한민국)'), - 'SS' => new Country('SS','South Sudan (‫جنوب السودان‬‎)'), - 'ES' => new Country('ES','Spain (España)','Spain'), - 'LK' => new Country('LK','Sri Lanka (ශ්‍රී ලංකාව)'), - 'VC' => new Country('VC','St. Vincent & Grenadines'), - 'SD' => new Country('SD','Sudan (‫السودان‬‎)'), - 'SR' => new Country('SR','Suriname'), - 'SJ' => new Country('SJ','Svalbard and Jan Mayen (Svalbard og Jan Mayen)'), - 'SZ' => new Country('SZ','Swaziland'), - 'SE' => new Country('SE','Sweden (Sverige)','Sweden'), - 'CH' => new Country('CH','Switzerland (Schweiz)','Switzerland'), - 'SY' => new Country('SY','Syria (‫سوريا‬‎)'), - 'TW' => new Country('TW','Taiwan (台灣)'), - 'TJ' => new Country('TJ','Tajikistan'), - 'TZ' => new Country('TZ','Tanzania'), - 'TH' => new Country('TH','Thailand (ไทย)'), - 'TL' => new Country('TL','Timor-Leste'), - 'TG' => new Country('TG','Togo'), - 'TK' => new Country('TK','Tokelau'), - 'TO' => new Country('TO','Tonga'), - 'TT' => new Country('TT','Trinidad and Tobago'), - 'TA' => new Country('TA','Tristan da Cunha'), - 'TN' => new Country('TN','Tunisia (‫تونس‬‎)'), - 'TR' => new Country('TR','Turkey (Türkiye)'), - 'TM' => new Country('TM','Turkmenistan'), - 'TC' => new Country('TC','Turks and Caicos Islands'), - 'TV' => new Country('TV','Tuvalu'), - 'UM' => new Country('UM','U.S. Outlying Islands','USA'), - 'VI' => new Country('VI','U.S. Virgin Islands','USA'), - 'UG' => new Country('UG','Uganda'), - 'UA' => new Country('UA','Ukraine (Україна)','Ukraine'), - 'AE' => new Country('AE','United Arab Emirates (‫الإمارات العربية المتحدة‬‎)'), - 'GB' => new Country('GB','United Kingdom','UnitedKingdom'), - 'US' => new Country('US','United States','USA'), - 'UY' => new Country('UY','Uruguay'), - 'UZ' => new Country('UZ','Uzbekistan (Oʻzbekiston)'), - 'VU' => new Country('VU','Vanuatu'), - 'VA' => new Country('VA','Vatican City (Città del Vaticano)'), - 'VE' => new Country('VE','Venezuela'), - 'VN' => new Country('VN','Vietnam (Việt Nam)'), - 'WF' => new Country('WF','Wallis and Futuna'), - 'EH' => new Country('EH','Western Sahara (‫الصحراء الغربية‬‎)'), - 'YE' => new Country('YE','Yemen (‫اليمن‬‎)'), - 'ZM' => new Country('ZM','Zambia'), - 'ZW' => new Country('ZW','Zimbabwe') - ); + private static function initializeCountries() + { + self::$countries = [ + 'AF' => new Country('AF', 'Afghanistan (‫افغانستان‬‎)'), + 'AX' => new Country('AX', 'Åland Islands (Åland)'), + 'AL' => new Country('AL', 'Albania (Shqipëri)'), + 'DZ' => new Country('DZ', 'Algeria (‫الجزائر‬‎)'), + 'AS' => new Country('AS', 'American Samoa'), + 'AD' => new Country('AD', 'Andorra'), + 'AO' => new Country('AO', 'Angola'), + 'AI' => new Country('AI', 'Anguilla'), + 'AQ' => new Country('AQ', 'Antarctica'), + 'AG' => new Country('AG', 'Antigua and Barbuda'), + 'AR' => new Country('AR', 'Argentina'), + 'AM' => new Country('AM', 'Armenia (Հայաստան)'), + 'AW' => new Country('AW', 'Aruba'), + 'AC' => new Country('AC', 'Ascension Island'), + 'AU' => new Country('AU', 'Australia', 'Australia'), + 'AT' => new Country('AT', 'Austria (Österreich)', 'Austria'), + 'AZ' => new Country('AZ', 'Azerbaijan (Azərbaycan)'), + 'BS' => new Country('BS', 'Bahamas'), + 'BH' => new Country('BH', 'Bahrain (‫البحرين‬‎)'), + 'BD' => new Country('BD', 'Bangladesh (বাংলাদেশ)'), + 'BB' => new Country('BB', 'Barbados'), + 'BY' => new Country('BY', 'Belarus (Беларусь)'), + 'BE' => new Country('BE', 'Belgium (België)', 'Belgium'), + 'BZ' => new Country('BZ', 'Belize'), + 'BJ' => new Country('BJ', 'Benin (Bénin)'), + 'BM' => new Country('BM', 'Bermuda'), + 'BT' => new Country('BT', 'Bhutan (འབྲུག)'), + 'BO' => new Country('BO', 'Bolivia'), + 'BA' => new Country('BA', 'Bosnia and Herzegovina (Босна и Херцеговина)', 'Bosnia'), + 'BW' => new Country('BW', 'Botswana'), + 'BV' => new Country('BV', 'Bouvet Island'), + 'BR' => new Country('BR', 'Brazil (Brasil)', 'Brazil'), + 'IO' => new Country('IO', 'British Indian Ocean Territory'), + 'VG' => new Country('VG', 'British Virgin Islands'), + 'BN' => new Country('BN', 'Brunei'), + 'BG' => new Country('BG', 'Bulgaria (България)'), + 'BF' => new Country('BF', 'Burkina Faso'), + 'BI' => new Country('BI', 'Burundi (Uburundi)'), + 'KH' => new Country('KH', 'Cambodia (កម្ពុជា)'), + 'CM' => new Country('CM', 'Cameroon (Cameroun)'), + 'CA' => new Country('CA', 'Canada'), + 'IC' => new Country('IC', 'Canary Islands (islas Canarias)'), + 'CV' => new Country('CV', 'Cape Verde (Kabu Verdi)'), + 'BQ' => new Country('BQ', 'Caribbean Netherlands'), + 'KY' => new Country('KY', 'Cayman Islands'), + 'CF' => new Country('CF', 'Central African Republic (République centrafricaine)'), + 'EA' => new Country('EA', 'Ceuta and Melilla (Ceuta y Melilla)'), + 'TD' => new Country('TD', 'Chad (Tchad)'), + 'CL' => new Country('CL', 'Chile'), + 'CN' => new Country('CN', 'China (中国)'), + 'CX' => new Country('CX', 'Christmas Island'), + 'CP' => new Country('CP', 'Clipperton Island'), + 'CC' => new Country('CC', 'Cocos (Keeling) Islands (Kepulauan Cocos (Keeling))'), + 'CO' => new Country('CO', 'Colombia'), + 'KM' => new Country('KM', 'Comoros (‫جزر القمر‬‎)'), + 'CD' => new Country('CD', 'Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)'), + 'CG' => new Country('CG', 'Congo (Republic) (Congo-Brazzaville)'), + 'CK' => new Country('CK', 'Cook Islands'), + 'CR' => new Country('CR', 'Costa Rica'), + 'CI' => new Country('CI', 'Côte d’Ivoire'), + 'HR' => new Country('HR', 'Croatia (Hrvatska)', 'Croatia'), + 'CU' => new Country('CU', 'Cuba'), + 'CW' => new Country('CW', 'Curaçao'), + 'CY' => new Country('CY', 'Cyprus (Κύπρος)'), + 'CZ' => new Country('CZ', 'Czech Republic (Česká republika)', 'CzechRepublic'), + 'DK' => new Country('DK', 'Denmark (Danmark)', 'Denmark'), + 'DG' => new Country('DG', 'Diego Garcia'), + 'DJ' => new Country('DJ', 'Djibouti'), + 'DM' => new Country('DM', 'Dominica'), + 'DO' => new Country('DO', 'Dominican Republic (República Dominicana)'), + 'EC' => new Country('EC', 'Ecuador'), + 'EG' => new Country('EG', 'Egypt (‫مصر‬‎)'), + 'SV' => new Country('SV', 'El Salvador'), + 'GQ' => new Country('GQ', 'Equatorial Guinea (Guinea Ecuatorial)'), + 'ER' => new Country('ER', 'Eritrea'), + 'EE' => new Country('EE', 'Estonia (Eesti)', 'Estonia'), + 'ET' => new Country('ET', 'Ethiopia'), + 'FK' => new Country('FK', 'Falkland Islands (Islas Malvinas)'), + 'FO' => new Country('FO', 'Faroe Islands (Føroyar)'), + 'FJ' => new Country('FJ', 'Fiji'), + 'FI' => new Country('FI', 'Finland (Suomi)', 'Finland'), + 'FR' => new Country('FR', 'France', 'France'), + 'GF' => new Country('GF', 'French Guiana (Guyane française)'), + 'PF' => new Country('PF', 'French Polynesia (Polynésie française)'), + 'TF' => new Country('TF', 'French Southern Territories (Terres australes françaises)'), + 'GA' => new Country('GA', 'Gabon'), + 'GM' => new Country('GM', 'Gambia'), + 'GE' => new Country('GE', 'Georgia (საქართველო)'), + 'DE' => new Country('DE', 'Germany (Deutschland)', 'Germany'), + 'GH' => new Country('GH', 'Ghana (Gaana)'), + 'GI' => new Country('GI', 'Gibraltar'), + 'GR' => new Country('GR', 'Greece (Ελλάδα)', 'Greece'), + 'GL' => new Country('GL', 'Greenland (Kalaallit Nunaat)'), + 'GD' => new Country('GD', 'Grenada'), + 'GP' => new Country('GP', 'Guadeloupe'), + 'GU' => new Country('GU', 'Guam'), + 'GT' => new Country('GT', 'Guatemala'), + 'GG' => new Country('GG', 'Guernsey'), + 'GN' => new Country('GN', 'Guinea (Guinée)'), + 'GW' => new Country('GW', 'Guinea-Bissau (Guiné Bissau)'), + 'GY' => new Country('GY', 'Guyana'), + 'HT' => new Country('HT', 'Haiti'), + 'HM' => new Country('HM', 'Heard & McDonald Islands'), + 'HN' => new Country('HN', 'Honduras'), + 'HK' => new Country('HK', 'Hong Kong (香港)'), + 'HU' => new Country('HU', 'Hungary (Magyarország)', 'Hungary'), + 'IS' => new Country('IS', 'Iceland (Ísland)'), + 'IN' => new Country('IN', 'India (भारत)'), + 'ID' => new Country('ID', 'Indonesia'), + 'IR' => new Country('IR', 'Iran (‫ایران‬‎)'), + 'IQ' => new Country('IQ', 'Iraq (‫العراق‬‎)'), + 'IE' => new Country('IE', 'Ireland', 'Ireland'), + 'IM' => new Country('IM', 'Isle of Man'), + 'IL' => new Country('IL', 'Israel (‫ישראל‬‎)'), + 'IT' => new Country('IT', 'Italy (Italia)', 'Italy'), + 'JM' => new Country('JM', 'Jamaica'), + 'JP' => new Country('JP', 'Japan (日本)', 'Japan'), + 'JE' => new Country('JE', 'Jersey'), + 'JO' => new Country('JO', 'Jordan (‫الأردن‬‎)'), + 'KZ' => new Country('KZ', 'Kazakhstan (Казахстан)'), + 'KE' => new Country('KE', 'Kenya'), + 'KI' => new Country('KI', 'Kiribati'), + 'XK' => new Country('XK', 'Kosovo (Kosovë)'), + 'KW' => new Country('KW', 'Kuwait (‫الكويت‬‎)'), + 'KG' => new Country('KG', 'Kyrgyzstan (Кыргызстан)'), + 'LA' => new Country('LA', 'Laos (ລາວ)'), + 'LV' => new Country('LV', 'Latvia (Latvija)'), + 'LB' => new Country('LB', 'Lebanon (‫لبنان‬‎)'), + 'LS' => new Country('LS', 'Lesotho'), + 'LR' => new Country('LR', 'Liberia'), + 'LY' => new Country('LY', 'Libya (‫ليبيا‬‎)'), + 'LI' => new Country('LI', 'Liechtenstein'), + 'LT' => new Country('LT', 'Lithuania (Lietuva)', 'Netherlands'), + 'LU' => new Country('LU', 'Luxembourg'), + 'MO' => new Country('MO', 'Macau (澳門)'), + 'MK' => new Country('MK', 'Macedonia (FYROM) (Македонија)'), + 'MG' => new Country('MG', 'Madagascar (Madagasikara)'), + 'MW' => new Country('MW', 'Malawi'), + 'MY' => new Country('MY', 'Malaysia'), + 'MV' => new Country('MV', 'Maldives'), + 'ML' => new Country('ML', 'Mali'), + 'MT' => new Country('MT', 'Malta'), + 'MH' => new Country('MH', 'Marshall Islands'), + 'MQ' => new Country('MQ', 'Martinique'), + 'MR' => new Country('MR', 'Mauritania (‫موريتانيا‬‎)'), + 'MU' => new Country('MU', 'Mauritius (Moris)'), + 'YT' => new Country('YT', 'Mayotte'), + 'MX' => new Country('MX', 'Mexico (México)'), + 'FM' => new Country('FM', 'Micronesia'), + 'MD' => new Country('MD', 'Moldova (Republica Moldova)'), + 'MC' => new Country('MC', 'Monaco'), + 'MN' => new Country('MN', 'Mongolia (Монгол)'), + 'ME' => new Country('ME', 'Montenegro (Crna Gora)'), + 'MS' => new Country('MS', 'Montserrat'), + 'MA' => new Country('MA', 'Morocco (‫المغرب‬‎)'), + 'MZ' => new Country('MZ', 'Mozambique (Moçambique)'), + 'MM' => new Country('MM', 'Myanmar (Burma) (မြန်မာ)'), + 'NA' => new Country('NA', 'Namibia (Namibië)'), + 'NR' => new Country('NR', 'Nauru'), + 'NP' => new Country('NP', 'Nepal (नेपाल)'), + 'NL' => new Country('NL', 'Netherlands (Nederland)', 'Netherlands'), + 'NC' => new Country('NC', 'New Caledonia (Nouvelle-Calédonie)'), + 'NZ' => new Country('NZ', 'New Zealand', 'NewZealand'), + 'NI' => new Country('NI', 'Nicaragua'), + 'NE' => new Country('NE', 'Niger (Nijar)'), + 'NG' => new Country('NG', 'Nigeria'), + 'NU' => new Country('NU', 'Niue'), + 'NF' => new Country('NF', 'Norfolk Island'), + 'MP' => new Country('MP', 'Northern Mariana Islands'), + 'KP' => new Country('KP', 'North Korea (조선 민주주의 인민 공화국)'), + 'NO' => new Country('NO', 'Norway (Norge)', 'Norway'), + 'OM' => new Country('OM', 'Oman (‫عُمان‬‎)'), + 'PK' => new Country('PK', 'Pakistan (‫پاکستان‬‎)'), + 'PW' => new Country('PW', 'Palau'), + 'PS' => new Country('PS', 'Palestine (‫فلسطين‬‎)'), + 'PA' => new Country('PA', 'Panama (Panamá)'), + 'PG' => new Country('PG', 'Papua New Guinea'), + 'PY' => new Country('PY', 'Paraguay'), + 'PE' => new Country('PE', 'Peru (Perú)'), + 'PH' => new Country('PH', 'Philippines'), + 'PN' => new Country('PN', 'Pitcairn Islands'), + 'PL' => new Country('PL', 'Poland (Polska)', 'Poland'), + 'PT' => new Country('PT', 'Portugal', 'Portugal'), + 'PR' => new Country('PR', 'Puerto Rico'), + 'QA' => new Country('QA', 'Qatar (‫قطر‬‎)'), + 'RE' => new Country('RE', 'Réunion (La Réunion)'), + 'RO' => new Country('RO', 'Romania (România)', 'Romania'), + 'RU' => new Country('RU', 'Russia (Россия)', 'Russia'), + 'RW' => new Country('RW', 'Rwanda'), + 'BL' => new Country('BL', 'Saint Barthélemy (Saint-Barthélemy)'), + 'SH' => new Country('SH', 'Saint Helena'), + 'KN' => new Country('KN', 'Saint Kitts and Nevis'), + 'LC' => new Country('LC', 'Saint Lucia'), + 'MF' => new Country('MF', 'Saint Martin (Saint-Martin (partie française))'), + 'PM' => new Country('PM', 'Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)'), + 'WS' => new Country('WS', 'Samoa'), + 'SM' => new Country('SM', 'San Marino'), + 'ST' => new Country('ST', 'São Tomé and Príncipe (São Tomé e Príncipe)'), + 'SA' => new Country('SA', 'Saudi Arabia (‫المملكة العربية السعودية‬‎)'), + 'SN' => new Country('SN', 'Senegal (Sénégal)'), + 'RS' => new Country('RS', 'Serbia (Србија)'), + 'SC' => new Country('SC', 'Seychelles'), + 'SL' => new Country('SL', 'Sierra Leone'), + 'SG' => new Country('SG', 'Singapore'), + 'SX' => new Country('SX', 'Sint Maarten'), + 'SK' => new Country('SK', 'Slovakia (Slovensko)', 'Slovakia'), + 'SI' => new Country('SI', 'Slovenia (Slovenija)', 'Slovakia'), + 'SB' => new Country('SB', 'Solomon Islands'), + 'SO' => new Country('SO', 'Somalia (Soomaaliya)'), + 'ZA' => new Country('ZA', 'South Africa', 'SouthAfrica'), + 'GS' => new Country('GS', 'South Georgia & South Sandwich Islands'), + 'KR' => new Country('KR', 'South Korea (대한민국)'), + 'SS' => new Country('SS', 'South Sudan (‫جنوب السودان‬‎)'), + 'ES' => new Country('ES', 'Spain (España)', 'Spain'), + 'LK' => new Country('LK', 'Sri Lanka (ශ්‍රී ලංකාව)'), + 'VC' => new Country('VC', 'St. Vincent & Grenadines'), + 'SD' => new Country('SD', 'Sudan (‫السودان‬‎)'), + 'SR' => new Country('SR', 'Suriname'), + 'SJ' => new Country('SJ', 'Svalbard and Jan Mayen (Svalbard og Jan Mayen)'), + 'SZ' => new Country('SZ', 'Swaziland'), + 'SE' => new Country('SE', 'Sweden (Sverige)', 'Sweden'), + 'CH' => new Country('CH', 'Switzerland (Schweiz)', 'Switzerland'), + 'SY' => new Country('SY', 'Syria (‫سوريا‬‎)'), + 'TW' => new Country('TW', 'Taiwan (台灣)'), + 'TJ' => new Country('TJ', 'Tajikistan'), + 'TZ' => new Country('TZ', 'Tanzania'), + 'TH' => new Country('TH', 'Thailand (ไทย)'), + 'TL' => new Country('TL', 'Timor-Leste'), + 'TG' => new Country('TG', 'Togo'), + 'TK' => new Country('TK', 'Tokelau'), + 'TO' => new Country('TO', 'Tonga'), + 'TT' => new Country('TT', 'Trinidad and Tobago'), + 'TA' => new Country('TA', 'Tristan da Cunha'), + 'TN' => new Country('TN', 'Tunisia (‫تونس‬‎)'), + 'TR' => new Country('TR', 'Turkey (Türkiye)'), + 'TM' => new Country('TM', 'Turkmenistan'), + 'TC' => new Country('TC', 'Turks and Caicos Islands'), + 'TV' => new Country('TV', 'Tuvalu'), + 'UM' => new Country('UM', 'U.S. Outlying Islands', 'USA'), + 'VI' => new Country('VI', 'U.S. Virgin Islands', 'USA'), + 'UG' => new Country('UG', 'Uganda'), + 'UA' => new Country('UA', 'Ukraine (Україна)', 'Ukraine'), + 'AE' => new Country('AE', 'United Arab Emirates (‫الإمارات العربية المتحدة‬‎)'), + 'GB' => new Country('GB', 'United Kingdom', 'UnitedKingdom'), + 'US' => new Country('US', 'United States', 'USA'), + 'UY' => new Country('UY', 'Uruguay'), + 'UZ' => new Country('UZ', 'Uzbekistan (Oʻzbekiston)'), + 'VU' => new Country('VU', 'Vanuatu'), + 'VA' => new Country('VA', 'Vatican City (Città del Vaticano)'), + 'VE' => new Country('VE', 'Venezuela'), + 'VN' => new Country('VN', 'Vietnam (Việt Nam)'), + 'WF' => new Country('WF', 'Wallis and Futuna'), + 'EH' => new Country('EH', 'Western Sahara (‫الصحراء الغربية‬‎)'), + 'YE' => new Country('YE', 'Yemen (‫اليمن‬‎)'), + 'ZM' => new Country('ZM', 'Zambia'), + 'ZW' => new Country('ZW', 'Zimbabwe'), + ]; } + private static function getSingleName(Country $Country) { - return $Country->getCountryName(); + return $Country->getCountryName(); } public static function getNames() { - self::initializeCountries(); - return array_map(array("self","getSingleName"),self::$countries); + self::initializeCountries(); + + return array_map(['self', 'getSingleName'], self::$countries); } public static function getAll() { - self::initializeCountries(); - return self::$countries; + self::initializeCountries(); + + return self::$countries; } public static function getCountry(string $CountryCode) { - self::initializeCountries(); - return self::$countries[$CountryCode]; - } + self::initializeCountries(); + return self::$countries[$CountryCode]; + } public static function getCountryByName(string $CountryName) { - if (empty($CountryName)) - { - return null; - } - self::initializeCountries(); - $result = array_filter(self::$countries,function ($e) use ($CountryName) { - return $e->getCountryName() === $CountryName; - }); - if (count($result) === 1 ) - { - return current($result); - } - throw new \Exception(gettext("Invalid country name supplied")); + if (empty($CountryName)) { + return null; + } + self::initializeCountries(); + $result = array_filter(self::$countries, function ($e) use ($CountryName) { + return $e->getCountryName() === $CountryName; + }); + if (count($result) === 1) { + return current($result); + } + + throw new \Exception(gettext('Invalid country name supplied')); } } diff --git a/src/ChurchCRM/data/Country.php b/src/ChurchCRM/data/Country.php index d4bac02900..9e22c40406 100644 --- a/src/ChurchCRM/data/Country.php +++ b/src/ChurchCRM/data/Country.php @@ -1,32 +1,37 @@ countryCode = $CountryCode; - $this->countryName = $CountryName; - $this->countryNameYasumi = $CountryNameYasumi; - } + private $countryCode; + private $countryName; + private $countryNameYasumi; - public function getCountryCode(){ - return $this->countryCode; - } + public function __construct(string $CountryCode, string $CountryName, string $CountryNameYasumi = null) + { + $this->countryCode = $CountryCode; + $this->countryName = $CountryName; + $this->countryNameYasumi = $CountryNameYasumi; + } + + public function getCountryCode() + { + return $this->countryCode; + } - public function getCountryName() { - return $this->countryName; - } + public function getCountryName() + { + return $this->countryName; + } - public function getCountryNameYasumi() { - return $this->countryNameYasumi; - } + public function getCountryNameYasumi() + { + return $this->countryNameYasumi; + } public function jsonSerialize() { - return ["name" => $this->countryName, "code" => $this->countryCode]; + return ['name' => $this->countryName, 'code' => $this->countryCode]; } } diff --git a/src/ChurchCRM/data/States.php b/src/ChurchCRM/data/States.php index 1c2963b381..3fdff41311 100644 --- a/src/ChurchCRM/data/States.php +++ b/src/ChurchCRM/data/States.php @@ -1,4 +1,5 @@ countryCode = $countryCode; - $stateFileName = SystemURLs::getDocumentRoot() . '/locale/states/'. $countryCode .'.json'; - if( is_file($stateFileName)) { + $stateFileName = SystemURLs::getDocumentRoot().'/locale/states/'.$countryCode.'.json'; + if (is_file($stateFileName)) { $satesFile = file_get_contents($stateFileName); $this->states = json_decode($satesFile, true); } diff --git a/src/ChurchCRM/dto/Cart.php b/src/ChurchCRM/dto/Cart.php index bedb37d302..b6e03d6a19 100644 --- a/src/ChurchCRM/dto/Cart.php +++ b/src/ChurchCRM/dto/Cart.php @@ -1,4 +1,5 @@ filterByGroupId($GroupID) - ->find(); - foreach ($GroupMembers as $GroupMember) + if (!is_numeric($GroupID)) { + throw new \Exception(gettext('GroupID for Cart must be numeric'), 400); + } + $GroupMembers = Person2group2roleP2g2rQuery::create() + ->filterByGroupId($GroupID) + ->find(); + foreach ($GroupMembers as $GroupMember) { + Cart::AddPerson($GroupMember->getPersonId()); + } + } + + public static function AddFamily($FamilyID) { - Cart::AddPerson($GroupMember->getPersonId()); + if (!is_numeric($FamilyID)) { + throw new \Exception(gettext('FamilyID for Cart must be numeric'), 400); + } + $FamilyMembers = PersonQuery::create() + ->filterByFamId($FamilyID) + ->find(); + foreach ($FamilyMembers as $FamilyMember) { + Cart::AddPerson($FamilyMember->getId()); + } + } + + public static function IntersectArrayWithPeopleCart($aIDs) + { + if (isset($_SESSION['aPeopleCart']) && is_array($aIDs)) { + $_SESSION['aPeopleCart'] = array_intersect($_SESSION['aPeopleCart'], $aIDs); + } } - } - public static function AddFamily($FamilyID) - { - if (!is_numeric($FamilyID)) + public static function RemovePerson($PersonID) { - throw new \Exception (gettext("FamilyID for Cart must be numeric"),400); - } - $FamilyMembers = PersonQuery::create() - ->filterByFamId($FamilyID) - ->find(); - foreach ($FamilyMembers as $FamilyMember) + // make sure the cart array exists + // we can't remove anybody if there is no cart + if (!is_numeric($PersonID)) { + throw new \Exception(gettext('PersonID for Cart must be numeric'), 400); + } + if (isset($_SESSION['aPeopleCart'])) { + $aTempArray[] = $PersonID; // the only element in this array is the ID to be removed + $_SESSION['aPeopleCart'] = array_values(array_diff($_SESSION['aPeopleCart'], $aTempArray)); + } + } + + public static function RemovePersonArray($aIDs) { - Cart::AddPerson($FamilyMember->getId()); + // make sure the cart array exists + // we can't remove anybody if there is no cart + if (isset($_SESSION['aPeopleCart']) && is_array($aIDs)) { + $_SESSION['aPeopleCart'] = array_values(array_diff($_SESSION['aPeopleCart'], $aIDs)); + } } - } - public static function IntersectArrayWithPeopleCart($aIDs) - { - if (isset($_SESSION['aPeopleCart']) && is_array($aIDs)) { - $_SESSION['aPeopleCart'] = array_intersect($_SESSION['aPeopleCart'], $aIDs); - } - } - - public static function RemovePerson($PersonID) - { - // make sure the cart array exists - // we can't remove anybody if there is no cart - if (!is_numeric($PersonID)) + public static function RemoveGroup($GroupID) { - throw new \Exception (gettext("PersonID for Cart must be numeric"),400); - } - if (isset($_SESSION['aPeopleCart'])) { - $aTempArray[] = $PersonID; // the only element in this array is the ID to be removed - $_SESSION['aPeopleCart'] = array_values(array_diff($_SESSION['aPeopleCart'], $aTempArray)); + if (!is_numeric($GroupID)) { + throw new \Exception(gettext('GroupID for Cart must be numeric'), 400); + } + $GroupMembers = Person2group2roleP2g2rQuery::create() + ->filterByGroupId($GroupID) + ->find(); + foreach ($GroupMembers as $GroupMember) { + Cart::RemovePerson($GroupMember->getPersonId()); + } + } + + public static function HasPeople() + { + return array_key_exists('aPeopleCart', $_SESSION) && count($_SESSION['aPeopleCart']) != 0; } - } - public static function RemovePersonArray($aIDs) - { - // make sure the cart array exists - // we can't remove anybody if there is no cart - if (isset($_SESSION['aPeopleCart']) && is_array($aIDs)) { - $_SESSION['aPeopleCart'] = array_values(array_diff($_SESSION['aPeopleCart'], $aIDs)); + public static function CountPeople() + { + return count($_SESSION['aPeopleCart']); } - } - public static function RemoveGroup($GroupID) - { - if (!is_numeric($GroupID)) + public static function ConvertCartToString($aCartArray) { - throw new \Exception (gettext("GroupID for Cart must be numeric"),400); + // Implode the array + $sCartString = implode(',', $aCartArray); + + // Make sure the comma is chopped off the end + if (mb_substr($sCartString, strlen($sCartString) - 1, 1) == ',') { + $sCartString = mb_substr($sCartString, 0, strlen($sCartString) - 1); + } + + // Make sure there are no duplicate commas + $sCartString = str_replace(',,', '', $sCartString); + + return $sCartString; } - $GroupMembers = Person2group2roleP2g2rQuery::create() - ->filterByGroupId($GroupID) - ->find(); - foreach ($GroupMembers as $GroupMember) + + public static function CountFamilies() { - Cart::RemovePerson($GroupMember->getPersonId()); - } - } + $persons = PersonQuery::create() + ->distinct() + ->select(['Person.FamId']) + ->filterById($_SESSION['aPeopleCart']) + ->orderByFamId() + ->find(); - public static function HasPeople() - { - return array_key_exists('aPeopleCart', $_SESSION) && count($_SESSION['aPeopleCart']) != 0; - } + return $persons->count(); + } - public static function CountPeople() - { - return count($_SESSION['aPeopleCart']); - } + public static function EmptyToGroup($GroupID, $RoleID) + { + $iCount = 0; - public static function ConvertCartToString($aCartArray) - { - // Implode the array - $sCartString = implode(',', $aCartArray); + $group = GroupQuery::create()->findOneById($GroupID); - // Make sure the comma is chopped off the end - if (mb_substr($sCartString, strlen($sCartString) - 1, 1) == ',') { - $sCartString = mb_substr($sCartString, 0, strlen($sCartString) - 1); - } + if ($RoleID == 0) { + $RoleID = $group->getDefaultRole(); + } - // Make sure there are no duplicate commas - $sCartString = str_replace(',,', '', $sCartString); + while ($element = each($_SESSION['aPeopleCart'])) { + $personGroupRole = Person2group2roleP2g2rQuery::create() + ->filterByGroupId($GroupID) + ->filterByPersonId($_SESSION['aPeopleCart'][$element['key']]) + ->findOneOrCreate() + ->setRoleId($RoleID) + ->save(); - return $sCartString; - } + /* + This part of code should be done + */ + // Check if this group has special properties + /* $sSQL = 'SELECT grp_hasSpecialProps FROM group_grp WHERE grp_ID = '.$iGroupID; + $rsTemp = RunQuery($sSQL); + $rowTemp = mysqli_fetch_row($rsTemp); + $bHasProp = $rowTemp[0]; - public static function CountFamilies() - { - $persons = PersonQuery::create() - ->distinct() - ->select(['Person.FamId']) - ->filterById($_SESSION['aPeopleCart']) - ->orderByFamId() - ->find(); - return $persons->count(); - } + if ($bHasProp == 'true') { + $sSQL = 'INSERT INTO groupprop_'.$iGroupID." (per_ID) VALUES ('".$iPersonID."')"; + RunQuery($sSQL); + } */ - public static function EmptyToGroup($GroupID,$RoleID) - { - $iCount = 0; + $iCount += 1; + } - $group = GroupQuery::create()->findOneById($GroupID); + $_SESSION['aPeopleCart'] = []; + } - if($RoleID == 0) + public static function getCartPeople() { - $RoleID = $group->getDefaultRole(); + $people = PersonQuery::create() + ->filterById($_SESSION['aPeopleCart']) + ->find(); + + return $people; } - while ($element = each($_SESSION['aPeopleCart'])) { - $personGroupRole = Person2group2roleP2g2rQuery::create() - ->filterByGroupId($GroupID) - ->filterByPersonId($_SESSION['aPeopleCart'][$element['key']]) - ->findOneOrCreate() - ->setRoleId($RoleID) - ->save(); + public static function getEmailLink() + { + /* @var $cartPerson ChurchCRM\Person */ + $people = Cart::getCartPeople(); + $emailAddressArray = []; + foreach ($people as $cartPerson) { + if (!empty($cartPerson->getEmail())) { + array_push($emailAddressArray, $cartPerson->getEmail()); + } + } + $delimiter = AuthenticationManager::GetCurrentUser()->getUserConfigString('sMailtoDelimiter'); + $sEmailLink = implode($delimiter, array_unique(array_filter($emailAddressArray))); + if (!empty(SystemConfig::getValue('sToEmailAddress')) && !stristr($sEmailLink, SystemConfig::getValue('sToEmailAddress'))) { + $sEmailLink .= $delimiter.SystemConfig::getValue('sToEmailAddress'); + } + + return $sEmailLink; + } + + public static function getSMSLink() + { + /* @var $cartPerson ChurchCRM\Person */ + $people = Cart::getCartPeople(); + $SMSNumberArray = []; + foreach ($people as $cartPerson) { + if (!empty($cartPerson->getCellPhone())) { + array_push($SMSNumberArray, $cartPerson->getCellPhone()); + } + } + $sSMSLink = implode(',', $SMSNumberArray); - /* - This part of code should be done - */ - // Check if this group has special properties - /* $sSQL = 'SELECT grp_hasSpecialProps FROM group_grp WHERE grp_ID = '.$iGroupID; - $rsTemp = RunQuery($sSQL); - $rowTemp = mysqli_fetch_row($rsTemp); - $bHasProp = $rowTemp[0]; - - if ($bHasProp == 'true') { - $sSQL = 'INSERT INTO groupprop_'.$iGroupID." (per_ID) VALUES ('".$iPersonID."')"; - RunQuery($sSQL); - } */ - - $iCount += 1; - } - - $_SESSION['aPeopleCart'] = []; - } - - public static function getCartPeople() { - - $people = PersonQuery::create() - ->filterById($_SESSION['aPeopleCart']) - ->find(); - return $people; - } - - public static function getEmailLink() { - /* @var $cartPerson ChurchCRM\Person */ - $people = Cart::getCartPeople(); - $emailAddressArray = array(); - foreach($people as $cartPerson) { - if (!empty($cartPerson->getEmail())) { - array_push($emailAddressArray, $cartPerson->getEmail()); - } - } - $delimiter = AuthenticationManager::GetCurrentUser()->getUserConfigString("sMailtoDelimiter"); - $sEmailLink = implode($delimiter, array_unique(array_filter($emailAddressArray))); - if (!empty(SystemConfig::getValue('sToEmailAddress')) && !stristr($sEmailLink, SystemConfig::getValue('sToEmailAddress'))) { - $sEmailLink .= $delimiter . SystemConfig::getValue('sToEmailAddress'); - } - return $sEmailLink; - } - - public static function getSMSLink() { - - /* @var $cartPerson ChurchCRM\Person */ - $people = Cart::getCartPeople(); - $SMSNumberArray = array(); - foreach($people as $cartPerson) - { - if (!empty($cartPerson->getCellPhone())) { - array_push($SMSNumberArray, $cartPerson->getCellPhone()); - } - } - $sSMSLink = implode(",", $SMSNumberArray); - return $sSMSLink; - } - - public static function EmptyAll() { - Cart::RemovePersonArray($_SESSION['aPeopleCart']); - } + return $sSMSLink; + } + + public static function EmptyAll() + { + Cart::RemovePersonArray($_SESSION['aPeopleCart']); + } } diff --git a/src/ChurchCRM/dto/ChurchCRMRelease.php b/src/ChurchCRM/dto/ChurchCRMRelease.php index 326a5d3916..be5f216e5b 100644 --- a/src/ChurchCRM/dto/ChurchCRMRelease.php +++ b/src/ChurchCRM/dto/ChurchCRMRelease.php @@ -1,53 +1,46 @@ rawRelease = $releaseArray; - $versions = explode(".",$releaseArray["name"]); + $versions = explode('.', $releaseArray['name']); $this->MAJOR = $versions[0]; $this->MINOR = $versions[1]; $this->PATCH = $versions[2]; } - - public function equals(ChurchCRMRelease $b) { + public function equals(ChurchCRMRelease $b) + { return $this->MAJOR == $b->MAJOR && $this->MINOR == $b->MINOR && $this->PATCH == $b->PATCH; } - public function compareTo(ChurchCRMRelease $b) { - if ($this->MAJOR < $b->MAJOR ) - { + public function compareTo(ChurchCRMRelease $b) + { + if ($this->MAJOR < $b->MAJOR) { return -1; - } - elseif ($this->MAJOR > $b->MAJOR ) { + } elseif ($this->MAJOR > $b->MAJOR) { return 1; - } - elseif ($this->MAJOR == $b->MAJOR ) { + } elseif ($this->MAJOR == $b->MAJOR) { if ($this->MINOR < $b->MINOR) { return -1; - } - elseif ($this->MINOR > $b->MINOR) { + } elseif ($this->MINOR > $b->MINOR) { return 1; - } - elseif ($this->MINOR == $b->MINOR) { - if ($this->PATCH < $b->PATCH) - { + } elseif ($this->MINOR == $b->MINOR) { + if ($this->PATCH < $b->PATCH) { return -1; - } - else if ($this->PATCH > $b->PATCH) { + } elseif ($this->PATCH > $b->PATCH) { return 1; - } - else if($this->PATCH == $b->PATCH) { + } elseif ($this->PATCH == $b->PATCH) { return 0; } } @@ -56,32 +49,33 @@ public function compareTo(ChurchCRMRelease $b) { public function __toString() { - try - { - return (string) $this->MAJOR.".".$this->MINOR.".".$this->PATCH; - } - catch (Exception $exception) - { + try { + return (string) $this->MAJOR.'.'.$this->MINOR.'.'.$this->PATCH; + } catch (Exception $exception) { return ''; } } - public function getDownloadURL() { + public function getDownloadURL() + { foreach ($this->rawRelease['assets'] as $asset) { - if ($asset['name'] == "ChurchCRM-" . $this->rawRelease['name'] . ".zip") { - $url = $asset['browser_download_url']; + if ($asset['name'] == 'ChurchCRM-'.$this->rawRelease['name'].'.zip') { + $url = $asset['browser_download_url']; } } + return $url; } - public function getReleaseNotes(): string { + public function getReleaseNotes(): string + { return $this->rawRelease['body']; } - public function isPreRelease(): bool { - // yeah, it's a boolean in the JSON, but + public function isPreRelease(): bool + { + // yeah, it's a boolean in the JSON, but // let's check it to be sure this function returns a boolean. return $this->rawRelease['prerelease'] == true; } -} \ No newline at end of file +} diff --git a/src/ChurchCRM/dto/ChurchCRMReleaseManager.php b/src/ChurchCRM/dto/ChurchCRMReleaseManager.php index 75f1c08e50..5b0db24e76 100644 --- a/src/ChurchCRM/dto/ChurchCRMReleaseManager.php +++ b/src/ChurchCRM/dto/ChurchCRMReleaseManager.php @@ -8,8 +8,8 @@ use ChurchCRM\FileSystemUtils; use Github\Client; -class ChurchCRMReleaseManager { - +class ChurchCRMReleaseManager +{ // todo: make these const variables private after deprecating PHP7.0 #4948 const GITHUB_USER_NAME = 'churchcrm'; const GITHUB_REPOSITORY_NAME = 'crm'; @@ -17,34 +17,35 @@ class ChurchCRMReleaseManager { /** @var bool true when an upgrade is in progress */ private static $isUpgradeInProgress; - public static function getReleaseFromString(string $releaseString): ChurchCRMRelease { - if ( empty($_SESSION['ChurchCRMReleases'] )) { + public static function getReleaseFromString(string $releaseString): ChurchCRMRelease + { + if (empty($_SESSION['ChurchCRMReleases'])) { // The ChurchCRM releases have not yet been populated. // Since populating the release list can be an expensive operation // don't do it here, but rather wait for SystemServer TimerJobs to take care of it // just give the requestor a skeleton object - LoggerUtils::getAppLogger()->debug("Query for release string " . $releaseString . " occurred before GitHub releases were populated. Providing skeleton release object"); - return new ChurchCRMRelease(@["name" => $releaseString]); - } - else { - LoggerUtils::getAppLogger()->debug("Attempting to service query for release string " . $releaseString . " from GitHub release cache"); - $requestedRelease = array_values(array_filter($_SESSION['ChurchCRMReleases'],function($r) use ($releaseString) { + LoggerUtils::getAppLogger()->debug('Query for release string '.$releaseString.' occurred before GitHub releases were populated. Providing skeleton release object'); + + return new ChurchCRMRelease(@['name' => $releaseString]); + } else { + LoggerUtils::getAppLogger()->debug('Attempting to service query for release string '.$releaseString.' from GitHub release cache'); + $requestedRelease = array_values(array_filter($_SESSION['ChurchCRMReleases'], function ($r) use ($releaseString) { return $r->__toString() == $releaseString; })); - if (count($requestedRelease) == 1 && $requestedRelease[0] instanceof ChurchCRMRelease){ + if (count($requestedRelease) == 1 && $requestedRelease[0] instanceof ChurchCRMRelease) { // this should be the case 99% of the time - the current version of the software has exactly one release on the GitHub account - LoggerUtils::getAppLogger()->debug("Query for release string " . $releaseString . " serviced from GitHub release cache"); + LoggerUtils::getAppLogger()->debug('Query for release string '.$releaseString.' serviced from GitHub release cache'); + return $requestedRelease[0]; - } - elseif (count($requestedRelease) == 0) { + } elseif (count($requestedRelease) == 0) { // this will generally happen on dev or demo site instances // where the currently running software has not yet been released / tagged on GitHun - LoggerUtils::getAppLogger()->debug("Query for release string " . $releaseString . " did not match any GitHub releases. Providing skeleton release object"); - return new ChurchCRMRelease(@["name" => $releaseString]); - } - else { + LoggerUtils::getAppLogger()->debug('Query for release string '.$releaseString.' did not match any GitHub releases. Providing skeleton release object'); + + return new ChurchCRMRelease(@['name' => $releaseString]); + } else { // This should _never_ happen. - throw new \Exception("Provided string matched more than one ChurchCRM Release: " . \json_encode($requestedRelease)); + throw new \Exception('Provided string matched more than one ChurchCRM Release: '.\json_encode($requestedRelease)); } } } @@ -52,179 +53,191 @@ public static function getReleaseFromString(string $releaseString): ChurchCRMRel /** * @return ChurchCRMRelease[] */ - private static function populateReleases(): array{ + private static function populateReleases(): array + { $client = new Client(); - $eligibleReleases = array(); - LoggerUtils::getAppLogger()->debug("Querying GitHub '".ChurchCRMReleaseManager::GITHUB_USER_NAME."/".ChurchCRMReleaseManager::GITHUB_REPOSITORY_NAME."' for ChurchCRM Releases"); + $eligibleReleases = []; + LoggerUtils::getAppLogger()->debug("Querying GitHub '".ChurchCRMReleaseManager::GITHUB_USER_NAME.'/'.ChurchCRMReleaseManager::GITHUB_REPOSITORY_NAME."' for ChurchCRM Releases"); $gitHubReleases = $client->api('repo')->releases()->all(ChurchCRMReleaseManager::GITHUB_USER_NAME, ChurchCRMReleaseManager::GITHUB_REPOSITORY_NAME); - LoggerUtils::getAppLogger()->debug("Received ". count($gitHubReleases) . " ChurchCRM releases from GitHub"); - foreach($gitHubReleases as $r) - { + LoggerUtils::getAppLogger()->debug('Received '.count($gitHubReleases).' ChurchCRM releases from GitHub'); + foreach ($gitHubReleases as $r) { $release = new ChurchCRMRelease($r); - if ($release->isPreRelease()){ - if (SystemConfig::getBooleanValue("bAllowPrereleaseUpgrade")){ - LoggerUtils::getAppLogger()->debug("bAllowPrereleaseUpgrade allows upgrade to a pre-release version. Including ".$release." for consideration"); - array_push($eligibleReleases,$release); - } - else { - LoggerUtils::getAppLogger()->debug("bAllowPrereleaseUpgrade disallows upgrade to a pre-release version. Not including ".$release." for consideration"); + if ($release->isPreRelease()) { + if (SystemConfig::getBooleanValue('bAllowPrereleaseUpgrade')) { + LoggerUtils::getAppLogger()->debug('bAllowPrereleaseUpgrade allows upgrade to a pre-release version. Including '.$release.' for consideration'); + array_push($eligibleReleases, $release); + } else { + LoggerUtils::getAppLogger()->debug('bAllowPrereleaseUpgrade disallows upgrade to a pre-release version. Not including '.$release.' for consideration'); } - } - else { - LoggerUtils::getAppLogger()->debug($release." is not a pre-release version. Including for consideration"); + } else { + LoggerUtils::getAppLogger()->debug($release.' is not a pre-release version. Including for consideration'); array_push($eligibleReleases, $release); } - - } - usort($eligibleReleases, function(ChurchCRMRelease $a, ChurchCRMRelease $b){ + usort($eligibleReleases, function (ChurchCRMRelease $a, ChurchCRMRelease $b) { return $a->compareTo($b) < 0; }); - LoggerUtils::getAppLogger()->debug("Found " . count($eligibleReleases) . " eligible ChurchCRM releases on GitHub"); + LoggerUtils::getAppLogger()->debug('Found '.count($eligibleReleases).' eligible ChurchCRM releases on GitHub'); + return $eligibleReleases; } - - - public static function checkForUpdates() { + public static function checkForUpdates() + { $_SESSION['ChurchCRMReleases'] = self::populateReleases(); } - public static function isReleaseCurrent(ChurchCRMRelease $Release) : bool { - if ( empty($_SESSION['ChurchCRMReleases'] )) { + public static function isReleaseCurrent(ChurchCRMRelease $Release): bool + { + if (empty($_SESSION['ChurchCRMReleases'])) { // The ChurchCRM releases have not yet been populated. // Since populating the release list can be an expensive operation // don't do it here, but rather wait for SystemServer TimerJobs to take care of it // just tell the requestor that the provided release _is_ current return true; - - } - else { + } else { $CurrentRelease = $_SESSION['ChurchCRMReleases'][0]; - LoggerUtils::getAppLogger()->debug("Determining if ".$Release." is current by checking if equals: " . $CurrentRelease); + LoggerUtils::getAppLogger()->debug('Determining if '.$Release.' is current by checking if equals: '.$CurrentRelease); + return $CurrentRelease->equals($Release); } - } - private static function getHighestReleaseInArray (array $eligibleUpgradeTargetReleases) { - if (count($eligibleUpgradeTargetReleases) >0 ) { - usort($eligibleUpgradeTargetReleases, function(ChurchCRMRelease $a, ChurchCRMRelease $b){ + private static function getHighestReleaseInArray(array $eligibleUpgradeTargetReleases) + { + if (count($eligibleUpgradeTargetReleases) > 0) { + usort($eligibleUpgradeTargetReleases, function (ChurchCRMRelease $a, ChurchCRMRelease $b) { return $a->compareTo($b) < 0; }); + return $eligibleUpgradeTargetReleases[0]; } + return null; } - private static function getReleaseNextPatch(array $rs, ChurchCRMRelease $currentRelease) { - $eligibleUpgradeTargetReleases = array_values(array_filter($rs , function(ChurchCRMRelease $r) use ($currentRelease) { + private static function getReleaseNextPatch(array $rs, ChurchCRMRelease $currentRelease) + { + $eligibleUpgradeTargetReleases = array_values(array_filter($rs, function (ChurchCRMRelease $r) use ($currentRelease) { $isSameMajorAndMinorWithGreaterPatch = ($r->MAJOR == $currentRelease->MAJOR) && ($r->MINOR == $currentRelease->MINOR) && ($r->PATCH > $currentRelease->PATCH); - LoggerUtils::getAppLogger()->debug("Release " . $r . " is" . ($isSameMajorAndMinorWithGreaterPatch ? " ":" not ") . "a possible patch upgrade target"); + LoggerUtils::getAppLogger()->debug('Release '.$r.' is'.($isSameMajorAndMinorWithGreaterPatch ? ' ' : ' not ').'a possible patch upgrade target'); + return $isSameMajorAndMinorWithGreaterPatch; })); + return self::getHighestReleaseInArray($eligibleUpgradeTargetReleases); } - private static function getReleaseNextMinor(array $rs, ChurchCRMRelease $currentRelease) { - $eligibleUpgradeTargetReleases = array_values(array_filter($rs , function(ChurchCRMRelease $r) use ($currentRelease) { + private static function getReleaseNextMinor(array $rs, ChurchCRMRelease $currentRelease) + { + $eligibleUpgradeTargetReleases = array_values(array_filter($rs, function (ChurchCRMRelease $r) use ($currentRelease) { $isSameMajorAndMinorWithGreaterPatch = ($r->MAJOR == $currentRelease->MAJOR) && ($r->MINOR > $currentRelease->MINOR); - LoggerUtils::getAppLogger()->debug("Release " . $r . " is" . ($isSameMajorAndMinorWithGreaterPatch ? " ":" not ") . "a possible minor upgrade target"); + LoggerUtils::getAppLogger()->debug('Release '.$r.' is'.($isSameMajorAndMinorWithGreaterPatch ? ' ' : ' not ').'a possible minor upgrade target'); + return $isSameMajorAndMinorWithGreaterPatch; })); + return self::getHighestReleaseInArray($eligibleUpgradeTargetReleases); } - private static function getReleaseNextMajor(array $rs, ChurchCRMRelease $currentRelease) { - $eligibleUpgradeTargetReleases = array_values(array_filter($rs , function(ChurchCRMRelease $r) use ($currentRelease) { + private static function getReleaseNextMajor(array $rs, ChurchCRMRelease $currentRelease) + { + $eligibleUpgradeTargetReleases = array_values(array_filter($rs, function (ChurchCRMRelease $r) use ($currentRelease) { $isSameMajorAndMinorWithGreaterPatch = ($r->MAJOR > $currentRelease->MAJOR); - LoggerUtils::getAppLogger()->debug("Release " . $r . " is" . ($isSameMajorAndMinorWithGreaterPatch ? " ":" not ") . "a possible major upgrade target"); + LoggerUtils::getAppLogger()->debug('Release '.$r.' is'.($isSameMajorAndMinorWithGreaterPatch ? ' ' : ' not ').'a possible major upgrade target'); + return $isSameMajorAndMinorWithGreaterPatch; })); + return self::getHighestReleaseInArray($eligibleUpgradeTargetReleases); } - public static function getNextReleaseStep(ChurchCRMRelease $currentRelease) : ChurchCRMRelease { - - LoggerUtils::getAppLogger()->debug("Determining the next-step release step for " . $currentRelease); - if ( empty( $_SESSION['ChurchCRMReleases'] ) ) { + public static function getNextReleaseStep(ChurchCRMRelease $currentRelease): ChurchCRMRelease + { + LoggerUtils::getAppLogger()->debug('Determining the next-step release step for '.$currentRelease); + if (empty($_SESSION['ChurchCRMReleases'])) { $_SESSION['ChurchCRMReleases'] = self::populateReleases(); } $rs = array_values($_SESSION['ChurchCRMReleases']); // look for releases having the same MAJOR and MINOR versions. // Of these releases, if there is one with a newer PATCH version, // We should use the newest patch. - LoggerUtils::getAppLogger()->debug("Evaluating next-step release eligibility based on " . count($_SESSION['ChurchCRMReleases']) . " available releases "); + LoggerUtils::getAppLogger()->debug('Evaluating next-step release eligibility based on '.count($_SESSION['ChurchCRMReleases']).' available releases '); - $nextStepRelease = self::getReleaseNextPatch($rs,$currentRelease); + $nextStepRelease = self::getReleaseNextPatch($rs, $currentRelease); - if (null == $nextStepRelease) { - $nextStepRelease = self::getReleaseNextMinor($rs,$currentRelease); + if (null == $nextStepRelease) { + $nextStepRelease = self::getReleaseNextMinor($rs, $currentRelease); } - if (null == $nextStepRelease) { - $nextStepRelease = self::getReleaseNextMajor($rs,$currentRelease); + if (null == $nextStepRelease) { + $nextStepRelease = self::getReleaseNextMajor($rs, $currentRelease); } - if (null == $nextStepRelease) { - throw new \Exception("Could not identify a suitable upgrade target release. Current software version: " . $currentRelease . ". Highest available release: " . $rs[0] ) ; + if (null == $nextStepRelease) { + throw new \Exception('Could not identify a suitable upgrade target release. Current software version: '.$currentRelease.'. Highest available release: '.$rs[0]); } - LoggerUtils::getAppLogger()->info("Next upgrade step for " . $currentRelease. " is : " . $nextStepRelease); + LoggerUtils::getAppLogger()->info('Next upgrade step for '.$currentRelease.' is : '.$nextStepRelease); + return $nextStepRelease; } - public static function downloadLatestRelease() { // this is a proxy function. For now, just download the nest step release - $releaseToDownload = ChurchCRMReleaseManager::getNextReleaseStep(ChurchCRMReleaseManager::getReleaseFromString($_SESSION['sSoftwareInstalledVersion'])); + $releaseToDownload = ChurchCRMReleaseManager::getNextReleaseStep(ChurchCRMReleaseManager::getReleaseFromString($_SESSION['sSoftwareInstalledVersion'])); + return ChurchCRMReleaseManager::downloadRelease($releaseToDownload); } + public static function downloadRelease(ChurchCRMRelease $release) { - LoggerUtils::getAppLogger()->info("Downloading release: " . $release); + LoggerUtils::getAppLogger()->info('Downloading release: '.$release); $logger = LoggerUtils::getAppLogger(); - $UpgradeDir = SystemURLs::getDocumentRoot() . '/Upgrade'; + $UpgradeDir = SystemURLs::getDocumentRoot().'/Upgrade'; $url = $release->getDownloadURL(); - $logger->debug("Creating upgrade directory: " . $UpgradeDir); - if (!is_dir($UpgradeDir)){ + $logger->debug('Creating upgrade directory: '.$UpgradeDir); + if (!is_dir($UpgradeDir)) { mkdir($UpgradeDir); } - $logger->info("Downloading release from: " . $url . " to: ". $UpgradeDir . '/' . basename($url)); + $logger->info('Downloading release from: '.$url.' to: '.$UpgradeDir.'/'.basename($url)); $executionTime = new ExecutionTime(); - file_put_contents($UpgradeDir . '/' . basename($url), file_get_contents($url)); - $logger->info("Finished downloading file. Execution time: " .$executionTime->getMilliseconds()." ms"); + file_put_contents($UpgradeDir.'/'.basename($url), file_get_contents($url)); + $logger->info('Finished downloading file. Execution time: '.$executionTime->getMilliseconds().' ms'); $returnFile = []; $returnFile['fileName'] = basename($url); $returnFile['releaseNotes'] = $release->getReleaseNotes(); - $returnFile['fullPath'] = $UpgradeDir . '/' . basename($url); - $returnFile['sha1'] = sha1_file($UpgradeDir . '/' . basename($url)); - $logger->info("SHA1 hash for ". $returnFile['fullPath'] .": " . $returnFile['sha1']); - $logger->info("Release notes: " . $returnFile['releaseNotes'] ); + $returnFile['fullPath'] = $UpgradeDir.'/'.basename($url); + $returnFile['sha1'] = sha1_file($UpgradeDir.'/'.basename($url)); + $logger->info('SHA1 hash for '.$returnFile['fullPath'].': '.$returnFile['sha1']); + $logger->info('Release notes: '.$returnFile['releaseNotes']); + return $returnFile; } - public static function preShutdown() { + public static function preShutdown() + { // this is kind of code-smell // since this callback will be invoked upon PHP timeout // we aren't guaranteed any of Slim's error handling // so we need to echo a JSON document that "looks like" // an exception the client-side JS can display to the user // so they know it actually timed out. - if (self::$isUpgradeInProgress){ + if (self::$isUpgradeInProgress) { // the PHP script was stopped while an upgrade was still in progress. $logger = LoggerUtils::getAppLogger(); - $logger->addWarning("Maximum execution time threshold exceeded: " . ini_get("max_execution_time")); + $logger->addWarning('Maximum execution time threshold exceeded: '.ini_get('max_execution_time')); echo \json_encode([ - 'code' => 500, - 'message' => "Maximum execution time threshold exceeded: " . ini_get("max_execution_time") . ". This ChurchCRM installation may now be in an unstable state. Please review the documentation at https://github.com/ChurchCRM/CRM/wiki/Recovering-from-a-failed-update" + 'code' => 500, + 'message' => 'Maximum execution time threshold exceeded: '.ini_get('max_execution_time').'. This ChurchCRM installation may now be in an unstable state. Please review the documentation at https://github.com/ChurchCRM/CRM/wiki/Recovering-from-a-failed-update', ]); } } + public static function doUpgrade($zipFilename, $sha1) { self::$isUpgradeInProgress = true; @@ -233,43 +246,44 @@ public static function doUpgrade($zipFilename, $sha1) // in the event this upgrade job times-out the // PHP instance's max_execution_time $displayErrors = ini_get('display_errors'); - ini_set('display_errors',0); - register_shutdown_function(function() { + ini_set('display_errors', 0); + register_shutdown_function(function () { return ChurchCRMReleaseManager::preShutdown(); }); $logger = LoggerUtils::getAppLogger(); - $logger->info("Beginnging upgrade process"); - $logger->info("PHP max_execution_time is now: " . ini_get("max_execution_time")); - $logger->info("Beginning hash validation on " . $zipFilename); + $logger->info('Beginnging upgrade process'); + $logger->info('PHP max_execution_time is now: '.ini_get('max_execution_time')); + $logger->info('Beginning hash validation on '.$zipFilename); if ($sha1 == sha1_file($zipFilename)) { - $logger->info("Hash validation succeeded on " . $zipFilename . " Got: " . sha1_file($zipFilename)); + $logger->info('Hash validation succeeded on '.$zipFilename.' Got: '.sha1_file($zipFilename)); $zip = new \ZipArchive(); if ($zip->open($zipFilename) == true) { - $logger->info("Extracting " . $zipFilename." to: " . SystemURLs::getDocumentRoot() . '/Upgrade'); - $executionTime = new ExecutionTime(); - $zip->extractTo(SystemURLs::getDocumentRoot() . '/Upgrade'); - $zip->close(); - $logger->info("Extraction completed. Took:" . $executionTime->getMilliseconds()); - $logger->info("Moving extracted zip into place"); - $executionTime = new ExecutionTime(); - FileSystemUtils::moveDir(SystemURLs::getDocumentRoot() . '/Upgrade/churchcrm', SystemURLs::getDocumentRoot()); - $logger->info("Move completed. Took:" . $executionTime->getMilliseconds()); + $logger->info('Extracting '.$zipFilename.' to: '.SystemURLs::getDocumentRoot().'/Upgrade'); + $executionTime = new ExecutionTime(); + $zip->extractTo(SystemURLs::getDocumentRoot().'/Upgrade'); + $zip->close(); + $logger->info('Extraction completed. Took:'.$executionTime->getMilliseconds()); + $logger->info('Moving extracted zip into place'); + $executionTime = new ExecutionTime(); + FileSystemUtils::moveDir(SystemURLs::getDocumentRoot().'/Upgrade/churchcrm', SystemURLs::getDocumentRoot()); + $logger->info('Move completed. Took:'.$executionTime->getMilliseconds()); } - $logger->info("Deleting zip archive: ".$zipFilename); + $logger->info('Deleting zip archive: '.$zipFilename); unlink($zipFilename); SystemConfig::setValue('sLastIntegrityCheckTimeStamp', null); - $logger->debug("Set sLastIntegrityCheckTimeStamp to null"); - $logger->info("Upgrade process complete"); - ini_set('display_errors',$displayErrors); + $logger->debug('Set sLastIntegrityCheckTimeStamp to null'); + $logger->info('Upgrade process complete'); + ini_set('display_errors', $displayErrors); self::$isUpgradeInProgress = false; + return 'success'; } else { self::$isUpgradeInProgress = false; - ini_set('display_errors',$displayErrors); - $logger->err("Hash validation failed on " . $zipFilename.". Expected: ".$sha1. ". Got: ".sha1_file($zipFilename)); + ini_set('display_errors', $displayErrors); + $logger->err('Hash validation failed on '.$zipFilename.'. Expected: '.$sha1.'. Got: '.sha1_file($zipFilename)); + return 'hash validation failure'; } } - } diff --git a/src/ChurchCRM/dto/ChurchMetaData.php b/src/ChurchCRM/dto/ChurchMetaData.php index 86df4a7cab..e0b220ce3b 100644 --- a/src/ChurchCRM/dto/ChurchMetaData.php +++ b/src/ChurchCRM/dto/ChurchMetaData.php @@ -1,4 +1,5 @@ filterById(1)->orderByOptionSequence()->find(); } - public static function getName($clsId) { + public static function getName($clsId) + { $classification = ListOptionQuery::create()->filterById(1)->filterByOptionId($clsId)->findOne(); if (!empty($classification)) { return $classification->getOptionName(); } - return ""; - } + return ''; + } } diff --git a/src/ChurchCRM/dto/ConfigItem.php b/src/ChurchCRM/dto/ConfigItem.php index 15edaa482f..0750f7ed81 100644 --- a/src/ChurchCRM/dto/ConfigItem.php +++ b/src/ChurchCRM/dto/ConfigItem.php @@ -1,122 +1,122 @@ id = $id; - $this->name = $name; - $this->type = $type; - $this->default = $default; - $this->tooltip = $tooltip; - $this->data = $data; - $this->url = $url; - } - - public function getId() - { - return $this->id; - } - - public function getName() - { - return $this->name; - } - - public function getUrl() - { - return $this->url; - } + private $id; + private $name; + private $value; + private $type; + private $default; + private $tooltip; + private $url; + private $data; + private $dbConfigItem; + + public function __construct($id, $name, $type, $default, $tooltip = '', $url = '', $data = '') + { + $this->id = $id; + $this->name = $name; + $this->type = $type; + $this->default = $default; + $this->tooltip = $tooltip; + $this->data = $data; + $this->url = $url; + } + public function getId() + { + return $this->id; + } - public function setDBConfigObject($dbConfigItem) - { - $this->dbConfigItem = $dbConfigItem; - $this->value = $dbConfigItem->getValue(); - } - - public function getDBConfigObject() - { - return $this->dbConfigItem ; - } - - public function getValue() - { - if ( isset( $this->value ) ) + public function getName() { - return $this->value; + return $this->name; } - else + + public function getUrl() { - return $this->default; + return $this->url; } - } - public function getBooleanValue() - { - return boolval($this->getValue()); - } + public function setDBConfigObject($dbConfigItem) + { + $this->dbConfigItem = $dbConfigItem; + $this->value = $dbConfigItem->getValue(); + } - public function setValue($value) - { - if ( $value == $this->getDefault() ) + public function getDBConfigObject() { - //if the value is being set to the default value - if ( isset ($this->dbConfigItem) ) //and the item exists - { - //delete the item - $this->dbConfigItem->delete(); - } + return $this->dbConfigItem; } - else + + public function getValue() { - //if the value is being set to a non-default value - if ( ! isset ($this->dbConfigItem) ) - { - //create the item if it doesnt exist - $this->dbConfigItem = new Config(); - $this->dbConfigItem->setId($this->getId()); - $this->dbConfigItem->setName($this->getName()); - } - //set the values, and save it - $this->dbConfigItem->setValue($value); - $this->dbConfigItem->save(); - $this->value=$value; + if (isset($this->value)) { + return $this->value; + } else { + return $this->default; + } } - } - public function getDefault() - { - return $this->default; - } + public function getBooleanValue() + { + return boolval($this->getValue()); + } + public function setValue($value) + { + if ($value == $this->getDefault()) { + //if the value is being set to the default value + if (isset($this->dbConfigItem)) { //and the item exists + //delete the item + $this->dbConfigItem->delete(); + } + } else { + //if the value is being set to a non-default value + if (!isset($this->dbConfigItem)) { + //create the item if it doesnt exist + $this->dbConfigItem = new Config(); + $this->dbConfigItem->setId($this->getId()); + $this->dbConfigItem->setName($this->getName()); + } + //set the values, and save it + $this->dbConfigItem->setValue($value); + $this->dbConfigItem->save(); + $this->value = $value; + } + } - public function getType() - { - return $this->type; - } + public function getDefault() + { + return $this->default; + } - public function getTooltip() - { - return $this->tooltip; - } + public function getType() + { + return $this->type; + } - public function getSection() - { - return $this->section; - } + public function getTooltip() + { + return $this->tooltip; + } - public function getCategory() - { - return $this->category; - } + public function getSection() + { + return $this->section; + } - public function getData() - { - return $this->data; - } + public function getCategory() + { + return $this->category; + } + public function getData() + { + return $this->data; + } } diff --git a/src/ChurchCRM/dto/FullCalendarEvent.php b/src/ChurchCRM/dto/FullCalendarEvent.php index eb5851c5f4..ad13c85fac 100644 --- a/src/ChurchCRM/dto/FullCalendarEvent.php +++ b/src/ChurchCRM/dto/FullCalendarEvent.php @@ -1,39 +1,40 @@ title = $CRMEvent->getTitle(); - $this->start = $CRMEvent->getStart("c"); - $this->end = $CRMEvent->getEnd("c"); - $this->allDay = ( $CRMEvent->getEnd() == null ? true:false); + $this->start = $CRMEvent->getStart('c'); + $this->end = $CRMEvent->getEnd('c'); + $this->allDay = ($CRMEvent->getEnd() == null ? true : false); $this->id = $CRMEvent->getId(); - $this->backgroundColor = "#".$CRMCalendar->getBackgroundColor(); - $this->textColor = "#".$CRMCalendar->getForegroundColor(); + $this->backgroundColor = '#'.$CRMCalendar->getBackgroundColor(); + $this->textColor = '#'.$CRMCalendar->getForegroundColor(); $this->editable = $CRMEvent->isEditable(); $this->url = $CRMEvent->getURL(); - } + } } diff --git a/src/ChurchCRM/dto/KioskAssignmentTypes.php b/src/ChurchCRM/dto/KioskAssignmentTypes.php index 52a2b9b473..c498b055af 100644 --- a/src/ChurchCRM/dto/KioskAssignmentTypes.php +++ b/src/ChurchCRM/dto/KioskAssignmentTypes.php @@ -4,10 +4,8 @@ abstract class KioskAssignmentTypes { - const EVENTATTENDANCEKIOSK = 1; - const SELFREGISTRATIONKIOSK = 2; - const SELFCHECKINKIOSK = 3; - const GENERALATTENDANCEKIOSK = 4; + const EVENTATTENDANCEKIOSK = 1; + const SELFREGISTRATIONKIOSK = 2; + const SELFCHECKINKIOSK = 3; + const GENERALATTENDANCEKIOSK = 4; } - -?> \ No newline at end of file diff --git a/src/ChurchCRM/dto/LocaleInfo.php b/src/ChurchCRM/dto/LocaleInfo.php index 14e0167652..f7cdc68926 100644 --- a/src/ChurchCRM/dto/LocaleInfo.php +++ b/src/ChurchCRM/dto/LocaleInfo.php @@ -19,15 +19,15 @@ public function __construct($locale, $userLocale) if (!empty($userLocale)) { $this->locale = $userLocale->getValue(); } - $localesFile = file_get_contents(SystemURLs::getDocumentRoot() . "/locale/locales.json"); + $localesFile = file_get_contents(SystemURLs::getDocumentRoot().'/locale/locales.json'); $locales = json_decode($localesFile, true); foreach ($locales as $key => $value) { - if ($value["locale"] == $this->locale) { + if ($value['locale'] == $this->locale) { $this->name = $key; - $this->language = $value["languageCode"]; - $this->country = $value["countryCode"]; - $this->dataTables = $value["dataTables"]; - $this->poLocaleId = $value["poEditor"]; + $this->language = $value['languageCode']; + $this->country = $value['countryCode']; + $this->dataTables = $value['dataTables']; + $this->poLocaleId = $value['poEditor']; } } } @@ -97,7 +97,7 @@ public function getLocaleArray() $localArray = []; array_push($localArray, $this->getLanguageCode()); foreach ($utfList as $item) { - array_push($localArray, $this->getLanguageCode() . $item); + array_push($localArray, $this->getLanguageCode().$item); } return $localArray; diff --git a/src/ChurchCRM/dto/MenuEventsCount.php b/src/ChurchCRM/dto/MenuEventsCount.php index f28d88740e..dd7bb1bdc0 100644 --- a/src/ChurchCRM/dto/MenuEventsCount.php +++ b/src/ChurchCRM/dto/MenuEventsCount.php @@ -14,10 +14,8 @@ use ChurchCRM\PersonQuery; use Propel\Runtime\ActiveQuery\Criteria; - class MenuEventsCount { - public static function getBirthDates() { $peopleWithBirthDays = PersonQuery::create() diff --git a/src/ChurchCRM/dto/Notification.php b/src/ChurchCRM/dto/Notification.php index 6b483aead5..fb8d4d679b 100644 --- a/src/ChurchCRM/dto/Notification.php +++ b/src/ChurchCRM/dto/Notification.php @@ -2,130 +2,115 @@ namespace ChurchCRM\dto; - use ChurchCRM\Emails\NotificationEmail; use Vonage\Client; use Vonage\Client\Credentials\Basic; class Notification { + protected $projectorText; + protected $recipients; + protected $person; - protected $projectorText; - protected $recipients; - protected $person; - - public function __construct() - { - - } - - public function setRecipients($recipients) - { - $this->recipients = $recipients; - - } - - public function setSMSText($text) - { - - } - - public function setEmailText($text) - { - - } + public function __construct() + { + } - public function setPerson(\ChurchCRM\Person $Person) - { - $this->person = $Person; - } + public function setRecipients($recipients) + { + $this->recipients = $recipients; + } - public function setProjectorText($text) - { - $this->projectorText=$text; - } + public function setSMSText($text) + { + } - private function sendEmail() - { - $emailaddresses = []; - Foreach ($this->recipients as $recipient) + public function setEmailText($text) { - array_push($emailaddresses,$recipient->getEmail()); } - try + + public function setPerson(\ChurchCRM\Person $Person) { - $email = new NotificationEmail($emailaddresses,$this->person->getFullName()); - $emailStatus=$email->send(); - return $emailStatus; - } catch (Exception $ex) { - return false; + $this->person = $Person; } - } + public function setProjectorText($text) + { + $this->projectorText = $text; + } - private function sendSMS() - { - try - { + private function sendEmail() + { + $emailaddresses = []; + foreach ($this->recipients as $recipient) { + array_push($emailaddresses, $recipient->getEmail()); + } - $client = new Client(new Basic(SystemConfig::getValue("sNexmoAPIKey"),SystemConfig::getValue("sNexmoAPISecret"))); + try { + $email = new NotificationEmail($emailaddresses, $this->person->getFullName()); + $emailStatus = $email->send(); - Foreach ($this->recipients as $recipient) - { - $message = $client->message()->sendText([ - 'to' => $recipient->getNumericCellPhone(), - 'from' => SystemConfig::getValue("sNexmoFromNumber"), - 'text' => gettext('Notification for') . " " . $this->person->getFullName() - ]); + return $emailStatus; + } catch (Exception $ex) { + return false; } - return $message; - } catch (Exception $ex) { - return false; - } - - } - - private function sendProjector() - { - try - { - $OLPAlert = new OpenLPNotification(SystemConfig::getValue("sOLPURL"), - SystemConfig::getValue("sOLPUserName"), - SystemConfig::getValue("sOLPPassword")); - $OLPAlert->setAlertText($this->projectorText); - return $OLPAlert->send(); - } catch (Exception $ex) { - return false; - } - - } - - public function send() - { - - $methods = []; - if(SystemConfig::hasValidMailServerSettings()) - { - $send = $this->sendEmail(); - array_push($methods,"email: ".$send); } - if (SystemConfig::hasValidSMSServerSettings()) + + private function sendSMS() { - $send = (boolean)$this->sendSMS(); - array_push($methods,"sms: ".$send); + try { + $client = new Client(new Basic(SystemConfig::getValue('sNexmoAPIKey'), SystemConfig::getValue('sNexmoAPISecret'))); + + foreach ($this->recipients as $recipient) { + $message = $client->message()->sendText([ + 'to' => $recipient->getNumericCellPhone(), + 'from' => SystemConfig::getValue('sNexmoFromNumber'), + 'text' => gettext('Notification for').' '.$this->person->getFullName(), + ]); + } + + return $message; + } catch (Exception $ex) { + return false; + } } - if(SystemConfig::hasValidOpenLPSettings()) + + private function sendProjector() { - $send = (boolean)($this->sendProjector()); - array_push($methods,"projector: ".$send); + try { + $OLPAlert = new OpenLPNotification( + SystemConfig::getValue('sOLPURL'), + SystemConfig::getValue('sOLPUserName'), + SystemConfig::getValue('sOLPPassword') + ); + $OLPAlert->setAlertText($this->projectorText); + + return $OLPAlert->send(); + } catch (Exception $ex) { + return false; + } } - $sendStatus = [ - "status"=>"", - "methods"=>$methods - ]; - - return json_encode($sendStatus); - } + public function send() + { + $methods = []; + if (SystemConfig::hasValidMailServerSettings()) { + $send = $this->sendEmail(); + array_push($methods, 'email: '.$send); + } + if (SystemConfig::hasValidSMSServerSettings()) { + $send = (bool) $this->sendSMS(); + array_push($methods, 'sms: '.$send); + } + if (SystemConfig::hasValidOpenLPSettings()) { + $send = (bool) $this->sendProjector(); + array_push($methods, 'projector: '.$send); + } + $sendStatus = [ + 'status' => '', + 'methods'=> $methods, + ]; + return json_encode($sendStatus); + } } diff --git a/src/ChurchCRM/dto/Notification/UiNotification.php b/src/ChurchCRM/dto/Notification/UiNotification.php index cbba465a2a..b28adbd462 100644 --- a/src/ChurchCRM/dto/Notification/UiNotification.php +++ b/src/ChurchCRM/dto/Notification/UiNotification.php @@ -1,6 +1,7 @@ title = $title; $this->message = $message; @@ -101,10 +103,8 @@ public function getAlign() return $this->align; } - public function jsonSerialize() { return get_object_vars($this); } - } diff --git a/src/ChurchCRM/dto/OpenLPNotification.php b/src/ChurchCRM/dto/OpenLPNotification.php index 9ef44f2f09..652a6425f6 100644 --- a/src/ChurchCRM/dto/OpenLPNotification.php +++ b/src/ChurchCRM/dto/OpenLPNotification.php @@ -2,57 +2,56 @@ namespace ChurchCRM\dto; - class OpenLPNotification { - protected $OLPAddress; - protected $OLPUsername; - protected $OLPPassword; - protected $AlertText; - - public function __construct($OLPAddress,$OLPUsername,$OLPPassword) - { - $this->OLPAddress=$OLPAddress; - $this->OLPUsername=$OLPUsername; - $this->OLPPassword=$OLPPassword; - } - - public function setAlertText($text) - { - $this->AlertText = (string)$text; - } - - private function getAuthorizationHeader() - { - return base64_encode(SystemConfig::getValue("sOLPUserName").":".SystemConfig::getValue("sOLPPassword")); - } - - public function send() - { - $headers = array ( - 'http'=>array( - 'method' =>"GET", - 'timeout' => 5 - ), - "ssl" => array( - "verify_peer" => false, - "verify_peer_name" => false, - "allow_self_signed" => true, - ) - ); - if(SystemConfig::getValue("sOLPUserName")) + protected $OLPAddress; + protected $OLPUsername; + protected $OLPPassword; + protected $AlertText; + + public function __construct($OLPAddress, $OLPUsername, $OLPPassword) + { + $this->OLPAddress = $OLPAddress; + $this->OLPUsername = $OLPUsername; + $this->OLPPassword = $OLPPassword; + } + + public function setAlertText($text) + { + $this->AlertText = (string) $text; + } + + private function getAuthorizationHeader() + { + return base64_encode(SystemConfig::getValue('sOLPUserName').':'.SystemConfig::getValue('sOLPPassword')); + } + + public function send() { - $headers['http']['header'] = "Authorization: Basic ".$this->getAuthorizationHeader()."\r\n"; + $headers = [ + 'http'=> [ + 'method' => 'GET', + 'timeout' => 5, + ], + 'ssl' => [ + 'verify_peer' => false, + 'verify_peer_name' => false, + 'allow_self_signed' => true, + ], + ]; + if (SystemConfig::getValue('sOLPUserName')) { + $headers['http']['header'] = 'Authorization: Basic '.$this->getAuthorizationHeader()."\r\n"; + } + //return json_encode($headers); + $request = [ + 'request' => [ + 'text' => $this->AlertText, + ], + ]; + $url = $this->OLPAddress.'/api/alert?data='.urlencode(json_encode($request)); + $context = stream_context_create($headers); + $response = file_get_contents($url, false, $context); + + return $response; } - //return json_encode($headers); - $request = array( - "request" => array( - "text" =>$this->AlertText - ) - ); - $url = $this->OLPAddress."/api/alert?data=".urlencode(json_encode($request)); - $context = stream_context_create($headers); - $response = file_get_contents($url,false,$context); - return $response; - } -} \ No newline at end of file +} diff --git a/src/ChurchCRM/dto/PeopleCustomField.php b/src/ChurchCRM/dto/PeopleCustomField.php index d304ecf215..3e0584c30c 100644 --- a/src/ChurchCRM/dto/PeopleCustomField.php +++ b/src/ChurchCRM/dto/PeopleCustomField.php @@ -2,20 +2,21 @@ namespace ChurchCRM\dto; -use ChurchCRM\PersonQuery; use ChurchCRM\ListOptionQuery; +use ChurchCRM\PersonQuery; -Class PeopleCustomField { - +class PeopleCustomField +{ private $name; private $value; private $formattedValue; private $link; - private $icon = "fa fa-tag"; + private $icon = 'fa fa-tag'; private $displayValue; /** * PeopleCustomField constructor. + * * @param $name */ public function __construct($masterField, $value) @@ -26,24 +27,24 @@ public function __construct($masterField, $value) $masterField->getName(); if ($masterField->getTypeId() == 9) { - $this->icon = "fa fa-user"; - $this->link = SystemURLs::getRootPath() .'/PersonView.php?PersonID=' . $this->value; + $this->icon = 'fa fa-user'; + $this->link = SystemURLs::getRootPath().'/PersonView.php?PersonID='.$this->value; $person = PersonQuery::create()->findPk($this->value); if ($person) { $this->formattedValue = $person->getFullName(); } else { - $this->formattedValue = gettext("Unexpected Person Id"). " : " . $this->value; + $this->formattedValue = gettext('Unexpected Person Id').' : '.$this->value; } - } elseif ($masterField->getTypeId() == 11) { + } elseif ($masterField->getTypeId() == 11) { //$custom_Special = $sPhoneCountry; - $this->icon = "fa fa-phone"; - $this->link = "tel:".$this->value; + $this->icon = 'fa fa-phone'; + $this->link = 'tel:'.$this->value; } elseif ($masterField->getTypeId() == 12) { $customOption = ListOptionQuery::create()->filterById($masterField->getCustomSpecial())->filterByOptionId($this->value)->findOne(); if ($customOption != null) { - $this->formattedValue = $customOption->getOptionName(); + $this->formattedValue = $customOption->getOptionName(); } else { - $this->formattedValue = $this->value . " ( ". gettext("Deleted") ." )"; + $this->formattedValue = $this->value.' ( '.gettext('Deleted').' )'; } } } @@ -95,7 +96,4 @@ public function getDisplayValue() { return $this->displayValue; } - - - } diff --git a/src/ChurchCRM/dto/Photo.php b/src/ChurchCRM/dto/Photo.php index 29c5fe3008..3071c35e08 100644 --- a/src/ChurchCRM/dto/Photo.php +++ b/src/ChurchCRM/dto/Photo.php @@ -5,313 +5,339 @@ use ChurchCRM\FamilyQuery; use ChurchCRM\PersonQuery; -class Photo { - private $photoType; - private $id; - private $photoURI; - private $photoThumbURI; - private $thubmnailPath; - private $photoContentType; - private $remotesEnabled; - public static $validExtensions = ["png", "jpeg", "jpg"]; - - public function __construct($photoType,$id) { - $this->photoType = $photoType; - $this->id = $id; - $this->remotesEnabled = SystemConfig::getBooleanValue('bEnableGooglePhotos') || SystemConfig::getBooleanValue('bEnableGravatarPhotos'); - $this->photoHunt(); - } - - public static function getValidExtensions() { - return Photo::$validExtensions; - } - - private function setURIs($photoPath) { - $this->photoURI = $photoPath; - $this->thubmnailPath = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/thumbnails/"; - $this->photoThumbURI = $this->thubmnailPath . $this->id . ".jpg"; - } - - private function shouldRefreshPhotoFile($photoFile) { - if ($this->remotesEnabled) { - // if the system has remotes enabled, calculate the cutoff timestamp for refreshing remote photos. - $remotecachethreshold = date_create(); - date_sub($remotecachethreshold,date_interval_create_from_date_string(SystemConfig::getValue("iRemotePhotoCacheDuration"))); - if (strpos($photoFile,"remote") !== false || strpos($photoFile,"initials") !== false ) { - return filemtime($photoFile) < date_timestamp_get($remotecachethreshold); - } +class Photo +{ + private $photoType; + private $id; + private $photoURI; + private $photoThumbURI; + private $thubmnailPath; + private $photoContentType; + private $remotesEnabled; + public static $validExtensions = ['png', 'jpeg', 'jpg']; + + public function __construct($photoType, $id) + { + $this->photoType = $photoType; + $this->id = $id; + $this->remotesEnabled = SystemConfig::getBooleanValue('bEnableGooglePhotos') || SystemConfig::getBooleanValue('bEnableGravatarPhotos'); + $this->photoHunt(); } - else{ - // if remotes are disabled, and the image contains remote, then we should re-gen - return strpos($photoFile,"remote") !== false; + + public static function getValidExtensions() + { + return Photo::$validExtensions; } - } - - private function photoHunt() { - $baseName = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/" . $this->id; - $extensions = Photo::$validExtensions; - - foreach($extensions as $ext) { - $photoFiles = array($baseName . "." . $ext,$baseName . "-remote." . $ext,$baseName . "-initials." . $ext); - foreach ($photoFiles as $photoFile) - { - if (file_exists($photoFile)) { - $this->setURIs($photoFile); - if ($ext !== "png") - { - $this->convertToPNG(); - } - if ($this->shouldRefreshPhotoFile($photoFile)) { - //if we found the file, but it's remote and aged, then we should update it. - $this->delete(); - break 2; - } - return; - } - } + + private function setURIs($photoPath) + { + $this->photoURI = $photoPath; + $this->thubmnailPath = SystemURLs::getImagesRoot().'/'.$this->photoType.'/thumbnails/'; + $this->photoThumbURI = $this->thubmnailPath.$this->id.'.jpg'; + } + + private function shouldRefreshPhotoFile($photoFile) + { + if ($this->remotesEnabled) { + // if the system has remotes enabled, calculate the cutoff timestamp for refreshing remote photos. + $remotecachethreshold = date_create(); + date_sub($remotecachethreshold, date_interval_create_from_date_string(SystemConfig::getValue('iRemotePhotoCacheDuration'))); + if (strpos($photoFile, 'remote') !== false || strpos($photoFile, 'initials') !== false) { + return filemtime($photoFile) < date_timestamp_get($remotecachethreshold); + } + } else { + // if remotes are disabled, and the image contains remote, then we should re-gen + return strpos($photoFile, 'remote') !== false; + } + } + + private function photoHunt() + { + $baseName = SystemURLs::getImagesRoot().'/'.$this->photoType.'/'.$this->id; + $extensions = Photo::$validExtensions; + + foreach ($extensions as $ext) { + $photoFiles = [$baseName.'.'.$ext, $baseName.'-remote.'.$ext, $baseName.'-initials.'.$ext]; + foreach ($photoFiles as $photoFile) { + if (file_exists($photoFile)) { + $this->setURIs($photoFile); + if ($ext !== 'png') { + $this->convertToPNG(); + } + if ($this->shouldRefreshPhotoFile($photoFile)) { + //if we found the file, but it's remote and aged, then we should update it. + $this->delete(); + break 2; + } + + return; + } + } + } + // we still haven't found a photo file. Begin checking remote if it's enabled + // only check google and gravatar for person photos. + if ($this->photoType == 'Person' && $this->remotesEnabled) { + $person = PersonQuery::create()->findOneById($this->id); + if ($person) { + $personEmail = $person->getEmail(); + if (SystemConfig::getBooleanValue('bEnableGooglePhotos')) { + $photoPath = $this->loadFromGoogle($personEmail, $baseName); + if ($photoPath) { + $this->setURIs($photoPath); + + return; + } + } + + if (SystemConfig::getBooleanValue('bEnableGravatarPhotos')) { + $photoPath = $this->loadFromGravatar($personEmail, $baseName); + if ($photoPath) { + $this->setURIs($photoPath); + + return; + } + } + } + } + + // still no image - generate it from initials + $this->renderInitials(); + } + + private function convertToPNG() + { + $image = $this->getGDImage($this->getPhotoURI()); + $this->delete(); + $targetPath = SystemURLs::getImagesRoot().'/'.$this->photoType.'/'.$this->id.'.png'; + imagepng($image, $targetPath); + $this->setURIs($targetPath); } - # we still haven't found a photo file. Begin checking remote if it's enabled - # only check google and gravatar for person photos. - if ($this->photoType == "Person" && $this->remotesEnabled) { - $person = PersonQuery::create()->findOneById($this->id); - if($person) { - $personEmail = $person->getEmail(); - if (SystemConfig::getBooleanValue('bEnableGooglePhotos')) { - $photoPath = $this->loadFromGoogle($personEmail, $baseName); - if ($photoPath) { - $this->setURIs($photoPath); - return; - } + + private function getGDImage($sourceImagePath) + { + $sourceImageType = exif_imagetype($sourceImagePath); + switch ($sourceImageType) { + case IMAGETYPE_GIF: + $sourceGDImage = imagecreatefromgif($sourceImagePath); + break; + case IMAGETYPE_JPEG: + $sourceGDImage = imagecreatefromjpeg($sourceImagePath); + break; + case IMAGETYPE_PNG: + $sourceGDImage = imagecreatefrompng($sourceImagePath); + break; } - if (SystemConfig::getBooleanValue('bEnableGravatarPhotos')) { - $photoPath = $this->loadFromGravatar($personEmail, $baseName); - if ($photoPath) { - $this->setURIs($photoPath); - return; - } + return $sourceGDImage; + } + + private function ensureThumbnailsPath() + { + if (!file_exists($this->thubmnailPath)) { + mkdir($this->thubmnailPath); + } + } + + private function createThumbnail() + { + $this->ensureThumbnailsPath(); + $thumbWidth = SystemConfig::getValue('iThumbnailWidth'); + $img = $this->getGDImage($this->photoURI); //just in case we have legacy JPG/GIF that don't have a thumbnail. + $width = imagesx($img); + $height = imagesy($img); + $new_width = $thumbWidth; + $new_height = floor($height * ($thumbWidth / $width)); + $tmp_img = imagecreatetruecolor($new_width, $new_height); + imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); + imagejpeg($tmp_img, $this->photoThumbURI, 50); + } + + public function getThumbnailBytes() + { + if (!file_exists($this->photoThumbURI)) { + $this->createThumbnail(); } - } + + return file_get_contents($this->photoThumbURI); } - # still no image - generate it from initials - $this->renderInitials(); - } - - private function convertToPNG() { - $image = $this->getGDImage($this->getPhotoURI()); - $this->delete(); - $targetPath = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/" . $this->id.".png"; - imagepng($image,$targetPath); - $this->setURIs($targetPath); - } - - private function getGDImage($sourceImagePath) { - $sourceImageType = exif_imagetype($sourceImagePath); - switch ($sourceImageType) + public function getPhotoBytes() { - case IMAGETYPE_GIF: - $sourceGDImage = imagecreatefromgif($sourceImagePath); - break; - case IMAGETYPE_JPEG: - $sourceGDImage = imagecreatefromjpeg($sourceImagePath); - break; - case IMAGETYPE_PNG: - $sourceGDImage = imagecreatefrompng($sourceImagePath); - break; + return file_get_contents($this->photoURI); } - return $sourceGDImage; - } - private function ensureThumbnailsPath() { - if( !file_exists($this->thubmnailPath)){ - mkdir($this->thubmnailPath); + public function getPhotoContentType() + { + $finfo = new \finfo(FILEINFO_MIME); + $this->photoContentType = $finfo->file($this->photoURI); + + return $this->photoContentType; } - } - - private function createThumbnail() { - $this->ensureThumbnailsPath(); - $thumbWidth = SystemConfig::getValue("iThumbnailWidth"); - $img = $this->getGDImage($this->photoURI); //just in case we have legacy JPG/GIF that don't have a thumbnail. - $width = imagesx( $img ); - $height = imagesy( $img ); - $new_width = $thumbWidth; - $new_height = floor( $height * ( $thumbWidth / $width ) ); - $tmp_img = imagecreatetruecolor( $new_width, $new_height ); - imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height ); - imagejpeg($tmp_img, $this->photoThumbURI, 50); - } - - public function getThumbnailBytes() { - if (!file_exists($this->photoThumbURI)) + + public function getThumbnailContentType() { - $this->createThumbnail(); + $finfo = new \finfo(FILEINFO_MIME); + $this->thumbnailContentType = $finfo->file($this->photoThumbURI); + + return $this->thumbnailContentType; } - return file_get_contents($this->photoThumbURI); - } - - public function getPhotoBytes() { - return file_get_contents($this->photoURI); - } - - public function getPhotoContentType() { - $finfo = new \finfo(FILEINFO_MIME); - $this->photoContentType = $finfo->file($this->photoURI); - return $this->photoContentType; - } - - public function getThumbnailContentType() { - $finfo = new \finfo(FILEINFO_MIME); - $this->thumbnailContentType = $finfo->file($this->photoThumbURI); - return $this->thumbnailContentType; - } - - public function getThumbnailURI() { - if (!file_exists($this->photoThumbURI)) + + public function getThumbnailURI() { - $this->createThumbnail(); + if (!file_exists($this->photoThumbURI)) { + $this->createThumbnail(); + } + + return $this->photoThumbURI; } - return $this->photoThumbURI; - } - - public function getPhotoURI() { - return $this->photoURI; - } - - private function loadFromGravatar($email, $baseName) { - $s = 60; - $d = '404'; - $r = 'g'; - $img = false; - $atts = []; - $url = 'https://www.gravatar.com/avatar/'; - $url .= md5(strtolower(trim($email))); - $url .= "?s=$s&d=$d&r=$r"; - - $photo = imagecreatefromstring(file_get_contents($url)); - if ($photo){ - $photoPath = $baseName."-remote.png"; - imagepng($photo, $photoPath); - return $photoPath; + + public function getPhotoURI() + { + return $this->photoURI; } - return false; - } - - private function loadFromGoogle($email, $baseName) { - $url = 'http://picasaweb.google.com/data/entry/api/user/'; - $url .= strtolower(trim($email)); - $url .= "?alt=json"; - $headers = @get_headers($url); - if (strpos($headers[0], '404') === false) { - $json = file_get_contents($url); - if (!empty($json)) { - $obj = json_decode($json); - $photoEntry = $obj->entry; - $photoURL = $photoEntry->{'gphoto$thumbnail'}->{'$t'}; - $photo = imagecreatefromstring(file_get_contents($photoURL)); - if ($photo){ - $photoPath = $baseName."-remote.png"; + + private function loadFromGravatar($email, $baseName) + { + $s = 60; + $d = '404'; + $r = 'g'; + $img = false; + $atts = []; + $url = 'https://www.gravatar.com/avatar/'; + $url .= md5(strtolower(trim($email))); + $url .= "?s=$s&d=$d&r=$r"; + + $photo = imagecreatefromstring(file_get_contents($url)); + if ($photo) { + $photoPath = $baseName.'-remote.png'; imagepng($photo, $photoPath); + return $photoPath; - } } - } - return false; - } - - private function getRandomColor($image) { - $red = rand(0, 150); - $green = rand(0, 150); - $blue = rand(0, 150); - return imagecolorallocate($image, $red, $green, $blue); - } - - private function getInitialsString() { - $retstr = ""; - if ($this->photoType == "Person") + + return false; + } + + private function loadFromGoogle($email, $baseName) + { + $url = 'http://picasaweb.google.com/data/entry/api/user/'; + $url .= strtolower(trim($email)); + $url .= '?alt=json'; + $headers = @get_headers($url); + if (strpos($headers[0], '404') === false) { + $json = file_get_contents($url); + if (!empty($json)) { + $obj = json_decode($json); + $photoEntry = $obj->entry; + $photoURL = $photoEntry->{'gphoto$thumbnail'}->{'$t'}; + $photo = imagecreatefromstring(file_get_contents($photoURL)); + if ($photo) { + $photoPath = $baseName.'-remote.png'; + imagepng($photo, $photoPath); + + return $photoPath; + } + } + } + + return false; + } + + private function getRandomColor($image) { - $fullNameArr = PersonQuery::create()->select(array('FirstName','LastName'))->findOneById($this->id); - foreach ($fullNameArr as $name) - { - $retstr .= mb_strtoupper(mb_substr($name, 0, 1)); - } + $red = rand(0, 150); + $green = rand(0, 150); + $blue = rand(0, 150); + return imagecolorallocate($image, $red, $green, $blue); } - elseif ($this->photoType == "Family" ) + + private function getInitialsString() { - $fullNameArr = FamilyQuery::create()->findOneById($this->id)->getName(); - $retstr .= mb_strtoupper(mb_substr($fullNameArr, 0, 1)); + $retstr = ''; + if ($this->photoType == 'Person') { + $fullNameArr = PersonQuery::create()->select(['FirstName', 'LastName'])->findOneById($this->id); + foreach ($fullNameArr as $name) { + $retstr .= mb_strtoupper(mb_substr($name, 0, 1)); + } + } elseif ($this->photoType == 'Family') { + $fullNameArr = FamilyQuery::create()->findOneById($this->id)->getName(); + $retstr .= mb_strtoupper(mb_substr($fullNameArr, 0, 1)); + } + + return $retstr; } - return $retstr; - } - - private function renderInitials() { - $initials = $this->getInitialsString(); - $targetPath = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/" . $this->id."-initials.png"; - $height = SystemConfig::getValue("iPhotoHeight"); - $width= SystemConfig::getValue("iPhotoWidth"); - $pointSize = SystemConfig::getValue("iInitialsPointSize"); - $font = SystemURLs::getDocumentRoot()."/fonts/Roboto-Regular.ttf"; - $image = imagecreatetruecolor($width,$height); - $bgcolor = $this->getRandomColor($image); - $white = imagecolorallocate($image, 255, 255, 255); - imagefilledrectangle($image, 0, 0,$height , $width, $bgcolor); - $tb = imagettfbbox($pointSize, 0, $font, $initials); - $x = ceil(($width - $tb[2]) / 2); - $y = ceil(($height - $tb[5]) / 2); - imagefttext($image, $pointSize, 0, $x, $y, $white, $font, $initials); - imagepng($image,$targetPath); - $this->setURIs($targetPath); - } - - public function setImageFromBase64($base64) { - $this->delete(); - $fileName = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/" . $this->id.".png"; - $img = str_replace('data:image/png;base64,', '', $base64); - $img = str_replace(' ', '+', $img); - $fileData = base64_decode($img); - $finfo = new \finfo(FILEINFO_MIME); - if ($finfo->buffer($fileData) == "image/png; charset=binary") - { - file_put_contents( $fileName , $fileData); - } - - } - - public function delete() { - $deleted = false; - if (file_exists($this->photoURI)) + + private function renderInitials() { - unlink ($this->photoURI); - $deleted = true; + $initials = $this->getInitialsString(); + $targetPath = SystemURLs::getImagesRoot().'/'.$this->photoType.'/'.$this->id.'-initials.png'; + $height = SystemConfig::getValue('iPhotoHeight'); + $width = SystemConfig::getValue('iPhotoWidth'); + $pointSize = SystemConfig::getValue('iInitialsPointSize'); + $font = SystemURLs::getDocumentRoot().'/fonts/Roboto-Regular.ttf'; + $image = imagecreatetruecolor($width, $height); + $bgcolor = $this->getRandomColor($image); + $white = imagecolorallocate($image, 255, 255, 255); + imagefilledrectangle($image, 0, 0, $height, $width, $bgcolor); + $tb = imagettfbbox($pointSize, 0, $font, $initials); + $x = ceil(($width - $tb[2]) / 2); + $y = ceil(($height - $tb[5]) / 2); + imagefttext($image, $pointSize, 0, $x, $y, $white, $font, $initials); + imagepng($image, $targetPath); + $this->setURIs($targetPath); } - if (file_exists($this->photoThumbURI)) + + public function setImageFromBase64($base64) { - unlink($this->photoThumbURI); - $deleted = true; + $this->delete(); + $fileName = SystemURLs::getImagesRoot().'/'.$this->photoType.'/'.$this->id.'.png'; + $img = str_replace('data:image/png;base64,', '', $base64); + $img = str_replace(' ', '+', $img); + $fileData = base64_decode($img); + $finfo = new \finfo(FILEINFO_MIME); + if ($finfo->buffer($fileData) == 'image/png; charset=binary') { + file_put_contents($fileName, $fileData); + } } - return $deleted; - } - public function refresh() { - if (strpos($this->photoURI, "initials") || strpos($this->photoURI, "remote")) { - $this->delete(); + public function delete() + { + $deleted = false; + if (file_exists($this->photoURI)) { + unlink($this->photoURI); + $deleted = true; + } + if (file_exists($this->photoThumbURI)) { + unlink($this->photoThumbURI); + $deleted = true; + } + + return $deleted; } - $this->photoURI = $this->photoHunt(SystemURLs::getImagesRoot() . "/" . $photoType . "/" . $id); - $this->photoThumbURI = SystemURLs::getImagesRoot() . "/" . $photoType . "/thumbnails/" . $id . ".jpg"; - } - - public function isInitials() { - if($this->photoType == "Person" && $this->id == 2) { - echo $this->photoURI; - echo strpos($this->photoURI,"initials") !== false; - die(); + + public function refresh() + { + if (strpos($this->photoURI, 'initials') || strpos($this->photoURI, 'remote')) { + $this->delete(); + } + $this->photoURI = $this->photoHunt(SystemURLs::getImagesRoot().'/'.$photoType.'/'.$id); + $this->photoThumbURI = SystemURLs::getImagesRoot().'/'.$photoType.'/thumbnails/'.$id.'.jpg'; } - return strpos($this->photoURI,"initials") !== false; - } - public function isRemote() { - return strpos($this->photoURI,"remote") !== false; - } + public function isInitials() + { + if ($this->photoType == 'Person' && $this->id == 2) { + echo $this->photoURI; + echo strpos($this->photoURI, 'initials') !== false; + exit; + } + return strpos($this->photoURI, 'initials') !== false; + } + + public function isRemote() + { + return strpos($this->photoURI, 'remote') !== false; + } } diff --git a/src/ChurchCRM/dto/Prerequisite.php b/src/ChurchCRM/dto/Prerequisite.php index 909ec8786e..d4dd47e440 100644 --- a/src/ChurchCRM/dto/Prerequisite.php +++ b/src/ChurchCRM/dto/Prerequisite.php @@ -1,45 +1,57 @@ name = $name; - $this->testFunction = $testFunction; - $this->savedTestResult = null; - } - - public function IsPrerequisiteMet(){ - $callable = $this->testFunction; - if ( $this->savedTestResult === null) { - $this->savedTestResult = (bool)$callable(); +class Prerequisite implements \JsonSerializable +{ + private $name; + private $testFunction; + private $savedTestResult; + + public function __construct(string $name, callable $testFunction) + { + $this->name = $name; + $this->testFunction = $testFunction; + $this->savedTestResult = null; + } + + public function IsPrerequisiteMet() + { + $callable = $this->testFunction; + if ($this->savedTestResult === null) { + $this->savedTestResult = (bool) $callable(); + } + + return $this->savedTestResult; + } + + public function GetName() + { + return $this->name; } - return $this->savedTestResult; - } - - public function GetName() { - return $this->name; - } - - public function GetWikiLink() { - return 'https://github.com/ChurchCRM/CRM/wiki/ChurchCRM-Application-Platform-Prerequisites#' . MiscUtils::GetGitHubWikiAnchorLink($this->name); - } - public function GetStatusText() { - if ($this->IsPrerequisiteMet()){ - return gettext("Passed"); + + public function GetWikiLink() + { + return 'https://github.com/ChurchCRM/CRM/wiki/ChurchCRM-Application-Platform-Prerequisites#'.MiscUtils::GetGitHubWikiAnchorLink($this->name); + } + + public function GetStatusText() + { + if ($this->IsPrerequisiteMet()) { + return gettext('Passed'); + } + + return gettext('Failed'); + } + + public function jsonSerialize() + { + return [ + 'Name' => $this->GetName(), + 'WikiLink' => $this->GetWikiLink(), + 'Satisfied' => $this->IsPrerequisiteMet(), + ]; } - return gettext("Failed"); - } - public function jsonSerialize() { - return [ - 'Name' => $this->GetName(), - 'WikiLink' => $this->GetWikiLink(), - 'Satisfied' => $this->IsPrerequisiteMet() - ]; - } } diff --git a/src/ChurchCRM/dto/SystemCalendars.php b/src/ChurchCRM/dto/SystemCalendars.php index 1edcd6c6d2..8261cf19a0 100644 --- a/src/ChurchCRM/dto/SystemCalendars.php +++ b/src/ChurchCRM/dto/SystemCalendars.php @@ -1,54 +1,61 @@ setModel("ChurchCRM\\Calendar"); - foreach(self::getCalendars() as $calendar) { - $calendars->push(self::toPropelCalendar($calendar)); + + public static function getCalendarList() + { + $calendars = new ObjectCollection(); + $calendars->setModel('ChurchCRM\\Calendar'); + foreach (self::getCalendars() as $calendar) { + $calendars->push(self::toPropelCalendar($calendar)); + } + + return $calendars; } - return $calendars; - } - public static function getCalendarById($id) { - $requestedCalendar = null; - foreach(self::getCalendars() as $calendar) + public static function getCalendarById($id) { - if ($calendar->getId() == $id){ - $requestedCalendar = $calendar; - break; - } + $requestedCalendar = null; + foreach (self::getCalendars() as $calendar) { + if ($calendar->getId() == $id) { + $requestedCalendar = $calendar; + break; + } + } + + return $requestedCalendar; } - return $requestedCalendar; - } - - public static function toPropelCalendar(SystemCalendar $calendar) { - $procalendar = new Calendar(); - $procalendar->setId($calendar->getId()); - $procalendar->setName($calendar->getName()); - $procalendar->setAccessToken($calendar->getAccessToken()); - $procalendar->setBackgroundColor($calendar->getBackgroundColor()); - $procalendar->setForegroundColor($calendar->getForegroundColor()); - return $procalendar; - } + public static function toPropelCalendar(SystemCalendar $calendar) + { + $procalendar = new Calendar(); + $procalendar->setId($calendar->getId()); + $procalendar->setName($calendar->getName()); + $procalendar->setAccessToken($calendar->getAccessToken()); + $procalendar->setBackgroundColor($calendar->getBackgroundColor()); + $procalendar->setForegroundColor($calendar->getForegroundColor()); + + return $procalendar; + } } diff --git a/src/ChurchCRM/dto/SystemConfig.php b/src/ChurchCRM/dto/SystemConfig.php index 2c9813b61c..4c05dc0337 100644 --- a/src/ChurchCRM/dto/SystemConfig.php +++ b/src/ChurchCRM/dto/SystemConfig.php @@ -11,407 +11,394 @@ class SystemConfig { /** - * @var Config[] - */ - private static $configs; - private static $categories; + * @var Config[] + */ + private static $configs; + private static $categories; - private static function getSupportedLocales() - { - $localesFile = file_get_contents(SystemURLs::getDocumentRoot()."/locale/locales.json"); - $locales = json_decode($localesFile, true); - $languagesChoices = []; - foreach ($locales as $key => $value) { - array_push($languagesChoices, gettext($key).":".$value["locale"]); - } + private static function getSupportedLocales() + { + $localesFile = file_get_contents(SystemURLs::getDocumentRoot().'/locale/locales.json'); + $locales = json_decode($localesFile, true); + $languagesChoices = []; + foreach ($locales as $key => $value) { + array_push($languagesChoices, gettext($key).':'.$value['locale']); + } - return ["Choices" => $languagesChoices ]; - } + return ['Choices' => $languagesChoices]; + } public static function getMonoLogLevels() { return [ - "Choices" => [ - gettext("DEBUG").":".Logger::DEBUG, - gettext("INFO").":".Logger::INFO, - gettext("NOTICE").":".Logger::NOTICE, - gettext("WARNING").":".Logger::WARNING, - gettext("ERROR").":".Logger::ERROR, - gettext("CRITICAL").":".Logger::CRITICAL, - gettext("ALERT").":".Logger::ALERT, - gettext("EMERGENCY").":".Logger::EMERGENCY - ] + 'Choices' => [ + gettext('DEBUG').':'.Logger::DEBUG, + gettext('INFO').':'.Logger::INFO, + gettext('NOTICE').':'.Logger::NOTICE, + gettext('WARNING').':'.Logger::WARNING, + gettext('ERROR').':'.Logger::ERROR, + gettext('CRITICAL').':'.Logger::CRITICAL, + gettext('ALERT').':'.Logger::ALERT, + gettext('EMERGENCY').':'.Logger::EMERGENCY, + ], ]; } public static function getNameChoices() { return [ - "Choices" => [ - gettext("Title FirstName MiddleName LastName").":0", - gettext("Title FirstName MiddleInitial. LastName").":1", - gettext("LastName, Title FirstName MiddleName").":2", - gettext("LastName, Title FirstName MiddleInitial").":3", - gettext("FirstName MiddleName LastName").":4", - gettext("Title FirstName LastName").":5", - gettext("LastName, Title FirstName").":6", - gettext("LastName FirstName").":7", - gettext("LastName, FirstName MiddleName").":8" - ] + 'Choices' => [ + gettext('Title FirstName MiddleName LastName').':0', + gettext('Title FirstName MiddleInitial. LastName').':1', + gettext('LastName, Title FirstName MiddleName').':2', + gettext('LastName, Title FirstName MiddleInitial').':3', + gettext('FirstName MiddleName LastName').':4', + gettext('Title FirstName LastName').':5', + gettext('LastName, Title FirstName').':6', + gettext('LastName FirstName').':7', + gettext('LastName, FirstName MiddleName').':8', + ], ]; } public static function getFamilyRoleChoices() { - $roles = []; - try { - $familyRoles = ListOptionQuery::create()->getFamilyRoles(); + $roles = []; - foreach ($familyRoles as $familyRole) { - array_push($roles, $familyRole->getOptionName().":".$familyRole->getOptionId()); + try { + $familyRoles = ListOptionQuery::create()->getFamilyRoles(); + + foreach ($familyRoles as $familyRole) { + array_push($roles, $familyRole->getOptionName().':'.$familyRole->getOptionId()); + } + } catch (Exception $e) { } - } catch (Exception $e) { - } - return ["Choices" => $roles]; + return ['Choices' => $roles]; } - private static function buildConfigs() - { - return array( - "sLogLevel" => new ConfigItem(4, "sLogLevel", "choice", "200", gettext("Event Log severity to write, used by ORM and App Logs"), "", json_encode(SystemConfig::getMonoLogLevels())), - "sDirClassifications" => new ConfigItem(5, "sDirClassifications", "text", "1,2,4,5", gettext("Include only these classifications in the directory, comma separated")), - "sDirRoleHead" => new ConfigItem(6, "sDirRoleHead", "choice", "1", gettext("These are the family role numbers designated as head of house"),"", json_encode(SystemConfig::getFamilyRoleChoices())), - "sDirRoleSpouse" => new ConfigItem(7, "sDirRoleSpouse", "choice", "2", gettext("These are the family role numbers designated as spouse"),"", json_encode(SystemConfig::getFamilyRoleChoices())), - "sDirRoleChild" => new ConfigItem(8, "sDirRoleChild", "choice", "3", gettext("These are the family role numbers designated as child"),"", json_encode(SystemConfig::getFamilyRoleChoices())), - "iSessionTimeout" => new ConfigItem(9, "iSessionTimeout", "number", "3600", gettext("Session timeout length in seconds\rSet to zero to disable session timeouts.")), - "aFinanceQueries" => new ConfigItem(10, "aFinanceQueries", "text", "30,31,32", gettext("Queries for which user must have finance permissions to use:")), - "bCSVAdminOnly" => new ConfigItem(11, "bCSVAdminOnly", "boolean", "1", gettext("Should only administrators have access to the CSV export system and directory report?")), - "iMinPasswordLength" => new ConfigItem(13, "iMinPasswordLength", "number", "6", gettext("Minimum length a user may set their password to")), - "iMinPasswordChange" => new ConfigItem(14, "iMinPasswordChange", "number", "4", gettext("Minimum amount that a new password must differ from the old one (# of characters changed)\rSet to zero to disable this feature")), - "aDisallowedPasswords" => new ConfigItem(15, "aDisallowedPasswords","text", "password,god,jesus,church,christian", gettext("A comma-separated list of disallowed (too obvious) passwords.")), - "iMaxFailedLogins" => new ConfigItem(16, "iMaxFailedLogins", "number", "5", gettext("Maximum number of failed logins to allow before a user account is locked.\rOnce the maximum has been reached, an administrator must re-enable the account.\rThis feature helps to protect against automated password guessing attacks.\rSet to zero to disable this feature.")), - "iPDFOutputType" => new ConfigItem(20, "iPDFOutputType", "number", "1", gettext("PDF handling mode.\r1 = Save File dialog\r2 = Open in current browser window")), - "sDefaultCity" => new ConfigItem(21, "sDefaultCity", "text", "", gettext("Default City")), - "sDefaultState" => new ConfigItem(22, "sDefaultState", "text", "", gettext("Default State - Must be 2-letter abbreviation!")), - "sDefaultCountry" => new ConfigItem(23, "sDefaultCountry", "choice", "", "", "", json_encode(["Choices" => Countries::getNames()])), - "sToEmailAddress" => new ConfigItem(26, "sToEmailAddress", "text", "", gettext("Default account for receiving a copy of all emails")), - "iSMTPTimeout" => new ConfigItem(24, "iSMTPTimeout", "number", "10", gettext("SMTP Server timeout in sec")), - "sSMTPHost" => new ConfigItem(27, "sSMTPHost", "text", "", gettext("SMTP Server Address (mail.server.com:25)")), - "bSMTPAuth" => new ConfigItem(28, "bSMTPAuth", "boolean", "0", gettext("Does your SMTP server require auththentication (username/password)?")), - "sSMTPUser" => new ConfigItem(29, "sSMTPUser", "text", "", gettext("SMTP Username")), - "sSMTPPass" => new ConfigItem(30, "sSMTPPass", "password", "", gettext("SMTP Password")), - "bShowFamilyData" => new ConfigItem(33, "bShowFamilyData", "boolean", "1", gettext("Unavailable person info inherited from assigned family for display?\rThis option causes certain info from a person's assigned family record to be\rdisplayed IF the corresponding info has NOT been entered for that person. ")), - "sLanguage" => new ConfigItem(39, "sLanguage", "choice", "en_US", gettext("Internationalization (I18n) support"), "https://poeditor.com/join/project?hash=RABdnDSqAt", json_encode(SystemConfig::getSupportedLocales())), - "iFYMonth" => new ConfigItem(40, "iFYMonth", "choice", "1", gettext("First month of the fiscal year"),"",'{"Choices":["1","2","3","4","5","6","7","8","9","10","11","12"]}'), - "sGoogleMapsGeocodeKey" => new ConfigItem(44, "sGoogleMapsGeocodeKey", "text", "", gettext("Google Maps API Key used for Geocoding addresses") , "https://developers.google.com/maps/documentation/javascript/get-api-key"), - "sBingMapKey" => new ConfigItem(10000, "sBingMapKey", "text", "", gettext("Bing map API requires a unique key") , "https://www.microsoft.com/maps/create-a-bing-maps-key.aspx"), - "iMapZoom" => new ConfigItem(10001, "iMapZoom", "number", "10", gettext("Google Maps Zoom")), - "iChurchLatitude" => new ConfigItem(45, "iChurchLatitude", "number", "", gettext("Latitude of the church, used to center the Google map")), - "iChurchLongitude" => new ConfigItem(46, "iChurchLongitude", "number", "", gettext("Longitude of the church, used to center the Google map")), - "bHidePersonAddress" => new ConfigItem(47, "bHidePersonAddress", "boolean", "1", gettext("Set true to disable entering addresses in Person Editor. Set false to enable entering addresses in Person Editor.")), - "bHideFriendDate" => new ConfigItem(48, "bHideFriendDate", "boolean", "0", gettext("Set true to disable entering Friend Date in Person Editor. Set false to enable entering Friend Date in Person Editor.")), - "bHideFamilyNewsletter" => new ConfigItem(49, "bHideFamilyNewsletter", "boolean", "0", gettext("Set true to disable management of newsletter subscriptions in the Family Editor.")), - "bHideWeddingDate" => new ConfigItem(50, "bHideWeddingDate", "boolean", "0", gettext("Set true to disable entering Wedding Date in Family Editor. Set false to enable entering Wedding Date in Family Editor.")), - "bHideLatLon" => new ConfigItem(51, "bHideLatLon", "boolean", "0", gettext("Set true to disable entering Latitude and Longitude in Family Editor. Set false to enable entering Latitude and Longitude in Family Editor. Lookups are still performed, just not displayed.")), - "bUseDonationEnvelopes" => new ConfigItem(52, "bUseDonationEnvelopes", "boolean", "0", gettext("Set true to enable use of donation envelopes")), - "sHeader" => new ConfigItem(53, "sHeader", "textarea", "", gettext("Enter in HTML code which will be displayed as a header at the top of each page. Be sure to close your tags! Note: You must REFRESH YOUR BROWSER A SECOND TIME to view the new header.")), - "sISTusername" => new ConfigItem(54, "sISTusername", "text", "username", gettext("Intelligent Search Technolgy, Ltd. CorrectAddress Username") , "https://www.intelligentsearch.com/Hosted/User"), - "sISTpassword" => new ConfigItem(55, "sISTpassword", "password", "", gettext("Intelligent Search Technolgy, Ltd. CorrectAddress Password") , "https://www.intelligentsearch.com/Hosted/User"), - "sGeoCoderProvider" => new ConfigItem(56, "sGeoCoderProvider", "choice", "GoogleMaps", gettext("Select GeoCoder Provider") , "https://github.com/geocoder-php/Geocoder/blob/3.x/README.md#address-based-providers", '{"Choices":["GoogleMaps", "BingMaps"]}'), - "iChecksPerDepositForm" => new ConfigItem(57, "iChecksPerDepositForm", "number", "14", gettext("Number of checks for Deposit Slip Report")), - "bUseScannedChecks" => new ConfigItem(58, "bUseScannedChecks", "boolean", "0", gettext("Set true to enable use of scanned checks")), - "sDistanceUnit" => new ConfigItem(64, "sDistanceUnit", "choice", "miles", gettext("Unit used to measure distance, miles or km."), "",'{"Choices":["'.gettext("miles").'","'.gettext("kilometers").'"]}'), - "sTimeZone" => new ConfigItem(65, "sTimeZone", "choice", "America/New_York", gettext("Time zone"), "http://php.net/manual/en/timezones.php", json_encode(["Choices"=>timezone_identifiers_list()])), - "sGMapIcons" => new ConfigItem(66, "sGMapIcons","text", "green-dot,purple,yellow-dot,blue-dot,orange,yellow,green,blue,red,pink,lightblue", gettext("Names of markers for Google Maps in order of classification")), - "bForceUppercaseZip" => new ConfigItem(67, "bForceUppercaseZip", "boolean", "0", gettext("Make user-entered zip/postcodes UPPERCASE when saving to the database.")), - "bEnableNonDeductible" => new ConfigItem(72, "bEnableNonDeductible", "boolean", "0", gettext("Enable non-deductible payments")), - "bEnableSelfRegistration" => new ConfigItem(80, "bEnableSelfRegistration", "boolean", "0", gettext("Set true to enable family self registration.")), - "sPhoneFormat" => new ConfigItem(100, "sPhoneFormat", "text", "(999) 999-9999"), - "sPhoneFormatWithExt" => new ConfigItem(101, "sPhoneFormatWithExt", "text", "(999) 999-9999 x99999"), - "sPhoneFormatCell" => new ConfigItem(111, "sPhoneFormatCell", "text", "(999) 999-9999"), - "sDateFormatLong" => new ConfigItem(102, "sDateFormatLong", "text", "m/d/Y"), - "sDateFormatNoYear" => new ConfigItem(103, "sDateFormatNoYear", "text", "m/d"), - "sDateFormatShort" => new ConfigItem(104, "sDateFormatShort", "text", "j/m/y"), - "sDateTimeFormat" => new ConfigItem(105, "sDateTimeFormat", "text", "j/m/y g:i a"), - "sDateFilenameFormat" => new ConfigItem(106, "sDateFilenameFormat", "text", "Ymd-Gis"), - "sCSVExportDelimiter" => new ConfigItem(107, "sCSVExportDelimiter", "text", ",", gettext("To export to another For european CharSet use ;")), - "sCSVExportCharset" => new ConfigItem(108, "sCSVExportCharset", "text", "UTF-8", gettext("Default is UTF-8, For european CharSet use Windows-1252 for example for French language.")), - "sDatePickerPlaceHolder" => new ConfigItem(109, "sDatePickerPlaceHolder", "text", "yyyy-mm-dd", gettext("For defining the date in Date-Picker, per default : yyyy-mm-dd, In French : dd/mm/yyyy for example.")), - "sDatePickerFormat" => new ConfigItem(110, "sDatePickerFormat", "text", "Y-m-d", gettext("For defining the date in Date-Picker, per default : Y-m-d, In French : d/m/Y for example.")), - "bRegistered" => new ConfigItem(999, "bRegistered", "boolean", "0", gettext("ChurchCRM has been registered. The ChurchCRM team uses registration information to track usage. This information is kept confidential and never released or sold. If this field is true the registration option in the admin menu changes to update registration.")), - "leftX" => new ConfigItem(1001, "leftX", "number", "20", gettext("Left Margin (1 = 1/100th inch)")), - "incrementY" => new ConfigItem(1002, "incrementY", "number", "4", gettext("Line Thickness (1 = 1/100th inch")), - "sChurchName" => new ConfigItem(1003, "sChurchName", "text", "", gettext("Church Name")), - "sChurchAddress" => new ConfigItem(1004, "sChurchAddress", "text", "", gettext("Church Address")), - "sChurchCity" => new ConfigItem(1005, "sChurchCity", "text", "", gettext("Church City")), - "sChurchState" => new ConfigItem(1006, "sChurchState", "text", "", gettext("Church State")), - "sChurchZip" => new ConfigItem(1007, "sChurchZip", "text", "", gettext("Church Zip")), - "sChurchPhone" => new ConfigItem(1008, "sChurchPhone", "text", "", gettext("Church Phone")), - "sChurchEmail" => new ConfigItem(1009, "sChurchEmail", "text", "", gettext("Church Email")), - "sHomeAreaCode" => new ConfigItem(1010, "sHomeAreaCode", "text", "", gettext("Home area code of the church")), - "sTaxReport1" => new ConfigItem(1011, "sTaxReport1", "text", "This letter shows our record of your payments for", gettext("Verbage for top line of tax report. Dates will be appended to the end of this line.")), - "sTaxReport2" => new ConfigItem(1012, "sTaxReport2", "text", "Thank you for your help in making a difference. We greatly appreciate your gift!", gettext("Verbage for bottom line of tax report.")), - "sTaxReport3" => new ConfigItem(1013, "sTaxReport3", "text", "If you have any questions or corrections to make to this report, please contact the church at the above number during business hours, 9am to 4pm, M-F.", gettext("Verbage for bottom line of tax report.")), - "sTaxSigner" => new ConfigItem(1014, "sTaxSigner", "text", "", gettext("Tax Report signer")), - "sReminder1" => new ConfigItem(1015, "sReminder1", "text", "This letter shows our record of your pledge and payments for fiscal year", gettext("Verbage for the pledge reminder report")), - "sReminderSigner" => new ConfigItem(1016, "sReminderSigner", "text", "", gettext("Pledge Reminder Signer")), - "sReminderNoPledge" => new ConfigItem(1017, "sReminderNoPledge", "text", "Pledges: We do not have record of a pledge for from you for this fiscal year.", gettext("Verbage for the pledge reminder report - No record of a pledge")), - "sReminderNoPayments" => new ConfigItem(1018, "sReminderNoPayments", "text", "Payments: We do not have record of a pledge for from you for this fiscal year.", gettext("Verbage for the pledge reminder report - No record of payments")), - "sConfirm1" => new ConfigItem(1019, "sConfirm1", "text", "This letter shows the information we have in our database with respect to your family. Please review, mark-up as necessary, and return this form to the church office.", gettext("Verbage for the database information confirmation and correction report")), - "sConfirm2" => new ConfigItem(1020, "sConfirm2", "text", "Thank you very much for helping us to update this information. If you want on-line access to the church database please provide your email address and a desired password and we will send instructions.", gettext("Verbage for the database information confirmation and correction report")), - "sConfirm3" => new ConfigItem(1021, "sConfirm3", "text", "Email _____________________________________ Password ________________", gettext("Verbage for the database information confirmation and correction report")), - "sConfirm4" => new ConfigItem(1022, "sConfirm4", "text", "[ ] I no longer want to be associated with the church (check here to be removed from our records).", gettext("Verbage for the database information confirmation and correction report")), - "sConfirm5" => new ConfigItem(1023, "sConfirm5", "text", "", gettext("Verbage for the database information confirmation and correction report")), - "sConfirm6" => new ConfigItem(1024, "sConfirm6", "text", "", gettext("Verbage for the database information confirmation and correction report")), - "sConfirmSigner" => new ConfigItem(1025, "sConfirmSigner", "text", "", gettext("Database information confirmation and correction report signer")), - "sPledgeSummary1" => new ConfigItem(1026, "sPledgeSummary1", "text", "Summary of pledges and payments for the fiscal year", gettext("Verbage for the pledge summary report")), - "sPledgeSummary2" => new ConfigItem(1027, "sPledgeSummary2", "text", " as of", gettext("Verbage for the pledge summary report")), - "sDirectoryDisclaimer1" => new ConfigItem(1028, "sDirectoryDisclaimer1", "text", "Every effort was made to ensure the accuracy of this directory. If there are any errors or omissions, please contact the church office.\n\nThis directory is for the use of the people of", gettext("Verbage for the directory report")), - "sDirectoryDisclaimer2" => new ConfigItem(1029, "sDirectoryDisclaimer2", "text", ", and the information contained in it may not be used for business or commercial purposes.", gettext("Verbage for the directory report")), - "bDirLetterHead" => new ConfigItem(1030, "bDirLetterHead", "text", "../Images/church_letterhead.jpg", gettext("Church Letterhead path and file")), - "sZeroGivers" => new ConfigItem(1031, "sZeroGivers", "text", "This letter shows our record of your payments for", gettext("Verbage for top line of tax report. Dates will be appended to the end of this line.")), - "sZeroGivers2" => new ConfigItem(1032, "sZeroGivers2", "text", "Thank you for your help in making a difference. We greatly appreciate your gift!", gettext("Verbage for bottom line of tax report.")), - "sZeroGivers3" => new ConfigItem(1033, "sZeroGivers3", "text", "If you have any questions or corrections to make to this report, please contact the church at the above number during business hours, 9am to 4pm, M-F.", gettext("Verbage for bottom line of tax report.")), - "sChurchChkAcctNum" => new ConfigItem(1034, "sChurchChkAcctNum", "text", "", gettext("Church Checking Account Number")), - "bEnableGravatarPhotos" => new ConfigItem(1035, "bEnableGravatarPhotos", "boolean", "0", gettext("lookup user images on Gravatar when no local image is present")), - "bEnableExternalBackupTarget" => new ConfigItem(1036, "bEnableExternalBackupTarget", "boolean", "0", gettext("Enable Remote Backups to Cloud Services")), - "sExternalBackupType" => new ConfigItem(1037, "sExternalBackupType", "choice", "", gettext("Cloud Service Type (Supported values: WebDAV, Local)"), "",'{"Choices":["'.gettext("WebDAV").'","'.gettext("Local").'"]}'), - "sExternalBackupEndpoint" => new ConfigItem(1038, "sExternalBackupEndpoint", "text", "", gettext("Remote Backup Endpoint. If WebDAV, this must be url encoded. ")), - "sExternalBackupUsername" => new ConfigItem(1039, "sExternalBackupUsername", "text", "", gettext("Remote Backup Username")), - "sExternalBackupPassword" => new ConfigItem(1040, "sExternalBackupPassword", "password", "", gettext("Remote Backup Password")), - "sExternalBackupAutoInterval" => new ConfigItem(1041, "sExternalBackupAutoInterval", "text", "", gettext("Interval in Hours for Automatic Remote Backups")), - "sLastBackupTimeStamp" => new ConfigItem(1042, "sLastBackupTimeStamp", "text", "", gettext("Last Backup Timestamp")), - "sQBDTSettings" => new ConfigItem(1043, "sQBDTSettings", "json", '{"date1":{"x":"12","y":"42"},"date2X":"185","leftX":"64","topY":"7","perforationY":"97","amountOffsetX":"35","lineItemInterval":{"x":"49","y":"7"},"max":{"x":"200","y":"140"},"numberOfItems":{"x":"136","y":"68"},"subTotal":{"x":"197","y":"42"},"topTotal":{"x":"197","y":"68"},"titleX":"85"}' , gettext("QuickBooks Deposit Ticket Settings")), - "bEnableIntegrityCheck" => new ConfigItem(1044, "bEnableIntegrityCheck", "boolean", "1", gettext("Enable Integrity Check")), - "iIntegrityCheckInterval" => new ConfigItem(1045, "iIntegrityCheckInterval", "number", "168", gettext("Interval in Hours for Integrity Check")), - "sLastIntegrityCheckTimeStamp" => new ConfigItem(1046, "sLastIntegrityCheckTimeStamp", "text", "", gettext("Last Integrity Check Timestamp")), - "sChurchCountry" => new ConfigItem(1047, "sChurchCountry", "choice", "", "", "",json_encode(["Choices" => Countries::getNames()])), - "sConfirmSincerely" => new ConfigItem(1048, "sConfirmSincerely", "text", "Sincerely", gettext("Used to end a letter before Signer")), - "sDear" => new ConfigItem(1049, "sDear", "text", "Dear", gettext("Text before name in emails/reports")), - "sGoogleTrackingID" => new ConfigItem(1050, "sGoogleTrackingID", "text", "", gettext("Google Analytics Tracking Code")), - "sMailChimpApiKey" => new ConfigItem(2000, "sMailChimpApiKey", "text", "", "", "http://kb.mailchimp.com/accounts/management/about-api-keys"), - "sDepositSlipType" => new ConfigItem(2001, "sDepositSlipType", "choice", "QBDT", gettext("Deposit ticket type. QBDT - Quickbooks"), "",'{"Choices":["QBDT"]}'), - "bAllowEmptyLastName" => new ConfigItem(2010, "bAllowEmptyLastName", "boolean", "0", gettext("Set true to allow empty lastname in Person Editor. Set false to validate last name and inherit from family when left empty.")), - "iPersonNameStyle" => new ConfigItem(2020, "iPersonNameStyle", "choice", "4", "","", json_encode(SystemConfig::getNameChoices())), - "bDisplayBillCounts" => new ConfigItem(2002, "bDisplayBillCounts", "boolean", "1", gettext("Display bill counts on deposit slip")), - "sCloudURL" => new ConfigItem(2003, "sCloudURL", "text", "http://demo.churchcrm.io/", gettext("ChurchCRM Cloud Access URL")), - "sNexmoAPIKey" => new ConfigItem(2012, "sNexmoAPIKey", "text", "", gettext("Nexmo SMS API Key")), - "sNexmoAPISecret" => new ConfigItem(2005, "sNexmoAPISecret", "password", "", gettext("Nexmo SMS API Secret")), - "sNexmoFromNumber" => new ConfigItem(2006, "sNexmoFromNumber", "text", "", gettext("Nexmo SMS From Number")), - "sOLPURL" => new ConfigItem(2007, "sOLPURL", "text", "http://192.168.1.1:4316", gettext("OpenLP URL")), - "sOLPUserName" => new ConfigItem(2008, "sOLPUserName", "text", "", gettext("OpenLP Username")), - "sOLPPassword" => new ConfigItem(2009, "sOLPPassword", "password", "", gettext("OpenLP Password")), - "sKioskVisibilityTimestamp" => new ConfigItem(2011, "sKioskVisibilityTimestamp", "text", "", gettext("KioskVisibilityTimestamp")), - "bEnableLostPassword" => new ConfigItem(2004, "bEnableLostPassword", "boolean", "1", gettext("Show/Hide Lost Password Link on the login screen")), - "sChurchWebSite" => new ConfigItem(2013, "sChurchWebSite", "text", "", gettext("Your Church's Website")), - "sChurchFB" => new ConfigItem(2014, "sChurchFB", "text", "", gettext("Your Church's Facebook Page")), - "sChurchTwitter" => new ConfigItem(2015, "sChurchTwitter", "text", "", gettext("Your Church's Twitter Page")), - "bEnableGooglePhotos" => new ConfigItem(2016, "bEnableGooglePhotos", "boolean", "1", gettext("lookup user images on Google when no local image is present")), - "sNewPersonNotificationRecipientIDs" => new ConfigItem(2018, "sNewPersonNotificationRecipientIDs", "text", "", gettext("Comma Separated list of PersonIDs of people to notify when a new family or person is added")), - "bEnableExternalCalendarAPI" => new ConfigItem(2017, "bEnableExternalCalendarAPI", "boolean", "0", gettext("Allow unauthenticated reads of events from the external calendar API")), - "bSearchIncludePersons" => new ConfigItem(2019, "bSearchIncludePersons", "boolean", "1", gettext("Search People")), - "bSearchIncludeFamilies" => new ConfigItem(2021, "bSearchIncludeFamilies", "boolean", "1", gettext("Search Family")), - "bSearchIncludeFamilyHOH" => new ConfigItem(2022, "bSearchIncludeFamilyHOH", "boolean", "1", gettext("Show Family Head of House Names")), - "bSearchIncludeGroups" => new ConfigItem(2023, "bSearchIncludeGroups", "boolean", "1", gettext("Search Groups")), - "bSearchIncludeDeposits" => new ConfigItem(2024, "bSearchIncludeDeposits", "boolean", "1", gettext("Search Deposits")), - "bSearchIncludePayments" => new ConfigItem(2025, "bSearchIncludePayments", "boolean", "1", gettext("Search Payments")), - "bSearchIncludeAddresses" => new ConfigItem(2026, "bSearchIncludeAddresses", "boolean", "1", gettext("Search Addresses")), - "bSearchIncludePersonsMax" => new ConfigItem(2027, "bSearchIncludePersonsMax", "text", "15", gettext("Maximum number of People")), - "bSearchIncludeFamiliesMax" => new ConfigItem(2028, "bSearchIncludeFamiliesMax", "text", "15", gettext("Maximum number of Families")), - "bSearchIncludeFamilyHOHMax" => new ConfigItem(2029, "bSearchIncludeFamilyHOHMax", "text", "15", gettext("Maximum number of Family H.O.H Names")), - "bSearchIncludeGroupsMax" => new ConfigItem(2030, "bSearchIncludeGroupsMax", "text", "15", gettext("Maximum number of Groups")), - "bSearchIncludeDepositsMax" => new ConfigItem(2031, "bSearchIncludeDepositsMax", "text", "5", gettext("Maximum number of Deposits")), - "bSearchIncludePaymentsMax" => new ConfigItem(2032, "bSearchIncludePaymentsMax", "text", "5", gettext("Maximum number of Payments")), - "bSearchIncludeAddressesMax" => new ConfigItem(20233, "bSearchIncludeAddressesMax", "text", "15", gettext("Maximum number of Addresses")), - "iPhotoHeight" => new ConfigItem(2034, "iPhotoHeight", "number", "400", gettext("Height to use for images")), - "iPhotoWidth" => new ConfigItem(2035, "iPhotoWidth", "number", "400", gettext("Width to use for images")), - "iThumbnailWidth" => new ConfigItem(2036, "iPhotoWidth", "number", "100", gettext("Width to use for thumbnails")), - "iInitialsPointSize" => new ConfigItem(2037, "iInitialsPointSize", "number", "150", gettext("Point size to use for initials thumbnails")), - "iPhotoClientCacheDuration" => new ConfigItem(2038, "iPhotoClientCacheDuration", "number", "3600", gettext("Client cache seconds for images")), - "iRemotePhotoCacheDuration" => new ConfigItem(2039, "iRemotePhotoCacheDuration", "number", "72 hours", gettext("Server cache time for remote images")), - "iPersonConfessionFatherCustomField" => new ConfigItem(2040, "iPersonConfessionFatherCustomField", "ajax", "", gettext("Field where Father Of Confession is listed, must be a people of group type"), "", "/api/system/custom-fields/person/?typeId=9"), - "iPersonConfessionDateCustomField" => new ConfigItem(2041, "iPersonConfessionDateCustomField", "ajax", "", gettext("Field where last Confession is stored, must be a date type"), "", "/api/system/custom-fields/person/?typeId=2"), - "bHSTSEnable" => new ConfigItem(20142,"bHSTSEnable","boolean","0",gettext("Require that this ChurchCRM Database is accessed over HTTPS")), - "bEventsOnDashboardPresence" => new ConfigItem(2042, "bEventsOnDashboardPresence", "boolean", "1", gettext("Show Birthdates Anniversaries on start up of the CRM")), - "iEventsOnDashboardPresenceTimeOut" => new ConfigItem(2043, "iEventsOnDashboardPresenceTimeOut", "number", "10", gettext("Number of seconds after page load until the banner disappears, default 10 seconds")), - "bPHPMailerAutoTLS" => new ConfigItem(2045, "bPHPMailerAutoTLS", "boolean", "0", gettext("Automatically enable SMTP encryption if offered by the relaying server.")), - "sPHPMailerSMTPSecure" => new ConfigItem(2046, "sPHPMailerSMTPSecure", "choice", " ", gettext("Set the encryption system to use - ssl (deprecated) or tls"),"",'{"Choices":["None: ","TLS:tls","SSL:ssl"]}'), - "iDashboardServiceIntervalTime" => new ConfigItem(2047, "iDashboardServiceIntervalTime", "number", "60", gettext("Dashboard Service dynamic asynchronous refresh interval, default 60 second")), - "iProfilePictureListSize" => new ConfigItem(2048, "iProfilePictureListSize", "number", "85", gettext("Set the standard profile picture icon size in pixels to be used in people lists, default 85 pixels.")), - "bEnabledMenuLinks" => new ConfigItem(2050, "bEnabledMenuLinks", "boolean", "0", gettext("Show custom links on the left menu.")), - "bEnabledSundaySchool" => new ConfigItem(2051, "bEnabledSundaySchool", "boolean", "1", gettext("Enable Sunday School left menu.")), - "bEnabledFinance" => new ConfigItem(2052, "bEnabledFinance", "boolean", "1", gettext("Enable Finance menu")), - "bEnabledEvents" => new ConfigItem(2053, "bEnabledEvents", "boolean", "1", gettext("Enable Events menu.")), - "bEnabledCalendar" => new ConfigItem(2054, "bEnabledCalendar", "boolean", "1", gettext("Enable Calendar menu.")), - "bEnabledFundraiser" => new ConfigItem(2055, "bEnabledFundraiser", "boolean", "1", gettext("Enable Fundraiser menu.")), - "bEnabledEmail" => new ConfigItem(2056, "bEnabledEmail", "boolean", "1", gettext("Enable Email menu.")), - "sNotificationsURL" => new ConfigItem(2057, "sNotificationsURL", "text", "https://raw.githubusercontent.com/ChurchCRM/CRM/Notifications/notifications.json", gettext("ChurchCRM Central Notifications URL")), - "sGreeterCustomMsg1" => new ConfigItem(2058, "sGreeterCustomMsg1", "text", "", gettext("Custom message for church greeter email 1, max 255 characters")), - "sGreeterCustomMsg2" => new ConfigItem(2059, "sGreeterCustomMsg2", "text", "", gettext("Custom message for church greeter email 2, max 255 characters")), - "IncludeDataInNewPersonNotifications" => new ConfigItem(2060, "IncludeDataInNewPersonNotifications", "boolean", "0", gettext("Include contact and demographic data in new member email notification body")), - "bSearchIncludeFamilyCustomProperties" => new ConfigItem(2061, "bSearchIncludeFamilyCustomProperties", "boolean", "0", gettext("Include family custom properties in global search.")), - "bBackupExtraneousImages" => new ConfigItem(2062, "bBackupExtraneousImages", "boolean", "0", gettext("Include initials image files, remote image files (gravatar), and thumbnails in backup. These files are generally able to be reproduced after a restore and add very little value to the backup archive at a large expense of execution time and storage")), - "iSoftwareUpdateCheckInterval" => new ConfigItem(2063, "iSoftwareUpdateCheckInterval", "number", "24", gettext("Interval in Hours for software update check")), - "sLastSoftwareUpdateCheckTimeStamp" => new ConfigItem(2064, "sLastSoftwareUpdateCheckTimeStamp", "text", "", gettext("Last Software Update Check Timestamp")), - "bAllowPrereleaseUpgrade" => new ConfigItem(2065, "bAllowPrereleaseUpgrade", "boolean", "0", gettext("Allow system upgrades to release marked as 'pre release' on GitHub")), - "bSearchIncludeCalendarEvents" => new ConfigItem(2066, "bSearchIncludeCalendarEvents", "boolean", "1", gettext("Search Calendar Events")), - "bSearchIncludeCalendarEventsMax" => new ConfigItem(2067, "bSearchIncludeCalendarEventsMax", "text", "15", gettext("Maximum number of Calendar Events")), - "bEnable2FA" => new ConfigItem(2068,"bEnable2FA", "boolean","1",gettext("Allow users to self-enroll in 2 factor authentication")), - "bRequire2FA" => new ConfigItem(2069,"bRequire2FA", "boolean","0",gettext("Requires users to self-enroll in 2 factor authentication")), - "s2FAApplicationName" => new ConfigItem(2070,"s2FAApplicationName", "text",gettext("ChurchCRM"),gettext("Specify the application name to be displayed in authenticator app")), - "bSendUserDeletedEmail" => new ConfigItem(2071,"bSendUserDeletedEmail", "boolean","0",gettext("Send an email notifying users when their account has been deleted")), - "sGoogleMapsRenderKey" => new ConfigItem(2072, "sGoogleMapsRenderKey", "text", "", gettext("Google Maps API Key used for rendering maps in browser") , "https://developers.google.com/maps/documentation/javascript/get-api-key") - ); - } + { + return [ + 'sLogLevel' => new ConfigItem(4, 'sLogLevel', 'choice', '200', gettext('Event Log severity to write, used by ORM and App Logs'), '', json_encode(SystemConfig::getMonoLogLevels())), + 'sDirClassifications' => new ConfigItem(5, 'sDirClassifications', 'text', '1,2,4,5', gettext('Include only these classifications in the directory, comma separated')), + 'sDirRoleHead' => new ConfigItem(6, 'sDirRoleHead', 'choice', '1', gettext('These are the family role numbers designated as head of house'), '', json_encode(SystemConfig::getFamilyRoleChoices())), + 'sDirRoleSpouse' => new ConfigItem(7, 'sDirRoleSpouse', 'choice', '2', gettext('These are the family role numbers designated as spouse'), '', json_encode(SystemConfig::getFamilyRoleChoices())), + 'sDirRoleChild' => new ConfigItem(8, 'sDirRoleChild', 'choice', '3', gettext('These are the family role numbers designated as child'), '', json_encode(SystemConfig::getFamilyRoleChoices())), + 'iSessionTimeout' => new ConfigItem(9, 'iSessionTimeout', 'number', '3600', gettext("Session timeout length in seconds\rSet to zero to disable session timeouts.")), + 'aFinanceQueries' => new ConfigItem(10, 'aFinanceQueries', 'text', '30,31,32', gettext('Queries for which user must have finance permissions to use:')), + 'bCSVAdminOnly' => new ConfigItem(11, 'bCSVAdminOnly', 'boolean', '1', gettext('Should only administrators have access to the CSV export system and directory report?')), + 'iMinPasswordLength' => new ConfigItem(13, 'iMinPasswordLength', 'number', '6', gettext('Minimum length a user may set their password to')), + 'iMinPasswordChange' => new ConfigItem(14, 'iMinPasswordChange', 'number', '4', gettext("Minimum amount that a new password must differ from the old one (# of characters changed)\rSet to zero to disable this feature")), + 'aDisallowedPasswords' => new ConfigItem(15, 'aDisallowedPasswords', 'text', 'password,god,jesus,church,christian', gettext('A comma-separated list of disallowed (too obvious) passwords.')), + 'iMaxFailedLogins' => new ConfigItem(16, 'iMaxFailedLogins', 'number', '5', gettext("Maximum number of failed logins to allow before a user account is locked.\rOnce the maximum has been reached, an administrator must re-enable the account.\rThis feature helps to protect against automated password guessing attacks.\rSet to zero to disable this feature.")), + 'iPDFOutputType' => new ConfigItem(20, 'iPDFOutputType', 'number', '1', gettext("PDF handling mode.\r1 = Save File dialog\r2 = Open in current browser window")), + 'sDefaultCity' => new ConfigItem(21, 'sDefaultCity', 'text', '', gettext('Default City')), + 'sDefaultState' => new ConfigItem(22, 'sDefaultState', 'text', '', gettext('Default State - Must be 2-letter abbreviation!')), + 'sDefaultCountry' => new ConfigItem(23, 'sDefaultCountry', 'choice', '', '', '', json_encode(['Choices' => Countries::getNames()])), + 'sToEmailAddress' => new ConfigItem(26, 'sToEmailAddress', 'text', '', gettext('Default account for receiving a copy of all emails')), + 'iSMTPTimeout' => new ConfigItem(24, 'iSMTPTimeout', 'number', '10', gettext('SMTP Server timeout in sec')), + 'sSMTPHost' => new ConfigItem(27, 'sSMTPHost', 'text', '', gettext('SMTP Server Address (mail.server.com:25)')), + 'bSMTPAuth' => new ConfigItem(28, 'bSMTPAuth', 'boolean', '0', gettext('Does your SMTP server require auththentication (username/password)?')), + 'sSMTPUser' => new ConfigItem(29, 'sSMTPUser', 'text', '', gettext('SMTP Username')), + 'sSMTPPass' => new ConfigItem(30, 'sSMTPPass', 'password', '', gettext('SMTP Password')), + 'bShowFamilyData' => new ConfigItem(33, 'bShowFamilyData', 'boolean', '1', gettext("Unavailable person info inherited from assigned family for display?\rThis option causes certain info from a person's assigned family record to be\rdisplayed IF the corresponding info has NOT been entered for that person. ")), + 'sLanguage' => new ConfigItem(39, 'sLanguage', 'choice', 'en_US', gettext('Internationalization (I18n) support'), 'https://poeditor.com/join/project?hash=RABdnDSqAt', json_encode(SystemConfig::getSupportedLocales())), + 'iFYMonth' => new ConfigItem(40, 'iFYMonth', 'choice', '1', gettext('First month of the fiscal year'), '', '{"Choices":["1","2","3","4","5","6","7","8","9","10","11","12"]}'), + 'sGoogleMapsGeocodeKey' => new ConfigItem(44, 'sGoogleMapsGeocodeKey', 'text', '', gettext('Google Maps API Key used for Geocoding addresses'), 'https://developers.google.com/maps/documentation/javascript/get-api-key'), + 'sBingMapKey' => new ConfigItem(10000, 'sBingMapKey', 'text', '', gettext('Bing map API requires a unique key'), 'https://www.microsoft.com/maps/create-a-bing-maps-key.aspx'), + 'iMapZoom' => new ConfigItem(10001, 'iMapZoom', 'number', '10', gettext('Google Maps Zoom')), + 'iChurchLatitude' => new ConfigItem(45, 'iChurchLatitude', 'number', '', gettext('Latitude of the church, used to center the Google map')), + 'iChurchLongitude' => new ConfigItem(46, 'iChurchLongitude', 'number', '', gettext('Longitude of the church, used to center the Google map')), + 'bHidePersonAddress' => new ConfigItem(47, 'bHidePersonAddress', 'boolean', '1', gettext('Set true to disable entering addresses in Person Editor. Set false to enable entering addresses in Person Editor.')), + 'bHideFriendDate' => new ConfigItem(48, 'bHideFriendDate', 'boolean', '0', gettext('Set true to disable entering Friend Date in Person Editor. Set false to enable entering Friend Date in Person Editor.')), + 'bHideFamilyNewsletter' => new ConfigItem(49, 'bHideFamilyNewsletter', 'boolean', '0', gettext('Set true to disable management of newsletter subscriptions in the Family Editor.')), + 'bHideWeddingDate' => new ConfigItem(50, 'bHideWeddingDate', 'boolean', '0', gettext('Set true to disable entering Wedding Date in Family Editor. Set false to enable entering Wedding Date in Family Editor.')), + 'bHideLatLon' => new ConfigItem(51, 'bHideLatLon', 'boolean', '0', gettext('Set true to disable entering Latitude and Longitude in Family Editor. Set false to enable entering Latitude and Longitude in Family Editor. Lookups are still performed, just not displayed.')), + 'bUseDonationEnvelopes' => new ConfigItem(52, 'bUseDonationEnvelopes', 'boolean', '0', gettext('Set true to enable use of donation envelopes')), + 'sHeader' => new ConfigItem(53, 'sHeader', 'textarea', '', gettext('Enter in HTML code which will be displayed as a header at the top of each page. Be sure to close your tags! Note: You must REFRESH YOUR BROWSER A SECOND TIME to view the new header.')), + 'sISTusername' => new ConfigItem(54, 'sISTusername', 'text', 'username', gettext('Intelligent Search Technolgy, Ltd. CorrectAddress Username'), 'https://www.intelligentsearch.com/Hosted/User'), + 'sISTpassword' => new ConfigItem(55, 'sISTpassword', 'password', '', gettext('Intelligent Search Technolgy, Ltd. CorrectAddress Password'), 'https://www.intelligentsearch.com/Hosted/User'), + 'sGeoCoderProvider' => new ConfigItem(56, 'sGeoCoderProvider', 'choice', 'GoogleMaps', gettext('Select GeoCoder Provider'), 'https://github.com/geocoder-php/Geocoder/blob/3.x/README.md#address-based-providers', '{"Choices":["GoogleMaps", "BingMaps"]}'), + 'iChecksPerDepositForm' => new ConfigItem(57, 'iChecksPerDepositForm', 'number', '14', gettext('Number of checks for Deposit Slip Report')), + 'bUseScannedChecks' => new ConfigItem(58, 'bUseScannedChecks', 'boolean', '0', gettext('Set true to enable use of scanned checks')), + 'sDistanceUnit' => new ConfigItem(64, 'sDistanceUnit', 'choice', 'miles', gettext('Unit used to measure distance, miles or km.'), '', '{"Choices":["'.gettext('miles').'","'.gettext('kilometers').'"]}'), + 'sTimeZone' => new ConfigItem(65, 'sTimeZone', 'choice', 'America/New_York', gettext('Time zone'), 'http://php.net/manual/en/timezones.php', json_encode(['Choices'=>timezone_identifiers_list()])), + 'sGMapIcons' => new ConfigItem(66, 'sGMapIcons', 'text', 'green-dot,purple,yellow-dot,blue-dot,orange,yellow,green,blue,red,pink,lightblue', gettext('Names of markers for Google Maps in order of classification')), + 'bForceUppercaseZip' => new ConfigItem(67, 'bForceUppercaseZip', 'boolean', '0', gettext('Make user-entered zip/postcodes UPPERCASE when saving to the database.')), + 'bEnableNonDeductible' => new ConfigItem(72, 'bEnableNonDeductible', 'boolean', '0', gettext('Enable non-deductible payments')), + 'bEnableSelfRegistration' => new ConfigItem(80, 'bEnableSelfRegistration', 'boolean', '0', gettext('Set true to enable family self registration.')), + 'sPhoneFormat' => new ConfigItem(100, 'sPhoneFormat', 'text', '(999) 999-9999'), + 'sPhoneFormatWithExt' => new ConfigItem(101, 'sPhoneFormatWithExt', 'text', '(999) 999-9999 x99999'), + 'sPhoneFormatCell' => new ConfigItem(111, 'sPhoneFormatCell', 'text', '(999) 999-9999'), + 'sDateFormatLong' => new ConfigItem(102, 'sDateFormatLong', 'text', 'm/d/Y'), + 'sDateFormatNoYear' => new ConfigItem(103, 'sDateFormatNoYear', 'text', 'm/d'), + 'sDateFormatShort' => new ConfigItem(104, 'sDateFormatShort', 'text', 'j/m/y'), + 'sDateTimeFormat' => new ConfigItem(105, 'sDateTimeFormat', 'text', 'j/m/y g:i a'), + 'sDateFilenameFormat' => new ConfigItem(106, 'sDateFilenameFormat', 'text', 'Ymd-Gis'), + 'sCSVExportDelimiter' => new ConfigItem(107, 'sCSVExportDelimiter', 'text', ',', gettext('To export to another For european CharSet use ;')), + 'sCSVExportCharset' => new ConfigItem(108, 'sCSVExportCharset', 'text', 'UTF-8', gettext('Default is UTF-8, For european CharSet use Windows-1252 for example for French language.')), + 'sDatePickerPlaceHolder' => new ConfigItem(109, 'sDatePickerPlaceHolder', 'text', 'yyyy-mm-dd', gettext('For defining the date in Date-Picker, per default : yyyy-mm-dd, In French : dd/mm/yyyy for example.')), + 'sDatePickerFormat' => new ConfigItem(110, 'sDatePickerFormat', 'text', 'Y-m-d', gettext('For defining the date in Date-Picker, per default : Y-m-d, In French : d/m/Y for example.')), + 'bRegistered' => new ConfigItem(999, 'bRegistered', 'boolean', '0', gettext('ChurchCRM has been registered. The ChurchCRM team uses registration information to track usage. This information is kept confidential and never released or sold. If this field is true the registration option in the admin menu changes to update registration.')), + 'leftX' => new ConfigItem(1001, 'leftX', 'number', '20', gettext('Left Margin (1 = 1/100th inch)')), + 'incrementY' => new ConfigItem(1002, 'incrementY', 'number', '4', gettext('Line Thickness (1 = 1/100th inch')), + 'sChurchName' => new ConfigItem(1003, 'sChurchName', 'text', '', gettext('Church Name')), + 'sChurchAddress' => new ConfigItem(1004, 'sChurchAddress', 'text', '', gettext('Church Address')), + 'sChurchCity' => new ConfigItem(1005, 'sChurchCity', 'text', '', gettext('Church City')), + 'sChurchState' => new ConfigItem(1006, 'sChurchState', 'text', '', gettext('Church State')), + 'sChurchZip' => new ConfigItem(1007, 'sChurchZip', 'text', '', gettext('Church Zip')), + 'sChurchPhone' => new ConfigItem(1008, 'sChurchPhone', 'text', '', gettext('Church Phone')), + 'sChurchEmail' => new ConfigItem(1009, 'sChurchEmail', 'text', '', gettext('Church Email')), + 'sHomeAreaCode' => new ConfigItem(1010, 'sHomeAreaCode', 'text', '', gettext('Home area code of the church')), + 'sTaxReport1' => new ConfigItem(1011, 'sTaxReport1', 'text', 'This letter shows our record of your payments for', gettext('Verbage for top line of tax report. Dates will be appended to the end of this line.')), + 'sTaxReport2' => new ConfigItem(1012, 'sTaxReport2', 'text', 'Thank you for your help in making a difference. We greatly appreciate your gift!', gettext('Verbage for bottom line of tax report.')), + 'sTaxReport3' => new ConfigItem(1013, 'sTaxReport3', 'text', 'If you have any questions or corrections to make to this report, please contact the church at the above number during business hours, 9am to 4pm, M-F.', gettext('Verbage for bottom line of tax report.')), + 'sTaxSigner' => new ConfigItem(1014, 'sTaxSigner', 'text', '', gettext('Tax Report signer')), + 'sReminder1' => new ConfigItem(1015, 'sReminder1', 'text', 'This letter shows our record of your pledge and payments for fiscal year', gettext('Verbage for the pledge reminder report')), + 'sReminderSigner' => new ConfigItem(1016, 'sReminderSigner', 'text', '', gettext('Pledge Reminder Signer')), + 'sReminderNoPledge' => new ConfigItem(1017, 'sReminderNoPledge', 'text', 'Pledges: We do not have record of a pledge for from you for this fiscal year.', gettext('Verbage for the pledge reminder report - No record of a pledge')), + 'sReminderNoPayments' => new ConfigItem(1018, 'sReminderNoPayments', 'text', 'Payments: We do not have record of a pledge for from you for this fiscal year.', gettext('Verbage for the pledge reminder report - No record of payments')), + 'sConfirm1' => new ConfigItem(1019, 'sConfirm1', 'text', 'This letter shows the information we have in our database with respect to your family. Please review, mark-up as necessary, and return this form to the church office.', gettext('Verbage for the database information confirmation and correction report')), + 'sConfirm2' => new ConfigItem(1020, 'sConfirm2', 'text', 'Thank you very much for helping us to update this information. If you want on-line access to the church database please provide your email address and a desired password and we will send instructions.', gettext('Verbage for the database information confirmation and correction report')), + 'sConfirm3' => new ConfigItem(1021, 'sConfirm3', 'text', 'Email _____________________________________ Password ________________', gettext('Verbage for the database information confirmation and correction report')), + 'sConfirm4' => new ConfigItem(1022, 'sConfirm4', 'text', '[ ] I no longer want to be associated with the church (check here to be removed from our records).', gettext('Verbage for the database information confirmation and correction report')), + 'sConfirm5' => new ConfigItem(1023, 'sConfirm5', 'text', '', gettext('Verbage for the database information confirmation and correction report')), + 'sConfirm6' => new ConfigItem(1024, 'sConfirm6', 'text', '', gettext('Verbage for the database information confirmation and correction report')), + 'sConfirmSigner' => new ConfigItem(1025, 'sConfirmSigner', 'text', '', gettext('Database information confirmation and correction report signer')), + 'sPledgeSummary1' => new ConfigItem(1026, 'sPledgeSummary1', 'text', 'Summary of pledges and payments for the fiscal year', gettext('Verbage for the pledge summary report')), + 'sPledgeSummary2' => new ConfigItem(1027, 'sPledgeSummary2', 'text', ' as of', gettext('Verbage for the pledge summary report')), + 'sDirectoryDisclaimer1' => new ConfigItem(1028, 'sDirectoryDisclaimer1', 'text', "Every effort was made to ensure the accuracy of this directory. If there are any errors or omissions, please contact the church office.\n\nThis directory is for the use of the people of", gettext('Verbage for the directory report')), + 'sDirectoryDisclaimer2' => new ConfigItem(1029, 'sDirectoryDisclaimer2', 'text', ', and the information contained in it may not be used for business or commercial purposes.', gettext('Verbage for the directory report')), + 'bDirLetterHead' => new ConfigItem(1030, 'bDirLetterHead', 'text', '../Images/church_letterhead.jpg', gettext('Church Letterhead path and file')), + 'sZeroGivers' => new ConfigItem(1031, 'sZeroGivers', 'text', 'This letter shows our record of your payments for', gettext('Verbage for top line of tax report. Dates will be appended to the end of this line.')), + 'sZeroGivers2' => new ConfigItem(1032, 'sZeroGivers2', 'text', 'Thank you for your help in making a difference. We greatly appreciate your gift!', gettext('Verbage for bottom line of tax report.')), + 'sZeroGivers3' => new ConfigItem(1033, 'sZeroGivers3', 'text', 'If you have any questions or corrections to make to this report, please contact the church at the above number during business hours, 9am to 4pm, M-F.', gettext('Verbage for bottom line of tax report.')), + 'sChurchChkAcctNum' => new ConfigItem(1034, 'sChurchChkAcctNum', 'text', '', gettext('Church Checking Account Number')), + 'bEnableGravatarPhotos' => new ConfigItem(1035, 'bEnableGravatarPhotos', 'boolean', '0', gettext('lookup user images on Gravatar when no local image is present')), + 'bEnableExternalBackupTarget' => new ConfigItem(1036, 'bEnableExternalBackupTarget', 'boolean', '0', gettext('Enable Remote Backups to Cloud Services')), + 'sExternalBackupType' => new ConfigItem(1037, 'sExternalBackupType', 'choice', '', gettext('Cloud Service Type (Supported values: WebDAV, Local)'), '', '{"Choices":["'.gettext('WebDAV').'","'.gettext('Local').'"]}'), + 'sExternalBackupEndpoint' => new ConfigItem(1038, 'sExternalBackupEndpoint', 'text', '', gettext('Remote Backup Endpoint. If WebDAV, this must be url encoded. ')), + 'sExternalBackupUsername' => new ConfigItem(1039, 'sExternalBackupUsername', 'text', '', gettext('Remote Backup Username')), + 'sExternalBackupPassword' => new ConfigItem(1040, 'sExternalBackupPassword', 'password', '', gettext('Remote Backup Password')), + 'sExternalBackupAutoInterval' => new ConfigItem(1041, 'sExternalBackupAutoInterval', 'text', '', gettext('Interval in Hours for Automatic Remote Backups')), + 'sLastBackupTimeStamp' => new ConfigItem(1042, 'sLastBackupTimeStamp', 'text', '', gettext('Last Backup Timestamp')), + 'sQBDTSettings' => new ConfigItem(1043, 'sQBDTSettings', 'json', '{"date1":{"x":"12","y":"42"},"date2X":"185","leftX":"64","topY":"7","perforationY":"97","amountOffsetX":"35","lineItemInterval":{"x":"49","y":"7"},"max":{"x":"200","y":"140"},"numberOfItems":{"x":"136","y":"68"},"subTotal":{"x":"197","y":"42"},"topTotal":{"x":"197","y":"68"},"titleX":"85"}', gettext('QuickBooks Deposit Ticket Settings')), + 'bEnableIntegrityCheck' => new ConfigItem(1044, 'bEnableIntegrityCheck', 'boolean', '1', gettext('Enable Integrity Check')), + 'iIntegrityCheckInterval' => new ConfigItem(1045, 'iIntegrityCheckInterval', 'number', '168', gettext('Interval in Hours for Integrity Check')), + 'sLastIntegrityCheckTimeStamp' => new ConfigItem(1046, 'sLastIntegrityCheckTimeStamp', 'text', '', gettext('Last Integrity Check Timestamp')), + 'sChurchCountry' => new ConfigItem(1047, 'sChurchCountry', 'choice', '', '', '', json_encode(['Choices' => Countries::getNames()])), + 'sConfirmSincerely' => new ConfigItem(1048, 'sConfirmSincerely', 'text', 'Sincerely', gettext('Used to end a letter before Signer')), + 'sDear' => new ConfigItem(1049, 'sDear', 'text', 'Dear', gettext('Text before name in emails/reports')), + 'sGoogleTrackingID' => new ConfigItem(1050, 'sGoogleTrackingID', 'text', '', gettext('Google Analytics Tracking Code')), + 'sMailChimpApiKey' => new ConfigItem(2000, 'sMailChimpApiKey', 'text', '', '', 'http://kb.mailchimp.com/accounts/management/about-api-keys'), + 'sDepositSlipType' => new ConfigItem(2001, 'sDepositSlipType', 'choice', 'QBDT', gettext('Deposit ticket type. QBDT - Quickbooks'), '', '{"Choices":["QBDT"]}'), + 'bAllowEmptyLastName' => new ConfigItem(2010, 'bAllowEmptyLastName', 'boolean', '0', gettext('Set true to allow empty lastname in Person Editor. Set false to validate last name and inherit from family when left empty.')), + 'iPersonNameStyle' => new ConfigItem(2020, 'iPersonNameStyle', 'choice', '4', '', '', json_encode(SystemConfig::getNameChoices())), + 'bDisplayBillCounts' => new ConfigItem(2002, 'bDisplayBillCounts', 'boolean', '1', gettext('Display bill counts on deposit slip')), + 'sCloudURL' => new ConfigItem(2003, 'sCloudURL', 'text', 'http://demo.churchcrm.io/', gettext('ChurchCRM Cloud Access URL')), + 'sNexmoAPIKey' => new ConfigItem(2012, 'sNexmoAPIKey', 'text', '', gettext('Nexmo SMS API Key')), + 'sNexmoAPISecret' => new ConfigItem(2005, 'sNexmoAPISecret', 'password', '', gettext('Nexmo SMS API Secret')), + 'sNexmoFromNumber' => new ConfigItem(2006, 'sNexmoFromNumber', 'text', '', gettext('Nexmo SMS From Number')), + 'sOLPURL' => new ConfigItem(2007, 'sOLPURL', 'text', 'http://192.168.1.1:4316', gettext('OpenLP URL')), + 'sOLPUserName' => new ConfigItem(2008, 'sOLPUserName', 'text', '', gettext('OpenLP Username')), + 'sOLPPassword' => new ConfigItem(2009, 'sOLPPassword', 'password', '', gettext('OpenLP Password')), + 'sKioskVisibilityTimestamp' => new ConfigItem(2011, 'sKioskVisibilityTimestamp', 'text', '', gettext('KioskVisibilityTimestamp')), + 'bEnableLostPassword' => new ConfigItem(2004, 'bEnableLostPassword', 'boolean', '1', gettext('Show/Hide Lost Password Link on the login screen')), + 'sChurchWebSite' => new ConfigItem(2013, 'sChurchWebSite', 'text', '', gettext("Your Church's Website")), + 'sChurchFB' => new ConfigItem(2014, 'sChurchFB', 'text', '', gettext("Your Church's Facebook Page")), + 'sChurchTwitter' => new ConfigItem(2015, 'sChurchTwitter', 'text', '', gettext("Your Church's Twitter Page")), + 'bEnableGooglePhotos' => new ConfigItem(2016, 'bEnableGooglePhotos', 'boolean', '1', gettext('lookup user images on Google when no local image is present')), + 'sNewPersonNotificationRecipientIDs' => new ConfigItem(2018, 'sNewPersonNotificationRecipientIDs', 'text', '', gettext('Comma Separated list of PersonIDs of people to notify when a new family or person is added')), + 'bEnableExternalCalendarAPI' => new ConfigItem(2017, 'bEnableExternalCalendarAPI', 'boolean', '0', gettext('Allow unauthenticated reads of events from the external calendar API')), + 'bSearchIncludePersons' => new ConfigItem(2019, 'bSearchIncludePersons', 'boolean', '1', gettext('Search People')), + 'bSearchIncludeFamilies' => new ConfigItem(2021, 'bSearchIncludeFamilies', 'boolean', '1', gettext('Search Family')), + 'bSearchIncludeFamilyHOH' => new ConfigItem(2022, 'bSearchIncludeFamilyHOH', 'boolean', '1', gettext('Show Family Head of House Names')), + 'bSearchIncludeGroups' => new ConfigItem(2023, 'bSearchIncludeGroups', 'boolean', '1', gettext('Search Groups')), + 'bSearchIncludeDeposits' => new ConfigItem(2024, 'bSearchIncludeDeposits', 'boolean', '1', gettext('Search Deposits')), + 'bSearchIncludePayments' => new ConfigItem(2025, 'bSearchIncludePayments', 'boolean', '1', gettext('Search Payments')), + 'bSearchIncludeAddresses' => new ConfigItem(2026, 'bSearchIncludeAddresses', 'boolean', '1', gettext('Search Addresses')), + 'bSearchIncludePersonsMax' => new ConfigItem(2027, 'bSearchIncludePersonsMax', 'text', '15', gettext('Maximum number of People')), + 'bSearchIncludeFamiliesMax' => new ConfigItem(2028, 'bSearchIncludeFamiliesMax', 'text', '15', gettext('Maximum number of Families')), + 'bSearchIncludeFamilyHOHMax' => new ConfigItem(2029, 'bSearchIncludeFamilyHOHMax', 'text', '15', gettext('Maximum number of Family H.O.H Names')), + 'bSearchIncludeGroupsMax' => new ConfigItem(2030, 'bSearchIncludeGroupsMax', 'text', '15', gettext('Maximum number of Groups')), + 'bSearchIncludeDepositsMax' => new ConfigItem(2031, 'bSearchIncludeDepositsMax', 'text', '5', gettext('Maximum number of Deposits')), + 'bSearchIncludePaymentsMax' => new ConfigItem(2032, 'bSearchIncludePaymentsMax', 'text', '5', gettext('Maximum number of Payments')), + 'bSearchIncludeAddressesMax' => new ConfigItem(20233, 'bSearchIncludeAddressesMax', 'text', '15', gettext('Maximum number of Addresses')), + 'iPhotoHeight' => new ConfigItem(2034, 'iPhotoHeight', 'number', '400', gettext('Height to use for images')), + 'iPhotoWidth' => new ConfigItem(2035, 'iPhotoWidth', 'number', '400', gettext('Width to use for images')), + 'iThumbnailWidth' => new ConfigItem(2036, 'iPhotoWidth', 'number', '100', gettext('Width to use for thumbnails')), + 'iInitialsPointSize' => new ConfigItem(2037, 'iInitialsPointSize', 'number', '150', gettext('Point size to use for initials thumbnails')), + 'iPhotoClientCacheDuration' => new ConfigItem(2038, 'iPhotoClientCacheDuration', 'number', '3600', gettext('Client cache seconds for images')), + 'iRemotePhotoCacheDuration' => new ConfigItem(2039, 'iRemotePhotoCacheDuration', 'number', '72 hours', gettext('Server cache time for remote images')), + 'iPersonConfessionFatherCustomField' => new ConfigItem(2040, 'iPersonConfessionFatherCustomField', 'ajax', '', gettext('Field where Father Of Confession is listed, must be a people of group type'), '', '/api/system/custom-fields/person/?typeId=9'), + 'iPersonConfessionDateCustomField' => new ConfigItem(2041, 'iPersonConfessionDateCustomField', 'ajax', '', gettext('Field where last Confession is stored, must be a date type'), '', '/api/system/custom-fields/person/?typeId=2'), + 'bHSTSEnable' => new ConfigItem(20142, 'bHSTSEnable', 'boolean', '0', gettext('Require that this ChurchCRM Database is accessed over HTTPS')), + 'bEventsOnDashboardPresence' => new ConfigItem(2042, 'bEventsOnDashboardPresence', 'boolean', '1', gettext('Show Birthdates Anniversaries on start up of the CRM')), + 'iEventsOnDashboardPresenceTimeOut' => new ConfigItem(2043, 'iEventsOnDashboardPresenceTimeOut', 'number', '10', gettext('Number of seconds after page load until the banner disappears, default 10 seconds')), + 'bPHPMailerAutoTLS' => new ConfigItem(2045, 'bPHPMailerAutoTLS', 'boolean', '0', gettext('Automatically enable SMTP encryption if offered by the relaying server.')), + 'sPHPMailerSMTPSecure' => new ConfigItem(2046, 'sPHPMailerSMTPSecure', 'choice', ' ', gettext('Set the encryption system to use - ssl (deprecated) or tls'), '', '{"Choices":["None: ","TLS:tls","SSL:ssl"]}'), + 'iDashboardServiceIntervalTime' => new ConfigItem(2047, 'iDashboardServiceIntervalTime', 'number', '60', gettext('Dashboard Service dynamic asynchronous refresh interval, default 60 second')), + 'iProfilePictureListSize' => new ConfigItem(2048, 'iProfilePictureListSize', 'number', '85', gettext('Set the standard profile picture icon size in pixels to be used in people lists, default 85 pixels.')), + 'bEnabledMenuLinks' => new ConfigItem(2050, 'bEnabledMenuLinks', 'boolean', '0', gettext('Show custom links on the left menu.')), + 'bEnabledSundaySchool' => new ConfigItem(2051, 'bEnabledSundaySchool', 'boolean', '1', gettext('Enable Sunday School left menu.')), + 'bEnabledFinance' => new ConfigItem(2052, 'bEnabledFinance', 'boolean', '1', gettext('Enable Finance menu')), + 'bEnabledEvents' => new ConfigItem(2053, 'bEnabledEvents', 'boolean', '1', gettext('Enable Events menu.')), + 'bEnabledCalendar' => new ConfigItem(2054, 'bEnabledCalendar', 'boolean', '1', gettext('Enable Calendar menu.')), + 'bEnabledFundraiser' => new ConfigItem(2055, 'bEnabledFundraiser', 'boolean', '1', gettext('Enable Fundraiser menu.')), + 'bEnabledEmail' => new ConfigItem(2056, 'bEnabledEmail', 'boolean', '1', gettext('Enable Email menu.')), + 'sNotificationsURL' => new ConfigItem(2057, 'sNotificationsURL', 'text', 'https://raw.githubusercontent.com/ChurchCRM/CRM/Notifications/notifications.json', gettext('ChurchCRM Central Notifications URL')), + 'sGreeterCustomMsg1' => new ConfigItem(2058, 'sGreeterCustomMsg1', 'text', '', gettext('Custom message for church greeter email 1, max 255 characters')), + 'sGreeterCustomMsg2' => new ConfigItem(2059, 'sGreeterCustomMsg2', 'text', '', gettext('Custom message for church greeter email 2, max 255 characters')), + 'IncludeDataInNewPersonNotifications' => new ConfigItem(2060, 'IncludeDataInNewPersonNotifications', 'boolean', '0', gettext('Include contact and demographic data in new member email notification body')), + 'bSearchIncludeFamilyCustomProperties' => new ConfigItem(2061, 'bSearchIncludeFamilyCustomProperties', 'boolean', '0', gettext('Include family custom properties in global search.')), + 'bBackupExtraneousImages' => new ConfigItem(2062, 'bBackupExtraneousImages', 'boolean', '0', gettext('Include initials image files, remote image files (gravatar), and thumbnails in backup. These files are generally able to be reproduced after a restore and add very little value to the backup archive at a large expense of execution time and storage')), + 'iSoftwareUpdateCheckInterval' => new ConfigItem(2063, 'iSoftwareUpdateCheckInterval', 'number', '24', gettext('Interval in Hours for software update check')), + 'sLastSoftwareUpdateCheckTimeStamp' => new ConfigItem(2064, 'sLastSoftwareUpdateCheckTimeStamp', 'text', '', gettext('Last Software Update Check Timestamp')), + 'bAllowPrereleaseUpgrade' => new ConfigItem(2065, 'bAllowPrereleaseUpgrade', 'boolean', '0', gettext("Allow system upgrades to release marked as 'pre release' on GitHub")), + 'bSearchIncludeCalendarEvents' => new ConfigItem(2066, 'bSearchIncludeCalendarEvents', 'boolean', '1', gettext('Search Calendar Events')), + 'bSearchIncludeCalendarEventsMax' => new ConfigItem(2067, 'bSearchIncludeCalendarEventsMax', 'text', '15', gettext('Maximum number of Calendar Events')), + 'bEnable2FA' => new ConfigItem(2068, 'bEnable2FA', 'boolean', '1', gettext('Allow users to self-enroll in 2 factor authentication')), + 'bRequire2FA' => new ConfigItem(2069, 'bRequire2FA', 'boolean', '0', gettext('Requires users to self-enroll in 2 factor authentication')), + 's2FAApplicationName' => new ConfigItem(2070, 's2FAApplicationName', 'text', gettext('ChurchCRM'), gettext('Specify the application name to be displayed in authenticator app')), + 'bSendUserDeletedEmail' => new ConfigItem(2071, 'bSendUserDeletedEmail', 'boolean', '0', gettext('Send an email notifying users when their account has been deleted')), + 'sGoogleMapsRenderKey' => new ConfigItem(2072, 'sGoogleMapsRenderKey', 'text', '', gettext('Google Maps API Key used for rendering maps in browser'), 'https://developers.google.com/maps/documentation/javascript/get-api-key'), + ]; + } - private static function buildCategories() - { - return array ( - gettext('Church Information') =>["sChurchName","sChurchAddress","sChurchCity","sChurchState","sChurchZip","sChurchCountry","sChurchPhone","sChurchEmail","sHomeAreaCode","sTimeZone","iChurchLatitude","iChurchLongitude", "sChurchWebSite","sChurchFB", "sChurchTwitter"], - gettext('User Setup') => ["iMinPasswordLength","iMinPasswordChange","iMaxFailedLogins","iSessionTimeout","aDisallowedPasswords","bEnableLostPassword","bEnable2FA","bRequire2FA","s2FAApplicationName","bSendUserDeletedEmail"], - gettext('Email Setup') => ["sSMTPHost","bSMTPAuth","sSMTPUser","sSMTPPass", "iSMTPTimeout","sToEmailAddress", "bPHPMailerAutoTLS","sPHPMailerSMTPSecure"], - gettext('People Setup') => ["sDirClassifications","sDirRoleHead","sDirRoleSpouse","sDirRoleChild","sDefaultCity","sDefaultState","sDefaultCountry","bShowFamilyData","bHidePersonAddress","bHideFriendDate","bHideFamilyNewsletter","bHideWeddingDate","bHideLatLon","bForceUppercaseZip","bEnableSelfRegistration", "bAllowEmptyLastName", "iPersonNameStyle", "iProfilePictureListSize", "sNewPersonNotificationRecipientIDs", "IncludeDataInNewPersonNotifications","sGreeterCustomMsg1","sGreeterCustomMsg2"], - gettext('Enabled Features') => ["bEnabledFinance", "bEnabledSundaySchool","bEnabledEvents","bEnabledCalendar","bEnabledFundraiser","bEnabledEmail", "bEnabledMenuLinks"], - gettext('Map Settings') => ["sGeoCoderProvider","sGoogleMapsGeocodeKey","sGoogleMapsRenderKey","sBingMapKey","sGMapIcons", "iMapZoom","sISTusername","sISTpassword"], - gettext('Report Settings') => ["sQBDTSettings","leftX","incrementY","sTaxReport1","sTaxReport2","sTaxReport3","sTaxSigner","sReminder1","sReminderSigner","sReminderNoPledge","sReminderNoPayments","sConfirm1","sConfirm2","sConfirm3","sConfirm4","sConfirm5","sConfirm6","sDear","sConfirmSincerely","sConfirmSigner","sPledgeSummary1","sPledgeSummary2","sDirectoryDisclaimer1","sDirectoryDisclaimer2","bDirLetterHead","sZeroGivers","sZeroGivers2","sZeroGivers3", "iPDFOutputType"], - gettext('Financial Settings') => ["sDepositSlipType","iChecksPerDepositForm","bDisplayBillCounts","bUseScannedChecks","bEnableNonDeductible","iFYMonth","bUseDonationEnvelopes","aFinanceQueries"], - gettext('Quick Search') => ["bSearchIncludePersons","bSearchIncludePersonsMax","bSearchIncludeAddresses", "bSearchIncludeAddressesMax", "bSearchIncludeFamilies","bSearchIncludeFamiliesMax","bSearchIncludeFamilyHOH","bSearchIncludeFamilyHOHMax","bSearchIncludeGroups","bSearchIncludeGroupsMax","bSearchIncludeDeposits", "bSearchIncludeDepositsMax", "bSearchIncludePayments", "bSearchIncludePaymentsMax", "bSearchIncludeFamilyCustomProperties","bSearchIncludeCalendarEvents","bSearchIncludeCalendarEventsMax"], - gettext('Localization') => ["sLanguage","sDistanceUnit","sPhoneFormat","sPhoneFormatWithExt","sPhoneFormatCell","sDateFormatLong","sDateFormatNoYear","sDateFormatShort","sDateTimeFormat","sDateFilenameFormat","sCSVExportDelimiter","sCSVExportCharset","sDatePickerFormat","sDatePickerPlaceHolder"], - gettext('Integration') => ["sMailChimpApiKey","sGoogleTrackingID","bEnableGravatarPhotos","bEnableGooglePhotos","iRemotePhotoCacheDuration","sNexmoAPIKey","sNexmoAPISecret","sNexmoFromNumber","sOLPURL","sOLPUserName","sOLPPassword"], - gettext('Church Services') => ["iPersonConfessionFatherCustomField","iPersonConfessionDateCustomField"], - gettext('Events') => ["bEnableExternalCalendarAPI","bEventsOnDashboardPresence","iEventsOnDashboardPresenceTimeOut"], - gettext('Backup') => ["sLastBackupTimeStamp","bEnableExternalBackupTarget","sExternalBackupType","sExternalBackupAutoInterval","sExternalBackupEndpoint","sExternalBackupUsername","sExternalBackupPassword","bBackupExtraneousImages"], - gettext('System Settings') => ["sLogLevel", "bRegistered","bCSVAdminOnly","sHeader","bEnableIntegrityCheck","iIntegrityCheckInterval","sLastIntegrityCheckTimeStamp", "iPhotoClientCacheDuration","bHSTSEnable", "iDashboardServiceIntervalTime","iSoftwareUpdateCheckInterval","sLastSoftwareUpdateCheckTimeStamp","bAllowPrereleaseUpgrade"] - ); - } + private static function buildCategories() + { + return [ + gettext('Church Information') => ['sChurchName', 'sChurchAddress', 'sChurchCity', 'sChurchState', 'sChurchZip', 'sChurchCountry', 'sChurchPhone', 'sChurchEmail', 'sHomeAreaCode', 'sTimeZone', 'iChurchLatitude', 'iChurchLongitude', 'sChurchWebSite', 'sChurchFB', 'sChurchTwitter'], + gettext('User Setup') => ['iMinPasswordLength', 'iMinPasswordChange', 'iMaxFailedLogins', 'iSessionTimeout', 'aDisallowedPasswords', 'bEnableLostPassword', 'bEnable2FA', 'bRequire2FA', 's2FAApplicationName', 'bSendUserDeletedEmail'], + gettext('Email Setup') => ['sSMTPHost', 'bSMTPAuth', 'sSMTPUser', 'sSMTPPass', 'iSMTPTimeout', 'sToEmailAddress', 'bPHPMailerAutoTLS', 'sPHPMailerSMTPSecure'], + gettext('People Setup') => ['sDirClassifications', 'sDirRoleHead', 'sDirRoleSpouse', 'sDirRoleChild', 'sDefaultCity', 'sDefaultState', 'sDefaultCountry', 'bShowFamilyData', 'bHidePersonAddress', 'bHideFriendDate', 'bHideFamilyNewsletter', 'bHideWeddingDate', 'bHideLatLon', 'bForceUppercaseZip', 'bEnableSelfRegistration', 'bAllowEmptyLastName', 'iPersonNameStyle', 'iProfilePictureListSize', 'sNewPersonNotificationRecipientIDs', 'IncludeDataInNewPersonNotifications', 'sGreeterCustomMsg1', 'sGreeterCustomMsg2'], + gettext('Enabled Features') => ['bEnabledFinance', 'bEnabledSundaySchool', 'bEnabledEvents', 'bEnabledCalendar', 'bEnabledFundraiser', 'bEnabledEmail', 'bEnabledMenuLinks'], + gettext('Map Settings') => ['sGeoCoderProvider', 'sGoogleMapsGeocodeKey', 'sGoogleMapsRenderKey', 'sBingMapKey', 'sGMapIcons', 'iMapZoom', 'sISTusername', 'sISTpassword'], + gettext('Report Settings') => ['sQBDTSettings', 'leftX', 'incrementY', 'sTaxReport1', 'sTaxReport2', 'sTaxReport3', 'sTaxSigner', 'sReminder1', 'sReminderSigner', 'sReminderNoPledge', 'sReminderNoPayments', 'sConfirm1', 'sConfirm2', 'sConfirm3', 'sConfirm4', 'sConfirm5', 'sConfirm6', 'sDear', 'sConfirmSincerely', 'sConfirmSigner', 'sPledgeSummary1', 'sPledgeSummary2', 'sDirectoryDisclaimer1', 'sDirectoryDisclaimer2', 'bDirLetterHead', 'sZeroGivers', 'sZeroGivers2', 'sZeroGivers3', 'iPDFOutputType'], + gettext('Financial Settings') => ['sDepositSlipType', 'iChecksPerDepositForm', 'bDisplayBillCounts', 'bUseScannedChecks', 'bEnableNonDeductible', 'iFYMonth', 'bUseDonationEnvelopes', 'aFinanceQueries'], + gettext('Quick Search') => ['bSearchIncludePersons', 'bSearchIncludePersonsMax', 'bSearchIncludeAddresses', 'bSearchIncludeAddressesMax', 'bSearchIncludeFamilies', 'bSearchIncludeFamiliesMax', 'bSearchIncludeFamilyHOH', 'bSearchIncludeFamilyHOHMax', 'bSearchIncludeGroups', 'bSearchIncludeGroupsMax', 'bSearchIncludeDeposits', 'bSearchIncludeDepositsMax', 'bSearchIncludePayments', 'bSearchIncludePaymentsMax', 'bSearchIncludeFamilyCustomProperties', 'bSearchIncludeCalendarEvents', 'bSearchIncludeCalendarEventsMax'], + gettext('Localization') => ['sLanguage', 'sDistanceUnit', 'sPhoneFormat', 'sPhoneFormatWithExt', 'sPhoneFormatCell', 'sDateFormatLong', 'sDateFormatNoYear', 'sDateFormatShort', 'sDateTimeFormat', 'sDateFilenameFormat', 'sCSVExportDelimiter', 'sCSVExportCharset', 'sDatePickerFormat', 'sDatePickerPlaceHolder'], + gettext('Integration') => ['sMailChimpApiKey', 'sGoogleTrackingID', 'bEnableGravatarPhotos', 'bEnableGooglePhotos', 'iRemotePhotoCacheDuration', 'sNexmoAPIKey', 'sNexmoAPISecret', 'sNexmoFromNumber', 'sOLPURL', 'sOLPUserName', 'sOLPPassword'], + gettext('Church Services') => ['iPersonConfessionFatherCustomField', 'iPersonConfessionDateCustomField'], + gettext('Events') => ['bEnableExternalCalendarAPI', 'bEventsOnDashboardPresence', 'iEventsOnDashboardPresenceTimeOut'], + gettext('Backup') => ['sLastBackupTimeStamp', 'bEnableExternalBackupTarget', 'sExternalBackupType', 'sExternalBackupAutoInterval', 'sExternalBackupEndpoint', 'sExternalBackupUsername', 'sExternalBackupPassword', 'bBackupExtraneousImages'], + gettext('System Settings') => ['sLogLevel', 'bRegistered', 'bCSVAdminOnly', 'sHeader', 'bEnableIntegrityCheck', 'iIntegrityCheckInterval', 'sLastIntegrityCheckTimeStamp', 'iPhotoClientCacheDuration', 'bHSTSEnable', 'iDashboardServiceIntervalTime', 'iSoftwareUpdateCheckInterval', 'sLastSoftwareUpdateCheckTimeStamp', 'bAllowPrereleaseUpgrade'], + ]; + } - /** - * @param Config[] $configs - */ - public static function init($configs=null) - { - self::$configs = self::buildConfigs(); - self::$categories = self::buildCategories(); - if (!empty($configs)) { - self::scrapeDBConfigs($configs); - } - } + /** + * @param Config[] $configs + */ + public static function init($configs = null) + { + self::$configs = self::buildConfigs(); + self::$categories = self::buildCategories(); + if (!empty($configs)) { + self::scrapeDBConfigs($configs); + } + } - public static function isInitialized() { - return isset(self::$configs); - } + public static function isInitialized() + { + return isset(self::$configs); + } - public static function getCategories() - { - return self::$categories; - } + public static function getCategories() + { + return self::$categories; + } - private static function scrapeDBConfigs($configs) - { - foreach ($configs as $config) + private static function scrapeDBConfigs($configs) { - if ( isset( self::$configs[$config->getName()])) - { - //if the current config set defined by code contains the current config retrieved from the db, then cache it - self::$configs[$config->getName()]->setDBConfigObject($config); - } - else - { - //there's a config item in the DB that doesn't exist in the current code. - //delete it - $config->delete(); - } + foreach ($configs as $config) { + if (isset(self::$configs[$config->getName()])) { + //if the current config set defined by code contains the current config retrieved from the db, then cache it + self::$configs[$config->getName()]->setDBConfigObject($config); + } else { + //there's a config item in the DB that doesn't exist in the current code. + //delete it + $config->delete(); + } + } } - } public static function getConfigItem($name) { - return self::$configs[$name]; + return self::$configs[$name]; } public static function getValue($name) { - if ( isset(self::$configs[$name]) ) - { - return self::$configs[$name]->getValue(); - } - else - { - throw new \Exception (gettext("An invalid configuration name has been requested").": ".$name); - } + if (isset(self::$configs[$name])) { + return self::$configs[$name]->getValue(); + } else { + throw new \Exception(gettext('An invalid configuration name has been requested').': '.$name); + } } public static function getBooleanValue($name) { - if ( isset(self::$configs[$name]) ) - { - return self::$configs[$name]->getBooleanValue(); - } - else - { - throw new \Exception (gettext("An invalid configuration name has been requested").": ".$name); - } - + if (isset(self::$configs[$name])) { + return self::$configs[$name]->getBooleanValue(); + } else { + throw new \Exception(gettext('An invalid configuration name has been requested').': '.$name); + } } public static function setValue($name, $value) { - if ( isset(self::$configs[$name]) ) - { - self::$configs[$name]->setValue($value); - } - else - { - throw new \Exception (gettext("An invalid configuration name has been requested").": ".$name); - } - + if (isset(self::$configs[$name])) { + self::$configs[$name]->setValue($value); + } else { + throw new \Exception(gettext('An invalid configuration name has been requested').': '.$name); + } } public static function setValueById($Id, $value) { - $success = false; - foreach (self::$configs as $configItem) - { - if ($configItem->getId() == $Id) - { - $configItem->setValue($value); - $success = true; + $success = false; + foreach (self::$configs as $configItem) { + if ($configItem->getId() == $Id) { + $configItem->setValue($value); + $success = true; + } + } + if (!$success) { + throw new \Exception(gettext('An invalid configuration id has been requested').': '.$Id); } - } - if (! $success ) - { - throw new \Exception (gettext("An invalid configuration id has been requested").": ".$Id); - } } - public static function hasValidMailServerSettings() { + public static function hasValidMailServerSettings() + { $hasValidSettings = true; - if (empty(self::getValue("sSMTPHost"))) { + if (empty(self::getValue('sSMTPHost'))) { $hasValidSettings = false; } - if (SystemConfig::getBooleanValue("bSMTPAuth") and (empty(self::getValue("sSMTPUser")) or empty(self::getValue("sSMTPPass")))) { + if (SystemConfig::getBooleanValue('bSMTPAuth') and (empty(self::getValue('sSMTPUser')) or empty(self::getValue('sSMTPPass')))) { $hasValidSettings = false; } return $hasValidSettings; } - public static function hasValidSMSServerSettings() { - return (!empty(self::getValue("sNexmoAPIKey"))) && (!empty(self::getValue("sNexmoAPISecret"))) && (!empty(self::getValue("sNexmoFromNumber"))); + public static function hasValidSMSServerSettings() + { + return (!empty(self::getValue('sNexmoAPIKey'))) && (!empty(self::getValue('sNexmoAPISecret'))) && (!empty(self::getValue('sNexmoFromNumber'))); } - public static function hasValidOpenLPSettings() { - return (!empty(self::getValue("sOLPURL"))); + public static function hasValidOpenLPSettings() + { + return !empty(self::getValue('sOLPURL')); } - - public static function debugEnabled() { - if (self::getValue("sLogLevel") == Logger::DEBUG) { + public static function debugEnabled() + { + if (self::getValue('sLogLevel') == Logger::DEBUG) { return true; } + return false; } } diff --git a/src/ChurchCRM/dto/SystemURLs.php b/src/ChurchCRM/dto/SystemURLs.php index 4fc2550c10..45d14270ef 100644 --- a/src/ChurchCRM/dto/SystemURLs.php +++ b/src/ChurchCRM/dto/SystemURLs.php @@ -32,6 +32,7 @@ public static function getRootPath() if (self::isValidRootPath()) { return self::$rootPath; } + throw new \Exception("Please check the value for '\$sRootPath' in `Include\\Config.php`, the following is not valid [".self::$rootPath.']'); } @@ -39,10 +40,10 @@ public static function getDocumentRoot() { return self::$documentRoot; } - + public static function getImagesRoot() { - return self::$documentRoot."/Images"; + return self::$documentRoot.'/Images'; } public static function getURLs() @@ -50,24 +51,22 @@ public static function getURLs() return self::$urls; } - public static function getSupportURL($topic="") + public static function getSupportURL($topic = '') { - $supportURLs = array( - "HttpsTask" => "https://github.com/ChurchCRM/CRM/wiki/SSL", - "CheckExecutionTimeTask" => "https://github.com/ChurchCRM/CRM/wiki/PHP-Max-Execution-Time", - "SecretsConfigurationCheckTask" => "https://github.com/ChurchCRM/CRM/wiki/Secret-Keys-in-Config.php", - "UnsupportedPaymentDataCheck" => 'https://github.com/ChurchCRM/CRM/wiki/Finances', - "UnsupportedDepositCheck" => 'https://github.com/ChurchCRM/CRM/wiki/Finances', - "CheckUploadSizeTask" => "https://mediatemple.net/community/products/dv/204404784/how-do-i-increase-the-php-upload-limits" - ); - - if ( array_key_exists($topic,$supportURLs) ) { + $supportURLs = [ + 'HttpsTask' => 'https://github.com/ChurchCRM/CRM/wiki/SSL', + 'CheckExecutionTimeTask' => 'https://github.com/ChurchCRM/CRM/wiki/PHP-Max-Execution-Time', + 'SecretsConfigurationCheckTask' => 'https://github.com/ChurchCRM/CRM/wiki/Secret-Keys-in-Config.php', + 'UnsupportedPaymentDataCheck' => 'https://github.com/ChurchCRM/CRM/wiki/Finances', + 'UnsupportedDepositCheck' => 'https://github.com/ChurchCRM/CRM/wiki/Finances', + 'CheckUploadSizeTask' => 'https://mediatemple.net/community/products/dv/204404784/how-do-i-increase-the-php-upload-limits', + ]; + + if (array_key_exists($topic, $supportURLs)) { return $supportURLs[$topic]; - } - else { + } else { return 'https://github.com/ChurchCRM/CRM/wiki'; } - } public static function getURL($index = 0) @@ -75,9 +74,10 @@ public static function getURL($index = 0) // Return the URL configured for this server from Include/Config.php // Trim any trailing slashes from the configured URL $URL = self::$urls[$index]; - if (substr($URL,-1,1) == "/") { - return substr($URL,0,-1); + if (substr($URL, -1, 1) == '/') { + return substr($URL, 0, -1); } + return $URL; } @@ -118,9 +118,9 @@ public static function checkAllowedURL($bLockURL, $URL) } } } - + public static function getCSPNonce() { - return self::$CSPNonce; + return self::$CSPNonce; } } diff --git a/src/ChurchCRM/dto/iCal.php b/src/ChurchCRM/dto/iCal.php index 38ecda23f0..8e62910be3 100644 --- a/src/ChurchCRM/dto/iCal.php +++ b/src/ChurchCRM/dto/iCal.php @@ -6,47 +6,51 @@ * and open the template in the editor. */ - namespace ChurchCRM\dto; +namespace ChurchCRM\dto; + use ChurchCRM\Event; use ChurchCRM\Service\SystemService; use Propel\Runtime\Collection\ObjectCollection; -Class iCal { - - private $icsHeader; - private $eventsArray; - - public function __construct(ObjectCollection $Events, $CalendarName) { - $this->eventsArray = $Events; - $this->icsHeader = "BEGIN:VCALENDAR\r\n". - "VERSION:2.0\r\n". - "PRODID:-//ChurchCRM/CRM//NONSGML v".SystemService::getInstalledVersion()."//EN\r\n". - "CALSCALE:GREGORIAN\r\n". - "METHOD:PUBLISH\r\n". - "X-WR-CALNAME:".$CalendarName."\r\n". - "X-WR-CALDESC:\r\n"; - } - - private function eventToVEVENT(Event $event) { - $now = new \DateTime(); - $UTC = new \DateTimeZone("UTC"); - - return "BEGIN:VEVENT\r\n". - "UID:".$event->getId()."@".ChurchMetaData::getChurchName()."\r\n". - "DTSTAMP:".$now->setTimezone($UTC)->format('Ymd\THis\Z')."\r\n". - "DTSTART:".$event->getStart()->setTimezone($UTC)->format('Ymd\THis\Z')."\r\n". - "DTEND:".$event->getEnd()->setTimezone($UTC)->format('Ymd\THis\Z')."\r\n". - "SUMMARY:".$event->getTitle()."\r\n". - "END:VEVENT\r\n"; - } - - public function toString() { - $iCal = $this->icsHeader; - foreach ($this->eventsArray as $event){ - $iCal .= $this->eventToVEVENT($event); +class iCal +{ + private $icsHeader; + private $eventsArray; + + public function __construct(ObjectCollection $Events, $CalendarName) + { + $this->eventsArray = $Events; + $this->icsHeader = "BEGIN:VCALENDAR\r\n". + "VERSION:2.0\r\n". + 'PRODID:-//ChurchCRM/CRM//NONSGML v'.SystemService::getInstalledVersion()."//EN\r\n". + "CALSCALE:GREGORIAN\r\n". + "METHOD:PUBLISH\r\n". + 'X-WR-CALNAME:'.$CalendarName."\r\n". + "X-WR-CALDESC:\r\n"; + } + + private function eventToVEVENT(Event $event) + { + $now = new \DateTime(); + $UTC = new \DateTimeZone('UTC'); + + return "BEGIN:VEVENT\r\n". + 'UID:'.$event->getId().'@'.ChurchMetaData::getChurchName()."\r\n". + 'DTSTAMP:'.$now->setTimezone($UTC)->format('Ymd\THis\Z')."\r\n". + 'DTSTART:'.$event->getStart()->setTimezone($UTC)->format('Ymd\THis\Z')."\r\n". + 'DTEND:'.$event->getEnd()->setTimezone($UTC)->format('Ymd\THis\Z')."\r\n". + 'SUMMARY:'.$event->getTitle()."\r\n". + "END:VEVENT\r\n"; } - $iCal .="END:VCALENDAR"; - return $iCal; - } + public function toString() + { + $iCal = $this->icsHeader; + foreach ($this->eventsArray as $event) { + $iCal .= $this->eventToVEVENT($event); + } + $iCal .= 'END:VCALENDAR'; + + return $iCal; + } } diff --git a/src/ChurchCRM/iPhoto.php b/src/ChurchCRM/iPhoto.php index 8892c9b982..cae6bc29c6 100644 --- a/src/ChurchCRM/iPhoto.php +++ b/src/ChurchCRM/iPhoto.php @@ -1,9 +1,12 @@ content .= ''; // Export file - $OFXReturn->header = 'Content-Disposition: attachment; filename=ChurchCRM-Deposit-'.$this->getId().'-'.date(SystemConfig::getValue("sDateFilenameFormat")).'.ofx'; + $OFXReturn->header = 'Content-Disposition: attachment; filename=ChurchCRM-Deposit-'.$this->getId().'-'.date(SystemConfig::getValue('sDateFilenameFormat')).'.ofx'; return $OFXReturn; } @@ -147,7 +147,6 @@ private function generateTotalsByFund($thisReport) $thisReport->pdf->PrintRightJustified($thisReport->curX + 55, $thisReport->curY, $amountStr); $thisReport->curY += 4; } - } private function generateQBDepositSlip($thisReport) @@ -352,10 +351,9 @@ private function generateDepositSummary($thisReport) $this->generateTotalsByCurrencyType($thisReport); $thisReport->curY += $thisReport->depositSummaryParameters->summary->intervalY * 2; - if (!empty($this->getComment())) - { - $thisReport->pdf->SetXY($thisReport->curX, $thisReport->curY); - $thisReport->pdf->MultiCell(0, $thisReport->depositSummaryParameters->summary->intervalY, gettext('Deposit Comment') . ": " . $this->getComment(), 0, 'L'); + if (!empty($this->getComment())) { + $thisReport->pdf->SetXY($thisReport->curX, $thisReport->curY); + $thisReport->pdf->MultiCell(0, $thisReport->depositSummaryParameters->summary->intervalY, gettext('Deposit Comment').': '.$this->getComment(), 0, 'L'); } $thisReport->curY += 130; $thisReport->curX = $thisReport->depositSummaryParameters->summary->x; @@ -366,7 +364,7 @@ private function generateDepositSummary($thisReport) private function generateWitnessSignature($thisReport) { $thisReport->curX = $thisReport->depositSummaryParameters->summary->x; - $thisReport->curY = $thisReport->pdf->GetPageHeight() - 30; + $thisReport->curY = $thisReport->pdf->GetPageHeight() - 30; $thisReport->pdf->setXY($thisReport->curX, $thisReport->curY); $thisReport->pdf->write(8, 'Witness 1'); $thisReport->pdf->line($thisReport->curX + 17, $thisReport->curY + 8, $thisReport->curX + 80, $thisReport->curY + 8); @@ -409,7 +407,7 @@ public function getPDF() $this->generateDepositSummary($Report); // Export file - $Report->pdf->Output('ChurchCRM-DepositReport-'.$this->getId().'-'.date(SystemConfig::getValue("sDateFilenameFormat")).'.pdf', 'D'); + $Report->pdf->Output('ChurchCRM-DepositReport-'.$this->getId().'-'.date(SystemConfig::getValue('sDateFilenameFormat')).'.pdf', 'D'); } public function getTotalAmount() diff --git a/src/ChurchCRM/model/ChurchCRM/Event.php b/src/ChurchCRM/model/ChurchCRM/Event.php index a384a24a9b..a79ba438e2 100644 --- a/src/ChurchCRM/model/ChurchCRM/Event.php +++ b/src/ChurchCRM/model/ChurchCRM/Event.php @@ -17,71 +17,69 @@ */ class Event extends BaseEvent { - - private $editable; - - public function __construct() { - parent::__construct(); - $this->editable = true; - } - - public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) - { - - $array = parent::toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, $includeForeignObjects); - $array['PinnedCalendars'] = array_map('intval',Base\CalendarEventQuery::create() - ->filterByEventId($this->getId()) - ->select(Map\CalendarEventTableMap::COL_CALENDAR_ID) - ->find()->toArray()); - return $array; - - } - - public function isEditable() - { - return $this->editable; - } - - public function setEditable($editable) { - $this->editable = $editable; - } - - public function checkInPerson($PersonId) - { - $AttendanceRecord = EventAttendQuery::create() - ->filterByEvent($this) - ->filterByPersonId($PersonId) - ->findOneOrCreate(); - - $AttendanceRecord->setEvent($this) - ->setPersonId($PersonId) - ->setCheckinDate(date('Y-m-d H:i:s')) - ->setCheckoutDate(null) - ->save(); - - return array("status"=>"success"); - - } - - public function checkOutPerson($PersonId) - { - $AttendanceRecord = EventAttendQuery::create() - ->filterByEvent($this) - ->filterByPersonId($PersonId) - ->filterByCheckinDate(NULL, Criteria::NOT_EQUAL) - ->findOne(); - - $AttendanceRecord->setEvent($this) - ->setPersonId($PersonId) - ->setCheckoutDate(date('Y-m-d H:i:s')) - ->save(); - - return array("status"=>"success"); - - } - - public function getViewURI() - { - return SystemURLs::getRootPath()."/EventEditor.php?calendarAction=".$this->getID(); - } + private $editable; + + public function __construct() + { + parent::__construct(); + $this->editable = true; + } + + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = [], $includeForeignObjects = false) + { + $array = parent::toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, $includeForeignObjects); + $array['PinnedCalendars'] = array_map('intval', Base\CalendarEventQuery::create() + ->filterByEventId($this->getId()) + ->select(Map\CalendarEventTableMap::COL_CALENDAR_ID) + ->find()->toArray()); + + return $array; + } + + public function isEditable() + { + return $this->editable; + } + + public function setEditable($editable) + { + $this->editable = $editable; + } + + public function checkInPerson($PersonId) + { + $AttendanceRecord = EventAttendQuery::create() + ->filterByEvent($this) + ->filterByPersonId($PersonId) + ->findOneOrCreate(); + + $AttendanceRecord->setEvent($this) + ->setPersonId($PersonId) + ->setCheckinDate(date('Y-m-d H:i:s')) + ->setCheckoutDate(null) + ->save(); + + return ['status'=>'success']; + } + + public function checkOutPerson($PersonId) + { + $AttendanceRecord = EventAttendQuery::create() + ->filterByEvent($this) + ->filterByPersonId($PersonId) + ->filterByCheckinDate(null, Criteria::NOT_EQUAL) + ->findOne(); + + $AttendanceRecord->setEvent($this) + ->setPersonId($PersonId) + ->setCheckoutDate(date('Y-m-d H:i:s')) + ->save(); + + return ['status'=>'success']; + } + + public function getViewURI() + { + return SystemURLs::getRootPath().'/EventEditor.php?calendarAction='.$this->getID(); + } } diff --git a/src/ChurchCRM/model/ChurchCRM/EventAudience.php b/src/ChurchCRM/model/ChurchCRM/EventAudience.php index e23605749c..35b375024c 100644 --- a/src/ChurchCRM/model/ChurchCRM/EventAudience.php +++ b/src/ChurchCRM/model/ChurchCRM/EventAudience.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class EventAudience extends BaseEventAudience { - } diff --git a/src/ChurchCRM/model/ChurchCRM/EventAudienceQuery.php b/src/ChurchCRM/model/ChurchCRM/EventAudienceQuery.php index c0548d6363..064766f09f 100644 --- a/src/ChurchCRM/model/ChurchCRM/EventAudienceQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/EventAudienceQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class EventAudienceQuery extends BaseEventAudienceQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/EventType.php b/src/ChurchCRM/model/ChurchCRM/EventType.php index 011f77afe9..a0142b04e0 100644 --- a/src/ChurchCRM/model/ChurchCRM/EventType.php +++ b/src/ChurchCRM/model/ChurchCRM/EventType.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class EventType extends BaseEventType { - } diff --git a/src/ChurchCRM/model/ChurchCRM/EventTypeQuery.php b/src/ChurchCRM/model/ChurchCRM/EventTypeQuery.php index e88ab3b269..31853aa918 100644 --- a/src/ChurchCRM/model/ChurchCRM/EventTypeQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/EventTypeQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class EventTypeQuery extends BaseEventTypeQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/Family.php b/src/ChurchCRM/model/ChurchCRM/Family.php index f1427f5961..3f3b0ddd00 100644 --- a/src/ChurchCRM/model/ChurchCRM/Family.php +++ b/src/ChurchCRM/model/ChurchCRM/Family.php @@ -86,12 +86,11 @@ public function getWeddingMonth() public function postInsert(ConnectionInterface $con = null) { $this->createTimeLineNote('create'); - if (!empty(SystemConfig::getValue("sNewPersonNotificationRecipientIDs"))) - { - $NotificationEmail = new NewPersonOrFamilyEmail($this); - if (!$NotificationEmail->send()) { - LoggerUtils::getAppLogger()->warning(gettext("New Family Notification Email Error"). " :". $NotificationEmail->getError()); - } + if (!empty(SystemConfig::getValue('sNewPersonNotificationRecipientIDs'))) { + $NotificationEmail = new NewPersonOrFamilyEmail($this); + if (!$NotificationEmail->send()) { + LoggerUtils::getAppLogger()->warning(gettext('New Family Notification Email Error').' :'.$NotificationEmail->getError()); + } } } @@ -102,75 +101,92 @@ public function postUpdate(ConnectionInterface $con = null) } } + public function getPeopleSorted() + { + $familyMembersParents = array_merge($this->getHeadPeople(), $this->getSpousePeople()); + $familyMembersChildren = $this->getChildPeople(); + $familyMembersOther = $this->getOtherPeople(); + + return array_merge($familyMembersParents, $familyMembersChildren, $familyMembersOther); + } + + public function getHeadPeople() + { + return $this->getPeopleByRole('sDirRoleHead'); + } + + public function getSpousePeople() + { + return $this->getPeopleByRole('sDirRoleSpouse'); + } + + public function getAdults() + { + return array_merge($this->getHeadPeople(), $this->getSpousePeople()); + } + + public function getChildPeople() + { + return $this->getPeopleByRole('sDirRoleChild'); + } + + public function getOtherPeople() + { + $roleIds = array_merge( + explode(',', SystemConfig::getValue('sDirRoleHead')), + explode( + ',', + SystemConfig::getValue('sDirRoleSpouse') + ), + explode(',', SystemConfig::getValue('sDirRoleChild')) + ); + $foundPeople = []; + foreach ($this->getPeopleSorted() as $person) { + if (!in_array($person->getFmrId(), $roleIds)) { + array_push($foundPeople, $person); + } + } - public function getPeopleSorted() { - $familyMembersParents = array_merge($this->getHeadPeople(), $this->getSpousePeople()); - $familyMembersChildren = $this->getChildPeople(); - $familyMembersOther = $this->getOtherPeople(); - return array_merge($familyMembersParents, $familyMembersChildren, $familyMembersOther); - } - - public function getHeadPeople() { - return $this->getPeopleByRole("sDirRoleHead"); - } - - public function getSpousePeople() { - return $this->getPeopleByRole("sDirRoleSpouse"); - } - - public function getAdults() { - return array_merge($this->getHeadPeople(),$this->getSpousePeople()); - } - - public function getChildPeople() { - return $this->getPeopleByRole("sDirRoleChild"); - } - - public function getOtherPeople() { - $roleIds = array_merge (explode(",", SystemConfig::getValue("sDirRoleHead")), explode(",", - SystemConfig::getValue("sDirRoleSpouse")), - explode(",", SystemConfig::getValue("sDirRoleChild"))); - $foundPeople = array(); - foreach ($this->getPeopleSorted() as $person) { - if (!in_array($person->getFmrId(), $roleIds)) { - array_push($foundPeople, $person); - } + return $foundPeople; } - return $foundPeople; - } - - private function getPeopleByRole($roleConfigName) { - $roleIds = explode(",", SystemConfig::getValue($roleConfigName)); - $foundPeople = array(); - foreach ($this->getPeopleSorted() as $person) { - if (in_array($person->getFmrId(), $roleIds)) { - array_push($foundPeople, $person); - } + + private function getPeopleByRole($roleConfigName) + { + $roleIds = explode(',', SystemConfig::getValue($roleConfigName)); + $foundPeople = []; + foreach ($this->getPeopleSorted() as $person) { + if (in_array($person->getFmrId(), $roleIds)) { + array_push($foundPeople, $person); + } + } + + return $foundPeople; } - return $foundPeople; - } /** - * @return array * @throws \Propel\Runtime\Exception\PropelException + * + * @return array */ - public function getEmails() { - $emails = array(); - if (!(empty($this->getEmail()))) { - array_push($emails, $this->getEmail()); - } - foreach ($this->getPeopleSorted() as $person) { - $email = $person->getEmail(); - if ($email != null) { - array_push($emails, $email); + public function getEmails() + { + $emails = []; + if (!(empty($this->getEmail()))) { + array_push($emails, $this->getEmail()); } - $email = $person->getWorkEmail(); - if ($email != null) { - array_push($emails, $email); + foreach ($this->getPeopleSorted() as $person) { + $email = $person->getEmail(); + if ($email != null) { + array_push($emails, $email); + } + $email = $person->getWorkEmail(); + if ($email != null) { + array_push($emails, $email); + } } + + return $emails; } - return $emails; - } public function createTimeLineNote($type) { @@ -180,25 +196,25 @@ public function createTimeLineNote($type) $note->setDateEntered(new DateTime()); switch ($type) { - case "create": - $note->setText(gettext('Created')); - $note->setEnteredBy($this->getEnteredBy()); - $note->setDateEntered($this->getDateEntered()); - break; - case "edit": - $note->setText(gettext('Updated')); + case 'create': + $note->setText(gettext('Created')); + $note->setEnteredBy($this->getEnteredBy()); + $note->setDateEntered($this->getDateEntered()); + break; + case 'edit': + $note->setText(gettext('Updated')); $note->setEnteredBy($this->getEditedBy()); $note->setDateEntered($this->getDateLastEdited()); break; - case "verify": + case 'verify': $note->setText(gettext('Family Data Verified')); $note->setEnteredBy(AuthenticationManager::GetCurrentUser()->getId()); break; - case "verify-link": - $note->setText(gettext('Verification email sent')); - $note->setEnteredBy(AuthenticationManager::GetCurrentUser()->getId()); - break; - case "verify-URL": + case 'verify-link': + $note->setText(gettext('Verification email sent')); + $note->setEnteredBy(AuthenticationManager::GetCurrentUser()->getId()); + break; + case 'verify-URL': $note->setText(gettext('Verification URL created')); $note->setEnteredBy(AuthenticationManager::GetCurrentUser()->getId()); break; @@ -212,41 +228,46 @@ public function createTimeLineNote($type) */ public function getPhoto() { - if (!$this->photo) - { - $this->photo = new Photo("Family", $this->getId()); - } - return $this->photo; + if (!$this->photo) { + $this->photo = new Photo('Family', $this->getId()); + } + + return $this->photo; } public function deletePhoto() { - if (AuthenticationManager::GetCurrentUser()->isDeleteRecordsEnabled() ) { - if ( $this->getPhoto()->delete() ) - { - $note = new Note(); - $note->setText(gettext("Profile Image Deleted")); - $note->setType("photo"); - $note->setEntered(AuthenticationManager::GetCurrentUser()->getId()); - $note->setPerId($this->getId()); - $note->save(); - return true; + if (AuthenticationManager::GetCurrentUser()->isDeleteRecordsEnabled()) { + if ($this->getPhoto()->delete()) { + $note = new Note(); + $note->setText(gettext('Profile Image Deleted')); + $note->setType('photo'); + $note->setEntered(AuthenticationManager::GetCurrentUser()->getId()); + $note->setPerId($this->getId()); + $note->save(); + + return true; + } } - } - return false; + + return false; } - public function setImageFromBase64($base64) { - if (AuthenticationManager::GetCurrentUser()->isEditRecordsEnabled() ) { - $note = new Note(); - $note->setText(gettext("Profile Image uploaded")); - $note->setType("photo"); - $note->setEntered(AuthenticationManager::GetCurrentUser()->getId()); - $this->getPhoto()->setImageFromBase64($base64); - $note->setFamId($this->getId()); - $note->save(); - return true; - } - return false; + + public function setImageFromBase64($base64) + { + if (AuthenticationManager::GetCurrentUser()->isEditRecordsEnabled()) { + $note = new Note(); + $note->setText(gettext('Profile Image uploaded')); + $note->setType('photo'); + $note->setEntered(AuthenticationManager::GetCurrentUser()->getId()); + $this->getPhoto()->setImageFromBase64($base64); + $note->setFamId($this->getId()); + $note->save(); + + return true; + } + + return false; } public function verify() @@ -254,43 +275,41 @@ public function verify() $this->createTimeLineNote('verify'); } - public function getFamilyString($booleanIncludeHOH=true) + public function getFamilyString($booleanIncludeHOH = true) { - $HoH = []; - if ($booleanIncludeHOH) { - $HoH = $this->getHeadPeople(); - } - if (count($HoH) == 1) - { - return $this->getName(). ": " . $HoH[0]->getFirstName() . " - " . $this->getAddress(); - } - elseif (count($HoH) > 1) - { - $HoHs = []; - foreach ($HoH as $person) { - array_push($HoHs, $person->getFirstName()); + $HoH = []; + if ($booleanIncludeHOH) { + $HoH = $this->getHeadPeople(); } + if (count($HoH) == 1) { + return $this->getName().': '.$HoH[0]->getFirstName().' - '.$this->getAddress(); + } elseif (count($HoH) > 1) { + $HoHs = []; + foreach ($HoH as $person) { + array_push($HoHs, $person->getFirstName()); + } - return $this->getName(). ": " . join(",", $HoHs) . " - " . $this->getAddress(); - } - else - { - return $this->getName(). " " . $this->getAddress(); - } + return $this->getName().': '.join(',', $HoHs).' - '.$this->getAddress(); + } else { + return $this->getName().' '.$this->getAddress(); + } } - public function hasLatitudeAndLongitude() { + public function hasLatitudeAndLongitude() + { return !empty($this->getLatitude()) && !empty($this->getLongitude()); } /** * if the latitude or longitude is empty find the lat/lng from the address and update the lat lng for the family. + * * @return array of Lat/Lng */ - public function updateLanLng() { + public function updateLanLng() + { if (!empty($this->getAddress()) && (!$this->hasLatitudeAndLongitude())) { $latLng = GeoUtils::getLatLong($this->getAddress()); - if(!empty( $latLng['Latitude']) && !empty($latLng['Longitude'])) { + if (!empty($latLng['Latitude']) && !empty($latLng['Longitude'])) { $this->setLatitude($latLng['Latitude']); $this->setLongitude($latLng['Longitude']); $this->save(); @@ -298,56 +317,63 @@ public function updateLanLng() { } } - public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = Array(), $includeForeignObjects = false) + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = [], $includeForeignObjects = false) { - $array = parent::toArray(); - $array['Address']=$this->getAddress(); - $array['FamilyString']=$this->getFamilyString(); - return $array; + $array = parent::toArray(); + $array['Address'] = $this->getAddress(); + $array['FamilyString'] = $this->getFamilyString(); + + return $array; } public function toSearchArray() { - $searchArray=[ - "Id" => $this->getId(), - "displayName" => $this->getFamilyString(SystemConfig::getBooleanValue("bSearchIncludeFamilyHOH")), - "uri" => SystemURLs::getRootPath() . '/v2/family/' . $this->getId() - ]; - return $searchArray; + $searchArray = [ + 'Id' => $this->getId(), + 'displayName' => $this->getFamilyString(SystemConfig::getBooleanValue('bSearchIncludeFamilyHOH')), + 'uri' => SystemURLs::getRootPath().'/v2/family/'.$this->getId(), + ]; + + return $searchArray; } - public function isActive() { + public function isActive() + { return empty($this->getDateDeactivated()); } - public function getProperties() { + public function getProperties() + { return PropertyQuery::create() - ->filterByProClass("f") + ->filterByProClass('f') ->useRecordPropertyQuery() ->filterByRecordId($this->getId()) ->find(); } - public function sendVerifyEmail() { + public function sendVerifyEmail() + { $familyEmails = $this->getEmails(); if (empty($familyEmails)) { - throw new \Exception(gettext("Family has no emails to use")); + throw new \Exception(gettext('Family has no emails to use')); } // delete old tokens - TokenQuery::create()->filterByType("verifyFamily")->filterByReferenceId($this->getId())->delete(); + TokenQuery::create()->filterByType('verifyFamily')->filterByReferenceId($this->getId())->delete(); // create a new token an send to all emails $token = new Token(); - $token->build("verifyFamily", $this->getId()); + $token->build('verifyFamily', $this->getId()); $token->save(); $email = new FamilyVerificationEmail($familyEmails, $this->getName(), $token); if (!$email->send()) { LoggerUtils::getAppLogger()->error($email->getError()); + throw new \Exception($email->getError()); } - $this->createTimeLineNote("verify-link"); + $this->createTimeLineNote('verify-link'); + return true; } @@ -358,22 +384,22 @@ public function isSendNewsletter() public function getSalutation() { - $adults = $this->getAdults(); - $adultsCount = count($adults); - - if ($adultsCount == 1) { - return $adults[0]->getFullName(); - } elseif ($adultsCount == 2) { - $firstLastName = $adults[0]->getLastName(); - $secondLastName = $adults[1]->getLastName(); - if ($firstLastName == $secondLastName) { - return $adults[0]->getFirstName().' & '.$adults[1]->getFirstName().' '.$firstLastName; - } else { - return $adults[0]->getFullName().' & '.$adults[1]->getFullName(); - } - } else { - return $this->getName().' Family'; - } + $adults = $this->getAdults(); + $adultsCount = count($adults); + + if ($adultsCount == 1) { + return $adults[0]->getFullName(); + } elseif ($adultsCount == 2) { + $firstLastName = $adults[0]->getLastName(); + $secondLastName = $adults[1]->getLastName(); + if ($firstLastName == $secondLastName) { + return $adults[0]->getFirstName().' & '.$adults[1]->getFirstName().' '.$firstLastName; + } else { + return $adults[0]->getFullName().' & '.$adults[1]->getFullName(); + } + } else { + return $this->getName().' Family'; + } } public function getFirstNameSalutation() @@ -382,6 +408,7 @@ public function getFirstNameSalutation() foreach ($this->getPeopleSorted() as $person) { array_push($names, $person->getFirstName()); } - return implode(", ", $names); + + return implode(', ', $names); } } diff --git a/src/ChurchCRM/model/ChurchCRM/Group.php b/src/ChurchCRM/model/ChurchCRM/Group.php index 7f4db4ac4b..234b8cc362 100644 --- a/src/ChurchCRM/model/ChurchCRM/Group.php +++ b/src/ChurchCRM/model/ChurchCRM/Group.php @@ -95,26 +95,26 @@ public function checkAgainstCart() $groupMemberships = $this->getPerson2group2roleP2g2rsJoinPerson(); $bNoneInCart = true; $bAllInCart = true; - //Loop through the recordset - foreach ($groupMemberships as $groupMembership) { - if (!isset($_SESSION['aPeopleCart'])) { - $bAllInCart = false; - } // Cart does not exist. This person is not in cart. - elseif (!in_array($groupMembership->getPersonId(), $_SESSION['aPeopleCart'], false)) { - $bAllInCart = false; - } // This person is not in cart. - elseif (in_array($groupMembership->getPersonId(), $_SESSION['aPeopleCart'], false)) { - $bNoneInCart = false; - } // This person is in the cart - } + //Loop through the recordset + foreach ($groupMemberships as $groupMembership) { + if (!isset($_SESSION['aPeopleCart'])) { + $bAllInCart = false; + } // Cart does not exist. This person is not in cart. + elseif (!in_array($groupMembership->getPersonId(), $_SESSION['aPeopleCart'], false)) { + $bAllInCart = false; + } // This person is not in cart. + elseif (in_array($groupMembership->getPersonId(), $_SESSION['aPeopleCart'], false)) { + $bNoneInCart = false; + } // This person is in the cart + } if (!$bAllInCart) { //there is at least one person in this group who is not in the cart. Return false - return false; + return false; } if (!$bNoneInCart) { //every member of this group is in the cart. Return true - return true; + return true; } return false; @@ -122,6 +122,6 @@ public function checkAgainstCart() public function getViewURI() { - return SystemURLs::getRootPath() . '/GroupView.php?GroupID=' . $this->getId(); + return SystemURLs::getRootPath().'/GroupView.php?GroupID='.$this->getId(); } } diff --git a/src/ChurchCRM/model/ChurchCRM/GroupQuery.php b/src/ChurchCRM/model/ChurchCRM/GroupQuery.php index 626d43fbf9..a533eaa893 100644 --- a/src/ChurchCRM/model/ChurchCRM/GroupQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/GroupQuery.php @@ -24,8 +24,8 @@ public function preSelect(ConnectionInterface $con) $this->withColumn('COUNT(person2group2role_p2g2r.PersonId)', 'memberCount'); $this->groupBy('Group.Id'); $groupTypeJoin = new Join(); - $groupTypeJoin->addCondition("Group.Type", "list_lst.lst_OptionId", self::EQUAL ); - $groupTypeJoin->addForeignValueCondition("list_lst", "lst_ID", '', 3, self::EQUAL); + $groupTypeJoin->addCondition('Group.Type', 'list_lst.lst_OptionId', self::EQUAL); + $groupTypeJoin->addForeignValueCondition('list_lst', 'lst_ID', '', 3, self::EQUAL); $groupTypeJoin->setJoinType(Criteria::LEFT_JOIN); $this->addJoinObject($groupTypeJoin); $this->withColumn('list_lst.lst_OptionName', 'groupType'); diff --git a/src/ChurchCRM/model/ChurchCRM/KioskAssignment.php b/src/ChurchCRM/model/ChurchCRM/KioskAssignment.php index d521d2f412..c201e8a3a8 100644 --- a/src/ChurchCRM/model/ChurchCRM/KioskAssignment.php +++ b/src/ChurchCRM/model/ChurchCRM/KioskAssignment.php @@ -16,55 +16,48 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class KioskAssignment extends BaseKioskAssignment { - - private function getActiveEvent() - { - if ($this->getAssignmentType() == KioskAssignmentTypes::EVENTATTENDANCEKIOSK) + private function getActiveEvent() { - $Event = EventQuery::create() - ->filterByStart('now', Criteria::LESS_EQUAL) - ->filterByEnd('now',Criteria::GREATER_EQUAL) - ->filterById($this->getEventId()) - ->findOne(); - return $Event; - } - else - { - throw new \Exception("This kiosk does not support group attendance"); + if ($this->getAssignmentType() == KioskAssignmentTypes::EVENTATTENDANCEKIOSK) { + $Event = EventQuery::create() + ->filterByStart('now', Criteria::LESS_EQUAL) + ->filterByEnd('now', Criteria::GREATER_EQUAL) + ->filterById($this->getEventId()) + ->findOne(); + + return $Event; + } else { + throw new \Exception('This kiosk does not support group attendance'); + } } - } - public function getActiveGroupMembers() - { - if ($this->getAssignmentType() == KioskAssignmentTypes::EVENTATTENDANCEKIOSK) + public function getActiveGroupMembers() { - $groupTypeJoin = new Join(); - $groupTypeJoin->addCondition("Person2group2roleP2g2r.RoleId", "list_lst.lst_OptionId", Join::EQUAL); - $groupTypeJoin->addForeignValueCondition("list_lst", "lst_ID", '', $this->getActiveEvent()->getGroup()->getRoleListId(), Join::EQUAL); - $groupTypeJoin->setJoinType(Criteria::LEFT_JOIN); + if ($this->getAssignmentType() == KioskAssignmentTypes::EVENTATTENDANCEKIOSK) { + $groupTypeJoin = new Join(); + $groupTypeJoin->addCondition('Person2group2roleP2g2r.RoleId', 'list_lst.lst_OptionId', Join::EQUAL); + $groupTypeJoin->addForeignValueCondition('list_lst', 'lst_ID', '', $this->getActiveEvent()->getGroup()->getRoleListId(), Join::EQUAL); + $groupTypeJoin->setJoinType(Criteria::LEFT_JOIN); - $ssClass = PersonQuery::create() - ->joinWithPerson2group2roleP2g2r() - ->usePerson2group2roleP2g2rQuery() - ->filterByGroupId($this->getEvent()->getGroupId()) - ->joinGroup() - ->addJoinObject($groupTypeJoin) - ->withColumn(ListOptionTableMap::COL_LST_OPTIONNAME,"RoleName") - ->endUse() - ->leftJoin('EventAttend') - ->withColumn("(CASE WHEN event_attend.event_id is not null AND event_attend.checkout_date IS NULL then 1 else 0 end)","status") - ->select(array("Id","FirstName","LastName","status")) - ->find(); - return $ssClass; - } - else - { - throw new \Exception("This kiosk does not support group attendance"); - } - } + $ssClass = PersonQuery::create() + ->joinWithPerson2group2roleP2g2r() + ->usePerson2group2roleP2g2rQuery() + ->filterByGroupId($this->getEvent()->getGroupId()) + ->joinGroup() + ->addJoinObject($groupTypeJoin) + ->withColumn(ListOptionTableMap::COL_LST_OPTIONNAME, 'RoleName') + ->endUse() + ->leftJoin('EventAttend') + ->withColumn('(CASE WHEN event_attend.event_id is not null AND event_attend.checkout_date IS NULL then 1 else 0 end)', 'status') + ->select(['Id', 'FirstName', 'LastName', 'status']) + ->find(); + return $ssClass; + } else { + throw new \Exception('This kiosk does not support group attendance'); + } + } } diff --git a/src/ChurchCRM/model/ChurchCRM/KioskAssignmentQuery.php b/src/ChurchCRM/model/ChurchCRM/KioskAssignmentQuery.php index d2298f541c..9e9570aceb 100644 --- a/src/ChurchCRM/model/ChurchCRM/KioskAssignmentQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/KioskAssignmentQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class KioskAssignmentQuery extends BaseKioskAssignmentQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/KioskDevice.php b/src/ChurchCRM/model/ChurchCRM/KioskDevice.php index 5f7a9c98ea..41364825b7 100644 --- a/src/ChurchCRM/model/ChurchCRM/KioskDevice.php +++ b/src/ChurchCRM/model/ChurchCRM/KioskDevice.php @@ -3,81 +3,78 @@ namespace ChurchCRM; use ChurchCRM\Base\KioskDevice as BaseKioskDevice; -use ChurchCRM\Map\ListOptionTableMap; - class KioskDevice extends BaseKioskDevice { + public function getActiveAssignment() + { + return $this->getKioskAssignments()[0]; + } - public function getActiveAssignment() - { - return $this->getKioskAssignments()[0]; - } + public function setAssignment($assignmentType, $eventId) + { + $assignment = $this->getActiveAssignment(); + if (is_null($assignment)) { + $assignment = new KioskAssignment(); + $assignment->setKioskDevice($this); + } + $assignment->setAssignmentType($assignmentType); + $assignment->setEventId($eventId); + $assignment->save(); + } - public function setAssignment($assignmentType,$eventId) - { - $assignment = $this->getActiveAssignment(); - if (is_null($assignment)) + public function heartbeat() { - $assignment = new KioskAssignment(); - $assignment->setKioskDevice($this); + $this->setLastHeartbeat(date('Y-m-d H:i:s')) + ->save(); + + $assignmentJSON = null; + $assignment = $this->getActiveAssignment(); + + if (isset($assignment) && $assignment->getAssignmentType() == dto\KioskAssignmentTypes::EVENTATTENDANCEKIOSK) { + $assignment->getEvent(); + $assignmentJSON = $assignment->toJSON(); + } + + return [ + 'Accepted' => $this->getAccepted(), + 'Name' => $this->getName(), + 'Assignment'=> $assignmentJSON, + 'Commands' => $this->getPendingCommands(), + ]; } - $assignment->setAssignmentType($assignmentType); - $assignment->setEventId($eventId); - $assignment->save(); - } - public function heartbeat() - { - $this->setLastHeartbeat(date('Y-m-d H:i:s')) - ->save(); + public function getPendingCommands() + { + $commands = parent::getPendingCommands(); + $this->setPendingCommands(null); + $this->save(); - $assignmentJSON = null; - $assignment = $this->getActiveAssignment(); + return $commands; + } - if (isset($assignment) && $assignment->getAssignmentType() == dto\KioskAssignmentTypes::EVENTATTENDANCEKIOSK ) + public function reloadKiosk() { - $assignment->getEvent(); - $assignmentJSON = $assignment->toJSON(); - } + $this->setPendingCommands('Reload'); + $this->save(); + return true; + } - return array( - "Accepted"=>$this->getAccepted(), - "Name"=>$this->getName(), - "Assignment"=>$assignmentJSON, - "Commands"=>$this->getPendingCommands() - ); - } - - public function getPendingCommands() - { - $commands = parent::getPendingCommands(); - $this->setPendingCommands(null); - $this->save(); - return $commands; - } - - public function reloadKiosk() - { - $this->setPendingCommands("Reload"); - $this->save(); - return true; - } - - public function identifyKiosk() - { - $this->setPendingCommands("Identify"); - $this->save(); - return true; - } - - public function preInsert(\Propel\Runtime\Connection\ConnectionInterface $con = null) { - if (!isset($this->Name)) + public function identifyKiosk() { - $this->setName(Utils\MiscUtils::random_word()); + $this->setPendingCommands('Identify'); + $this->save(); + + return true; } - return true; - } + public function preInsert(\Propel\Runtime\Connection\ConnectionInterface $con = null) + { + if (!isset($this->Name)) { + $this->setName(Utils\MiscUtils::random_word()); + } + + return true; + } } diff --git a/src/ChurchCRM/model/ChurchCRM/KioskDeviceQuery.php b/src/ChurchCRM/model/ChurchCRM/KioskDeviceQuery.php index af6340a2de..8d958ba72f 100644 --- a/src/ChurchCRM/model/ChurchCRM/KioskDeviceQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/KioskDeviceQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class KioskDeviceQuery extends BaseKioskDeviceQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/ListOptionQuery.php b/src/ChurchCRM/model/ChurchCRM/ListOptionQuery.php index c30735ec22..37f0952462 100644 --- a/src/ChurchCRM/model/ChurchCRM/ListOptionQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/ListOptionQuery.php @@ -15,11 +15,6 @@ */ class ListOptionQuery extends BaseListOptionQuery { - - - /** - * - */ public function getFamilyRoles() { return $this diff --git a/src/ChurchCRM/model/ChurchCRM/Location.php b/src/ChurchCRM/model/ChurchCRM/Location.php index 1547fe974c..7026149431 100644 --- a/src/ChurchCRM/model/ChurchCRM/Location.php +++ b/src/ChurchCRM/model/ChurchCRM/Location.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class Location extends BaseLocation { - } diff --git a/src/ChurchCRM/model/ChurchCRM/LocationQuery.php b/src/ChurchCRM/model/ChurchCRM/LocationQuery.php index ce2d7de1ce..e443a93a51 100644 --- a/src/ChurchCRM/model/ChurchCRM/LocationQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/LocationQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class LocationQuery extends BaseLocationQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/MenuLink.php b/src/ChurchCRM/model/ChurchCRM/MenuLink.php index a1b44ac14c..5594de26f1 100644 --- a/src/ChurchCRM/model/ChurchCRM/MenuLink.php +++ b/src/ChurchCRM/model/ChurchCRM/MenuLink.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class MenuLink extends BaseMenuLink { - } diff --git a/src/ChurchCRM/model/ChurchCRM/MenuLinkQuery.php b/src/ChurchCRM/model/ChurchCRM/MenuLinkQuery.php index 370aa3354e..4aa45216f8 100644 --- a/src/ChurchCRM/model/ChurchCRM/MenuLinkQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/MenuLinkQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class MenuLinkQuery extends BaseMenuLinkQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/Person.php b/src/ChurchCRM/model/ChurchCRM/Person.php index 89c844e6aa..210b3311e2 100644 --- a/src/ChurchCRM/model/ChurchCRM/Person.php +++ b/src/ChurchCRM/model/ChurchCRM/Person.php @@ -25,7 +25,6 @@ */ class Person extends BasePerson implements iPhoto { - const SELF_REGISTER = -1; const SELF_VERIFY = -2; private $photo; @@ -47,12 +46,12 @@ public function isFemale() public function getGenderName() { - switch (strtolower($this->getGender())) { - case 1: - return gettext('Male'); - case 2: - return gettext('Female'); - } + switch (strtolower($this->getGender())) { + case 1: + return gettext('Male'); + case 2: + return gettext('Female'); + } } public function hideAge() @@ -66,36 +65,32 @@ public function getBirthDate() !is_null($this->getBirthMonth()) && $this->getBirthMonth() != '' ) { $birthYear = $this->getBirthYear(); - if ($birthYear == '') - { - $birthYear = 1900; + if ($birthYear == '') { + $birthYear = 1900; } - return date_create($birthYear . '-' . $this->getBirthMonth() . '-' . $this->getBirthDay()); + + return date_create($birthYear.'-'.$this->getBirthMonth().'-'.$this->getBirthDay()); } - return false; + return false; } public function getFormattedBirthDate() { - $birthDate = $this->getBirthDate(); - if (!$birthDate) { - return false; - } - if ($this->hideAge()) - { - return $birthDate->format(SystemConfig::getValue("sDateFormatNoYear")); - } - else - { - return $birthDate->format(SystemConfig::getValue("sDateFormatLong")); - } - + $birthDate = $this->getBirthDate(); + if (!$birthDate) { + return false; + } + if ($this->hideAge()) { + return $birthDate->format(SystemConfig::getValue('sDateFormatNoYear')); + } else { + return $birthDate->format(SystemConfig::getValue('sDateFormatLong')); + } } public function getViewURI() { - return SystemURLs::getRootPath() . '/PersonView.php?PersonID=' . $this->getId(); + return SystemURLs::getRootPath().'/PersonView.php?PersonID='.$this->getId(); } public function getFamilyRole() @@ -122,41 +117,42 @@ public function getFamilyRoleName() public function getClassification() { - $classification = null; - $clsId = $this->getClsId(); - if (!empty($clsId)) { - $classification = ListOptionQuery::create()->filterById(1)->filterByOptionId($clsId)->findOne(); - } - return $classification; + $classification = null; + $clsId = $this->getClsId(); + if (!empty($clsId)) { + $classification = ListOptionQuery::create()->filterById(1)->filterByOptionId($clsId)->findOne(); + } + + return $classification; } public function getClassificationName() { - $classificationName = ''; - $classification = $this->getClassification(); - if (!is_null($classification)) { - $classificationName = $classification->getOptionName(); - } - return $classificationName; + $classificationName = ''; + $classification = $this->getClassification(); + if (!is_null($classification)) { + $classificationName = $classification->getOptionName(); + } + + return $classificationName; } public function postInsert(ConnectionInterface $con = null) { - $this->createTimeLineNote('create'); - if (!empty(SystemConfig::getValue("sNewPersonNotificationRecipientIDs"))) - { - $NotificationEmail = new NewPersonOrFamilyEmail($this); - if (!$NotificationEmail->send()) { - LoggerUtils::getAppLogger()->warning(gettext("New Person Notification Email Error"). " :". $NotificationEmail->getError()); + $this->createTimeLineNote('create'); + if (!empty(SystemConfig::getValue('sNewPersonNotificationRecipientIDs'))) { + $NotificationEmail = new NewPersonOrFamilyEmail($this); + if (!$NotificationEmail->send()) { + LoggerUtils::getAppLogger()->warning(gettext('New Person Notification Email Error').' :'.$NotificationEmail->getError()); + } } - } } public function postUpdate(ConnectionInterface $con = null) { - if (!empty($this->getDateLastEdited())) { - $this->createTimeLineNote('edit'); - } + if (!empty($this->getDateLastEdited())) { + $this->createTimeLineNote('edit'); + } } private function createTimeLineNote($type) @@ -166,17 +162,17 @@ private function createTimeLineNote($type) $note->setType($type); $note->setDateEntered(new DateTime()); - switch ($type) { - case "create": - $note->setText(gettext('Created')); - $note->setEnteredBy($this->getEnteredBy()); - $note->setDateEntered($this->getDateEntered()); - break; - case "edit": - $note->setText(gettext('Updated')); - $note->setEnteredBy($this->getEditedBy()); - $note->setDateEntered($this->getDateLastEdited()); - break; + switch ($type) { + case 'create': + $note->setText(gettext('Created')); + $note->setEnteredBy($this->getEnteredBy()); + $note->setDateEntered($this->getDateEntered()); + break; + case 'edit': + $note->setText(gettext('Updated')); + $note->setEnteredBy($this->getEditedBy()); + $note->setDateEntered($this->getDateLastEdited()); + break; } $note->save(); @@ -191,6 +187,7 @@ public function isUser() /** * Get address of a person. If empty, return family address. + * * @return string */ public function getAddress() @@ -199,11 +196,11 @@ public function getAddress() $address = []; $tmp = $this->getAddress1(); if (!empty($this->getAddress2())) { - $tmp = $tmp . ' ' . $this->getAddress2(); + $tmp = $tmp.' '.$this->getAddress2(); } array_push($address, $tmp); if (!empty($this->getCity())) { - array_push($address, $this->getCity() . ','); + array_push($address, $this->getCity().','); } if (!empty($this->getState())) { array_push($address, $this->getState()); @@ -214,6 +211,7 @@ public function getAddress() if (!empty($this->getCountry())) { array_push($address, $this->getCountry()); } + return implode(' ', $address); } else { if ($this->getFamily()) { @@ -221,73 +219,82 @@ public function getAddress() ->getAddress(); } } + //if it reaches here, no address found. return empty $address - return ""; + return ''; } /** * Get name of a person family. + * * @return string */ public function getFamilyName() { - if ($this->getFamily()) { - return $this->getFamily() - ->getName(); - } - //if it reaches here, no family name found. return empty family name - return ""; + if ($this->getFamily()) { + return $this->getFamily() + ->getName(); + } + + //if it reaches here, no family name found. return empty family name + return ''; } /** * Get name of a person family. + * * @return string */ public function getFamilyCountry() { - if ($this->getFamily()) { - return $this->getFamily() - ->getCountry(); - } - //if it reaches here, no country found. return empty country - return ""; + if ($this->getFamily()) { + return $this->getFamily() + ->getCountry(); + } + + //if it reaches here, no country found. return empty country + return ''; } - /** + /** * Get Phone of a person family. * 0 = Home * 1 = Work - * 2 = Cell + * 2 = Cell. + * * @return string */ public function getFamilyPhone($type) { - switch ($type) { - case 0: - if($this->getFamily()) { - return $this->getFamily() - ->getHomePhone(); - } - break; - case 1: - if($this->getFamily()) { - return $this->getFamily() - ->getWorkPhone(); - } - break; - case 2: - if($this->getFamily()) { - return $this->getFamily() - ->getCellPhone(); - } - break; - } - //if it reaches here, no phone found. return empty phone - return ""; + switch ($type) { + case 0: + if ($this->getFamily()) { + return $this->getFamily() + ->getHomePhone(); + } + break; + case 1: + if ($this->getFamily()) { + return $this->getFamily() + ->getWorkPhone(); + } + break; + case 2: + if ($this->getFamily()) { + return $this->getFamily() + ->getCellPhone(); + } + break; + } + + //if it reaches here, no phone found. return empty phone + return ''; } + /** * * If person address found, return latitude and Longitude of person address - * else return family latitude and Longitude + * else return family latitude and Longitude. + * * @return array */ public function getLatLng() @@ -302,20 +309,20 @@ public function getLatLng() $lng = $latLng['Longitude']; } } else { - // Philippe Logel : this is usefull when a person don't have a family : ie not an address - if (!empty($this->getFamily())) - { - if (!$this->getFamily()->hasLatitudeAndLongitude()) { - $this->getFamily()->updateLanLng(); - } - $lat = $this->getFamily()->getLatitude(); - $lng = $this->getFamily()->getLongitude(); - } + // Philippe Logel : this is usefull when a person don't have a family : ie not an address + if (!empty($this->getFamily())) { + if (!$this->getFamily()->hasLatitudeAndLongitude()) { + $this->getFamily()->updateLanLng(); + } + $lat = $this->getFamily()->getLatitude(); + $lng = $this->getFamily()->getLongitude(); + } } - return array( - 'Latitude' => $lat, - 'Longitude' => $lng - ); + + return [ + 'Latitude' => $lat, + 'Longitude' => $lng, + ]; } public function deletePhoto() @@ -323,40 +330,43 @@ public function deletePhoto() if (AuthenticationManager::GetCurrentUser()->isDeleteRecordsEnabled()) { if ($this->getPhoto()->delete()) { $note = new Note(); - $note->setText(gettext("Profile Image Deleted")); - $note->setType("photo"); + $note->setText(gettext('Profile Image Deleted')); + $note->setType('photo'); $note->setEntered(AuthenticationManager::GetCurrentUser()->getId()); $note->setPerId($this->getId()); $note->save(); + return true; } } + return false; } public function getPhoto() { - if (!$this->photo) - { - $this->photo = new Photo("Person", $this->getId()); - } - return $this->photo; + if (!$this->photo) { + $this->photo = new Photo('Person', $this->getId()); + } + + return $this->photo; } public function setImageFromBase64($base64) { if (AuthenticationManager::GetCurrentUser()->isEditRecordsEnabled()) { $note = new Note(); - $note->setText(gettext("Profile Image uploaded")); - $note->setType("photo"); + $note->setText(gettext('Profile Image uploaded')); + $note->setType('photo'); $note->setEntered(AuthenticationManager::GetCurrentUser()->getId()); $this->getPhoto()->setImageFromBase64($base64); $note->setPerId($this->getId()); $note->save(); + return true; } - return false; + return false; } /** @@ -369,9 +379,10 @@ public function setImageFromBase64($base64) * $Style = 5 : "Title FirstName LastName" * $Style = 6 : "LastName, Title FirstName" * $Style = 7 : "LastName FirstName" - * $Style = 8 : "LastName, FirstName Middlename" + * $Style = 8 : "LastName, FirstName Middlename". * * @param $Style + * * @return string */ public function getFormattedName($Style) @@ -380,104 +391,104 @@ public function getFormattedName($Style) switch ($Style) { case 0: if ($this->getTitle()) { - $nameString .= $this->getTitle() . ' '; + $nameString .= $this->getTitle().' '; } $nameString .= $this->getFirstName(); if ($this->getMiddleName()) { - $nameString .= ' ' . $this->getMiddleName(); + $nameString .= ' '.$this->getMiddleName(); } if ($this->getLastName()) { - $nameString .= ' ' . $this->getLastName(); + $nameString .= ' '.$this->getLastName(); } if ($this->getSuffix()) { - $nameString .= ', ' . $this->getSuffix(); + $nameString .= ', '.$this->getSuffix(); } break; case 1: if ($this->getTitle()) { - $nameString .= $this->getTitle() . ' '; + $nameString .= $this->getTitle().' '; } $nameString .= $this->getFirstName(); if ($this->getMiddleName()) { - $nameString .= ' ' . strtoupper(mb_substr($this->getMiddleName(), 0, 1, 'UTF-8')) . '.'; + $nameString .= ' '.strtoupper(mb_substr($this->getMiddleName(), 0, 1, 'UTF-8')).'.'; } if ($this->getLastName()) { - $nameString .= ' ' . $this->getLastName(); + $nameString .= ' '.$this->getLastName(); } if ($this->getSuffix()) { - $nameString .= ', ' . $this->getSuffix(); + $nameString .= ', '.$this->getSuffix(); } break; case 2: if ($this->getLastName()) { - $nameString .= $this->getLastName() . ', '; + $nameString .= $this->getLastName().', '; } if ($this->getTitle()) { - $nameString .= $this->getTitle() . ' '; + $nameString .= $this->getTitle().' '; } $nameString .= $this->getFirstName(); if ($this->getMiddleName()) { - $nameString .= ' ' . $this->getMiddleName(); + $nameString .= ' '.$this->getMiddleName(); } if ($this->getSuffix()) { - $nameString .= ', ' . $this->getSuffix(); + $nameString .= ', '.$this->getSuffix(); } break; case 3: if ($this->getLastName()) { - $nameString .= $this->getLastName() . ', '; + $nameString .= $this->getLastName().', '; } if ($this->getTitle()) { - $nameString .= $this->getTitle() . ' '; + $nameString .= $this->getTitle().' '; } $nameString .= $this->getFirstName(); if ($this->getMiddleName()) { - $nameString .= ' ' . strtoupper(mb_substr($this->getMiddleName(), 0, 1, 'UTF-8')) . '.'; + $nameString .= ' '.strtoupper(mb_substr($this->getMiddleName(), 0, 1, 'UTF-8')).'.'; } if ($this->getSuffix()) { - $nameString .= ', ' . $this->getSuffix(); + $nameString .= ', '.$this->getSuffix(); } break; case 4: $nameString .= $this->getFirstName(); if ($this->getMiddleName()) { - $nameString .= ' ' . $this->getMiddleName(); + $nameString .= ' '.$this->getMiddleName(); } if ($this->getLastName()) { - $nameString .= ' ' . $this->getLastName(); + $nameString .= ' '.$this->getLastName(); } break; case 5: if ($this->getTitle()) { - $nameString .= $this->getTitle() . ' '; + $nameString .= $this->getTitle().' '; } $nameString .= $this->getFirstName(); if ($this->getLastName()) { - $nameString .= ' ' . $this->getLastName(); + $nameString .= ' '.$this->getLastName(); } break; case 6: if ($this->getLastName()) { - $nameString .= $this->getLastName() . ', '; + $nameString .= $this->getLastName().', '; } if ($this->getTitle()) { - $nameString .= $this->getTitle() . ' '; + $nameString .= $this->getTitle().' '; } $nameString .= $this->getFirstName(); break; case 7: if ($this->getLastName()) { - $nameString .= $this->getLastName() . ' '; + $nameString .= $this->getLastName().' '; } - if ($this->getFirstName() ){ + if ($this->getFirstName()) { $nameString .= $this->getFirstName(); } else { $nameString = trim($nameString); @@ -489,21 +500,20 @@ public function getFormattedName($Style) $nameString .= $this->getLastName(); } if ($this->getFirstName()) { - if (!$nameString) { // no first name - $nameString = $this->getFirstName(); - } else { - $nameString .= ', ' . $this->getFirstName(); - } - + if (!$nameString) { // no first name + $nameString = $this->getFirstName(); + } else { + $nameString .= ', '.$this->getFirstName(); + } } if ($this->getMiddleName()) { - $nameString .= ' ' . $this->getMiddleName(); + $nameString .= ' '.$this->getMiddleName(); } break; default: $nameString = trim($this->getFullName()); - } + return $nameString; } @@ -532,7 +542,7 @@ public function preDelete(ConnectionInterface $con = null) PersonVolunteerOpportunityQuery::create()->filterByPersonId($this->getId())->delete($con); PropertyQuery::create() - ->filterByProClass("p") + ->filterByProClass('p') ->useRecordPropertyQuery() ->filterByRecordId($this->getId()) ->delete($con); @@ -542,149 +552,162 @@ public function preDelete(ConnectionInterface $con = null) return parent::preDelete($con); } - public function getProperties() { - $personProperties = PropertyQuery::create() - ->filterByProClass("p") - ->useRecordPropertyQuery() - ->filterByRecordId($this->getId()) - ->find(); - return $personProperties; + public function getProperties() + { + $personProperties = PropertyQuery::create() + ->filterByProClass('p') + ->useRecordPropertyQuery() + ->filterByRecordId($this->getId()) + ->find(); + + return $personProperties; } // return array of person properties // created for the person-list.php datatable - public function getPropertiesString() { - $personProperties = PropertyQuery::create() - ->filterByProClass("p") - ->leftJoinRecordProperty() - ->where('r2p_record_ID='.$this->getId()) - ->find(); + public function getPropertiesString() + { + $personProperties = PropertyQuery::create() + ->filterByProClass('p') + ->leftJoinRecordProperty() + ->where('r2p_record_ID='.$this->getId()) + ->find(); + + $PropertiesList = []; + foreach ($personProperties as $element) { + $PropertiesList[] = $element->getProName(); + } - $PropertiesList = []; - foreach($personProperties as $element) { - $PropertiesList[] = $element->getProName(); - } - return $PropertiesList; + return $PropertiesList; } // return array of person custom fields // created for the person-list.php datatable - public function getCustomFields() { - // get list of custom field column names - $allPersonCustomFields = PersonCustomMasterQuery::create()->find(); - - // add custom fields to person_custom table since they are not defined in the propel schema - $rawQry = PersonCustomQuery::create(); - foreach ($allPersonCustomFields as $customfield ) { - if (AuthenticationManager::GetCurrentUser()->isEnabledSecurity($customfield->getFieldSecurity())) { - $rawQry->withColumn($customfield->getId()); - } - } - $thisPersonCustomFields = $rawQry->findOneByPerId($this->getId()); - - // get custom column names and values - $personCustom = []; - if ($rawQry->count() > 0) { - foreach ($allPersonCustomFields as $customfield ) { + public function getCustomFields() + { + // get list of custom field column names + $allPersonCustomFields = PersonCustomMasterQuery::create()->find(); + + // add custom fields to person_custom table since they are not defined in the propel schema + $rawQry = PersonCustomQuery::create(); + foreach ($allPersonCustomFields as $customfield) { if (AuthenticationManager::GetCurrentUser()->isEnabledSecurity($customfield->getFieldSecurity())) { - $value = $thisPersonCustomFields->getVirtualColumn($customfield->getId()); - if (!empty($value)) { - $personCustom[] = $customfield->getName(); + $rawQry->withColumn($customfield->getId()); + } + } + $thisPersonCustomFields = $rawQry->findOneByPerId($this->getId()); + + // get custom column names and values + $personCustom = []; + if ($rawQry->count() > 0) { + foreach ($allPersonCustomFields as $customfield) { + if (AuthenticationManager::GetCurrentUser()->isEnabledSecurity($customfield->getFieldSecurity())) { + $value = $thisPersonCustomFields->getVirtualColumn($customfield->getId()); + if (!empty($value)) { + $personCustom[] = $customfield->getName(); + } } } } - } - return $personCustom; + + return $personCustom; } + // return array of person groups // created for the person-list.php datatable - public function getGroups() { - $GroupList = GroupQuery::create() - ->leftJoinPerson2group2roleP2g2r() - ->where('p2g2r_per_ID='.$this->getId()) - ->find(); + public function getGroups() + { + $GroupList = GroupQuery::create() + ->leftJoinPerson2group2roleP2g2r() + ->where('p2g2r_per_ID='.$this->getId()) + ->find(); + + $group = []; + foreach ($GroupList as $element) { + $group[] = $element->getName(); + } - $group = []; - foreach($GroupList as $element) { - $group[] = $element->getName(); - } - return $group; + return $group; } public function getNumericCellPhone() { - return "1".preg_replace('/[^\.0-9]/',"",$this->getCellPhone()); + return '1'.preg_replace('/[^\.0-9]/', '', $this->getCellPhone()); } - public function postSave(ConnectionInterface $con = null) { - $this->getPhoto()->refresh(); - return parent::postSave($con); + public function postSave(ConnectionInterface $con = null) + { + $this->getPhoto()->refresh(); + + return parent::postSave($con); } public function getAge($now = null) { - $birthDate = $this->getBirthDate(); + $birthDate = $this->getBirthDate(); - if ($this->hideAge()) - { - return false; - } - if (empty($now)) { - $now = date_create('today'); - } - $age = date_diff($now,$birthDate); + if ($this->hideAge()) { + return false; + } + if (empty($now)) { + $now = date_create('today'); + } + $age = date_diff($now, $birthDate); - if ($age->y < 1) - return sprintf(ngettext('%d month old', '%d months old', $age->m), $age->m); + if ($age->y < 1) { + return sprintf(ngettext('%d month old', '%d months old', $age->m), $age->m); + } - return sprintf(ngettext('%d year old', '%d years old', $age->y), $age->y); + return sprintf(ngettext('%d year old', '%d years old', $age->y), $age->y); } - public function getNumericAge() { - $birthDate = $this->getBirthDate(); - if ($this->hideAge()) - { - return false; - } - if (empty($now)) { - $now = date_create('today'); - } - $age = date_diff($now,$birthDate); - if ($age->y < 1) { - $ageValue = 0; - } else { - $ageValue = $age->y; - } - return $ageValue; + public function getNumericAge() + { + $birthDate = $this->getBirthDate(); + if ($this->hideAge()) { + return false; + } + if (empty($now)) { + $now = date_create('today'); + } + $age = date_diff($now, $birthDate); + if ($age->y < 1) { + $ageValue = 0; + } else { + $ageValue = $age->y; + } + + return $ageValue; } /* Philippe Logel 2017 */ public function getFullNameWithAge() { - return $this->getFullName()." ".$this->getAge(); + return $this->getFullName().' '.$this->getAge(); } - public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = [], $includeForeignObjects = false) { $array = parent::toArray(); - $array['Address']=$this->getAddress(); + $array['Address'] = $this->getAddress(); + return $array; } - public function getThumbnailURL() { - return SystemURLs::getRootPath() . '/api/person/' . $this->getId() . '/thumbnail'; + public function getThumbnailURL() + { + return SystemURLs::getRootPath().'/api/person/'.$this->getId().'/thumbnail'; } - public function getEmail() { - if (parent::getEmail() == null) - { - $family = $this->getFamily(); - if ($family != null) - { - return $family->getEmail(); + public function getEmail() + { + if (parent::getEmail() == null) { + $family = $this->getFamily(); + if ($family != null) { + return $family->getEmail(); + } } - } - return parent::getEmail(); - } + return parent::getEmail(); + } } diff --git a/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunity.php b/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunity.php index 49e6ea8a81..766b18527a 100644 --- a/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunity.php +++ b/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunity.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class PersonVolunteerOpportunity extends BasePersonVolunteerOpportunity { - } diff --git a/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunityQuery.php b/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunityQuery.php index ebb26af6a8..36f8d90869 100644 --- a/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunityQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunityQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class PersonVolunteerOpportunityQuery extends BasePersonVolunteerOpportunityQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/Pledge.php b/src/ChurchCRM/model/ChurchCRM/Pledge.php index 5ff0d2c052..a70d05af65 100644 --- a/src/ChurchCRM/model/ChurchCRM/Pledge.php +++ b/src/ChurchCRM/model/ChurchCRM/Pledge.php @@ -17,14 +17,17 @@ */ class Pledge extends BasePledge { - public function getFormattedFY() { + public function getFormattedFY() + { return MakeFYString($this->getFyId()); } - /** - * Code to be run before deleting the object in database - * @param ConnectionInterface $con - * @return boolean + /** + * Code to be run before deleting the object in database. + * + * @param ConnectionInterface $con + * + * @return bool */ public function preDelete(ConnectionInterface $con = null) { @@ -36,20 +39,19 @@ public function preDelete(ConnectionInterface $con = null) } } - public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = [], $includeForeignObjects = false) { - $array = parent::toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, $includeForeignObjects); - $family = $this->getFamily(); + $array = parent::toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, $includeForeignObjects); + $family = $this->getFamily(); - if($family) - { - // This must be done in the Pledge object model instead of during a query with Propel's ->WithColumn() syntax - // because the getFamilyString logic is implemented in PHP, not SQL, and the consumer of this object - // expects to see the fully-formatted family string (name, address, state) instead of only family name. - // i.e. commit 33b40c973685b7f03cfb3e79241fe53594b83f04 does it incorrectly. - $array['FamilyString']=$family->getFamilyString(); - } + if ($family) { + // This must be done in the Pledge object model instead of during a query with Propel's ->WithColumn() syntax + // because the getFamilyString logic is implemented in PHP, not SQL, and the consumer of this object + // expects to see the fully-formatted family string (name, address, state) instead of only family name. + // i.e. commit 33b40c973685b7f03cfb3e79241fe53594b83f04 does it incorrectly. + $array['FamilyString'] = $family->getFamilyString(); + } - return $array; + return $array; } } diff --git a/src/ChurchCRM/model/ChurchCRM/PredefinedReports.php b/src/ChurchCRM/model/ChurchCRM/PredefinedReports.php index 34c0b7c700..86a1f2bfcb 100644 --- a/src/ChurchCRM/model/ChurchCRM/PredefinedReports.php +++ b/src/ChurchCRM/model/ChurchCRM/PredefinedReports.php @@ -15,5 +15,4 @@ */ class PredefinedReports extends BasePredefinedReports { - } diff --git a/src/ChurchCRM/model/ChurchCRM/PredefinedReportsQuery.php b/src/ChurchCRM/model/ChurchCRM/PredefinedReportsQuery.php index 52338d5133..90af1ad217 100644 --- a/src/ChurchCRM/model/ChurchCRM/PredefinedReportsQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/PredefinedReportsQuery.php @@ -15,5 +15,4 @@ */ class PredefinedReportsQuery extends BasePredefinedReportsQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/Property.php b/src/ChurchCRM/model/ChurchCRM/Property.php index c638df4f42..8208299eeb 100644 --- a/src/ChurchCRM/model/ChurchCRM/Property.php +++ b/src/ChurchCRM/model/ChurchCRM/Property.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class Property extends BaseProperty { - } diff --git a/src/ChurchCRM/model/ChurchCRM/PropertyQuery.php b/src/ChurchCRM/model/ChurchCRM/PropertyQuery.php index fb09c2d9ed..f00c0d04a4 100644 --- a/src/ChurchCRM/model/ChurchCRM/PropertyQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/PropertyQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class PropertyQuery extends BasePropertyQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/PropertyType.php b/src/ChurchCRM/model/ChurchCRM/PropertyType.php index ed3f15a7ec..16e0f06bb0 100644 --- a/src/ChurchCRM/model/ChurchCRM/PropertyType.php +++ b/src/ChurchCRM/model/ChurchCRM/PropertyType.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class PropertyType extends BasePropertyType { - } diff --git a/src/ChurchCRM/model/ChurchCRM/PropertyTypeQuery.php b/src/ChurchCRM/model/ChurchCRM/PropertyTypeQuery.php index 7e55601f26..4320620c46 100644 --- a/src/ChurchCRM/model/ChurchCRM/PropertyTypeQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/PropertyTypeQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class PropertyTypeQuery extends BasePropertyTypeQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/QueryParameterOptions.php b/src/ChurchCRM/model/ChurchCRM/QueryParameterOptions.php index 7ba0727f4d..e5d7f03cac 100644 --- a/src/ChurchCRM/model/ChurchCRM/QueryParameterOptions.php +++ b/src/ChurchCRM/model/ChurchCRM/QueryParameterOptions.php @@ -15,5 +15,4 @@ */ class QueryParameterOptions extends BaseQueryParameterOptions { - } diff --git a/src/ChurchCRM/model/ChurchCRM/QueryParameterOptionsQuery.php b/src/ChurchCRM/model/ChurchCRM/QueryParameterOptionsQuery.php index 19b10725a9..d9240c4a58 100644 --- a/src/ChurchCRM/model/ChurchCRM/QueryParameterOptionsQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/QueryParameterOptionsQuery.php @@ -15,5 +15,4 @@ */ class QueryParameterOptionsQuery extends BaseQueryParameterOptionsQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/RecordProperty.php b/src/ChurchCRM/model/ChurchCRM/RecordProperty.php index c4cd0dd9cf..2612be8f1b 100644 --- a/src/ChurchCRM/model/ChurchCRM/RecordProperty.php +++ b/src/ChurchCRM/model/ChurchCRM/RecordProperty.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class RecordProperty extends BaseRecordProperty { - } diff --git a/src/ChurchCRM/model/ChurchCRM/RecordPropertyQuery.php b/src/ChurchCRM/model/ChurchCRM/RecordPropertyQuery.php index b64ff5941a..38fdda99de 100644 --- a/src/ChurchCRM/model/ChurchCRM/RecordPropertyQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/RecordPropertyQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class RecordPropertyQuery extends BaseRecordPropertyQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/Token.php b/src/ChurchCRM/model/ChurchCRM/Token.php index 5b1310bda0..d7e53606a3 100644 --- a/src/ChurchCRM/model/ChurchCRM/Token.php +++ b/src/ChurchCRM/model/ChurchCRM/Token.php @@ -12,32 +12,29 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class Token extends BaseToken { - - const typeFamilyVerify = "verifyFamily"; - const typePassword = "password"; + const typeFamilyVerify = 'verifyFamily'; + const typePassword = 'password'; public function build($type, $referenceId) { $this->setReferenceId($referenceId); $this->setToken(uniqid()); switch ($type) { - case "verifyFamily": - $this->setValidUntilDate(strtotime("+1 week")); + case 'verifyFamily': + $this->setValidUntilDate(strtotime('+1 week')); $this->setRemainingUses(5); break; - case "password": - $this->setValidUntilDate(strtotime("+1 day")); + case 'password': + $this->setValidUntilDate(strtotime('+1 day')); $this->setRemainingUses(1); break; } $this->setType($type); } - public function isVerifyFamilyToken() { return self::typeFamilyVerify === $this->getType(); @@ -60,7 +57,7 @@ public function isValid() $today = new \DateTime(); $stillValidDate = $this->getValidUntilDate() > $today; } + return $stillValidDate && $hasUses; } - } diff --git a/src/ChurchCRM/model/ChurchCRM/TokenQuery.php b/src/ChurchCRM/model/ChurchCRM/TokenQuery.php index 1a2a9e9636..4d6723729f 100644 --- a/src/ChurchCRM/model/ChurchCRM/TokenQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/TokenQuery.php @@ -12,9 +12,7 @@ * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. - * */ class TokenQuery extends BaseTokenQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/User.php b/src/ChurchCRM/model/ChurchCRM/User.php index 28696d8364..e1f7677f77 100644 --- a/src/ChurchCRM/model/ChurchCRM/User.php +++ b/src/ChurchCRM/model/ChurchCRM/User.php @@ -22,8 +22,6 @@ */ class User extends BaseUser { - - private $provisional2FAKey; public function getId() @@ -73,9 +71,10 @@ public function isManageGroupsEnabled() public function isFinanceEnabled() { - if (SystemConfig::getBooleanValue("bEnabledFinance")) { + if (SystemConfig::getBooleanValue('bEnabledFinance')) { return $this->isAdmin() || $this->isFinance(); } + return false; } @@ -106,7 +105,7 @@ public function isPasswordValid($password) public function hashPassword($password) { - return hash('sha256', $password . $this->getPersonId()); + return hash('sha256', $password.$this->getPersonId()); } public function isAddEventEnabled() // TODO: Create permission to manag event deletion see https://github.com/ChurchCRM/CRM/issues/4726 @@ -144,29 +143,31 @@ public function isbUSAddressVerificationEnabled() return $this->isAdmin() || $this->isEnabledSecurity('bUSAddressVerification'); } - public function isLocked() { return SystemConfig::getValue('iMaxFailedLogins') > 0 && $this->getFailedLogins() >= SystemConfig::getValue('iMaxFailedLogins'); } - public function resetPasswordToRandom() { + public function resetPasswordToRandom() + { $password = User::randomPassword(); $this->updatePassword($password); $this->setNeedPasswordChange(true); $this->setFailedLogins(0); + return $password; } public static function randomPassword() { $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; - $pass = array(); //remember to declare $pass as an array + $pass = []; //remember to declare $pass as an array $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache for ($i = 0; $i < SystemConfig::getValue('iMinPasswordLength'); $i++) { $n = rand(0, $alphaLength); $pass[] = $alphabet[$n]; } + return implode($pass); //turn the array into a string } @@ -177,12 +178,12 @@ public static function randomApiKey() public function postInsert(ConnectionInterface $con = null) { - $this->createTimeLineNote("created"); + $this->createTimeLineNote('created'); } public function postDelete(ConnectionInterface $con = null) { - $this->createTimeLineNote("deleted"); + $this->createTimeLineNote('deleted'); } public function createTimeLineNote($type) @@ -193,25 +194,25 @@ public function createTimeLineNote($type) $note->setType('user'); switch ($type) { - case "created": + case 'created': $note->setText(gettext('system user created')); break; - case "updated": + case 'updated': $note->setText(gettext('system user updated')); break; - case "deleted": + case 'deleted': $note->setText(gettext('system user deleted')); break; - case "password-reset": + case 'password-reset': $note->setText(gettext('system user password reset')); break; - case "password-changed": + case 'password-changed': $note->setText(gettext('system user changed password')); break; - case "password-changed-admin": + case 'password-changed-admin': $note->setText(gettext('system user password changed by admin')); break; - case "login-reset": + case 'login-reset': $note->setText(gettext('system user login reset')); break; } @@ -219,63 +220,66 @@ public function createTimeLineNote($type) $note->save(); } - public function isEnabledSecurity($securityConfigName) { + public function isEnabledSecurity($securityConfigName) + { if ($this->isAdmin()) { return true; - } else if ($securityConfigName == "bAdmin") { + } elseif ($securityConfigName == 'bAdmin') { return false; } - if ($securityConfigName == "bAll") { + if ($securityConfigName == 'bAll') { return true; } - - if ($securityConfigName == "bAddRecords" && $this->isAddRecordsEnabled()) { + if ($securityConfigName == 'bAddRecords' && $this->isAddRecordsEnabled()) { return true; } - if ($securityConfigName == "bEditRecords" && $this->isEditRecordsEnabled()) { + if ($securityConfigName == 'bEditRecords' && $this->isEditRecordsEnabled()) { return true; } - if ($securityConfigName == "bDeleteRecords" && $this->isDeleteRecordsEnabled()) { + if ($securityConfigName == 'bDeleteRecords' && $this->isDeleteRecordsEnabled()) { return true; } - if ($securityConfigName == "bManageGroups" && $this->isManageGroupsEnabled()) { + if ($securityConfigName == 'bManageGroups' && $this->isManageGroupsEnabled()) { return true; } - if ($securityConfigName == "bFinance" && $this->isFinanceEnabled()) { + if ($securityConfigName == 'bFinance' && $this->isFinanceEnabled()) { return true; } - if ($securityConfigName == "bNotes" && $this->isNotesEnabled()) { + if ($securityConfigName == 'bNotes' && $this->isNotesEnabled()) { return true; } - if ($securityConfigName == "bCanvasser" && $this->isCanvasserEnabled()) { + if ($securityConfigName == 'bCanvasser' && $this->isCanvasserEnabled()) { return true; } foreach ($this->getUserConfigs() as $userConfig) { if ($userConfig->getName() == $securityConfigName) { - return $userConfig->getPermission() == "TRUE"; + return $userConfig->getPermission() == 'TRUE'; } } + return false; } - public function getUserConfigString($userConfigName) { - foreach ($this->getUserConfigs() as $userConfig) { - if ($userConfig->getName() == $userConfigName) { - return $userConfig->getValue(); + public function getUserConfigString($userConfigName) + { + foreach ($this->getUserConfigs() as $userConfig) { + if ($userConfig->getName() == $userConfigName) { + return $userConfig->getValue(); + } } - } } - public function setUserConfigString($userConfigName, $value) { + public function setUserConfigString($userConfigName, $value) + { foreach ($this->getUserConfigs() as $userConfig) { if ($userConfig->getName() == $userConfigName) { return $userConfig->setValue($value); @@ -283,8 +287,8 @@ public function setUserConfigString($userConfigName, $value) { } } - - public function setSetting($name, $value) { + public function setSetting($name, $value) + { $setting = $this->getSetting($name); if (!$setting) { $setting = new UserSetting(); @@ -295,42 +299,52 @@ public function setSetting($name, $value) { $setting->save(); } - public function getSettingValue($name) { + public function getSettingValue($name) + { $userSetting = $this->getSetting($name); - return (is_null($userSetting) ? "" : $userSetting->getValue()); + + return is_null($userSetting) ? '' : $userSetting->getValue(); } - public function getSetting($name) { + public function getSetting($name) + { foreach ($this->getUserSettings() as $userSetting) { if ($userSetting->getName() == $name) { return $userSetting; } } + return null; } - public function getStyle(){ - $skin = is_null($this->getSetting(UserSetting::UI_STYLE)) ? "skin-red" : $this->getSetting(UserSetting::UI_STYLE); + public function getStyle() + { + $skin = is_null($this->getSetting(UserSetting::UI_STYLE)) ? 'skin-red' : $this->getSetting(UserSetting::UI_STYLE); $cssClasses = []; array_push($cssClasses, $skin); array_push($cssClasses, $this->getSetting(UserSetting::UI_BOXED)); array_push($cssClasses, $this->getSetting(UserSetting::UI_SIDEBAR)); - return implode(" ", $cssClasses); + + return implode(' ', $cssClasses); } - public function isShowPledges() { - return $this->getSettingValue(UserSetting::FINANCE_SHOW_PLEDGES) == "true"; + public function isShowPledges() + { + return $this->getSettingValue(UserSetting::FINANCE_SHOW_PLEDGES) == 'true'; } - public function isShowPayments() { - return $this->getSettingValue(UserSetting::FINANCE_SHOW_PAYMENTS) == "true"; + public function isShowPayments() + { + return $this->getSettingValue(UserSetting::FINANCE_SHOW_PAYMENTS) == 'true'; } - public function getShowSince() { + public function getShowSince() + { return $this->getSettingValue(UserSetting::FINANCE_SHOW_SINCE); } - public function provisionNew2FAKey() { + public function provisionNew2FAKey() + { $google2fa = new Google2FA(); $key = $google2fa->generateSecretKey(); // store the temporary 2FA key in a private variable on this User object @@ -339,10 +353,12 @@ public function provisionNew2FAKey() { // encrypt the 2FA key since this object and its properties are serialized into the $_SESSION store // which is generally written to disk. $this->provisional2FAKey = Crypto::encryptWithPassword($key, KeyManager::GetTwoFASecretKey()); + return $key; } - public function confirmProvisional2FACode($twoFACode) { + public function confirmProvisional2FACode($twoFACode) + { $google2fa = new Google2FA(); $window = 2; //TODO: make this a system config $pw = Crypto::decryptWithPassword($this->provisional2FAKey, KeyManager::GetTwoFASecretKey()); @@ -350,70 +366,83 @@ public function confirmProvisional2FACode($twoFACode) { if ($isKeyValid) { $this->setTwoFactorAuthSecret($this->provisional2FAKey); $this->save(); + return true; } - return $isKeyValid; + return $isKeyValid; } - public function remove2FAKey() { + public function remove2FAKey() + { $this->setTwoFactorAuthSecret(null); $this->save(); } - public function getDecryptedTwoFactorAuthSecret() { + public function getDecryptedTwoFactorAuthSecret() + { return Crypto::decryptWithPassword($this->getTwoFactorAuthSecret(), KeyManager::GetTwoFASecretKey()); } - private function getDecryptedTwoFactorAuthRecoveryCodes() { - return explode(",",Crypto::decryptWithPassword($this->getTwoFactorAuthRecoveryCodes(), KeyManager::GetTwoFASecretKey())); + private function getDecryptedTwoFactorAuthRecoveryCodes() + { + return explode(',', Crypto::decryptWithPassword($this->getTwoFactorAuthRecoveryCodes(), KeyManager::GetTwoFASecretKey())); } - public function disableTwoFactorAuthentication() { + public function disableTwoFactorAuthentication() + { $this->setTwoFactorAuthRecoveryCodes(null); $this->setTwoFactorAuthSecret(null); $this->save(); } - public function is2FactorAuthEnabled() { + public function is2FactorAuthEnabled() + { return !empty($this->getTwoFactorAuthSecret()); } - public function getNewTwoFARecoveryCodes() { + public function getNewTwoFARecoveryCodes() + { // generate an array of 2FA recovery codes, and store as an encrypted, comma-separated list - $recoveryCodes = array(); - for($i=0; $i < 12; $i++) { + $recoveryCodes = []; + for ($i = 0; $i < 12; $i++) { $recoveryCodes[$i] = base64_encode(random_bytes(10)); } - $recoveryCodesString = implode(",",$recoveryCodes); + $recoveryCodesString = implode(',', $recoveryCodes); $this->setTwoFactorAuthRecoveryCodes(Crypto::encryptWithPassword($recoveryCodesString, KeyManager::GetTwoFASecretKey())); $this->save(); + return $recoveryCodes; } - public function isTwoFACodeValid($twoFACode) { + public function isTwoFACodeValid($twoFACode) + { $google2fa = new Google2FA(); $window = 2; //TODO: make this a system config $timestamp = $google2fa->verifyKeyNewer($this->getDecryptedTwoFactorAuthSecret(), $twoFACode, $this->getTwoFactorAuthLastKeyTimestamp(), $window); if ($timestamp !== false) { $this->setTwoFactorAuthLastKeyTimestamp($timestamp); $this->save(); + return true; } else { return false; } } - public function isTwoFaRecoveryCodeValid($twoFaRecoveryCode) { + public function isTwoFaRecoveryCodeValid($twoFaRecoveryCode) + { // checks for validity of a 2FA recovery code // if the specified code was valid, the code is also removed. $codes = $this->getDecryptedTwoFactorAuthRecoveryCodes(); if (($key = array_search($twoFaRecoveryCode, $codes)) !== false) { unset($codes[$key]); - $recoveryCodesString = implode(",",$codes); + $recoveryCodesString = implode(',', $codes); $this->setTwoFactorAuthRecoveryCodes(Crypto::encryptWithPassword($recoveryCodesString, KeyManager::GetTwoFASecretKey())); + return true; } + return false; } @@ -422,43 +451,46 @@ public function adminSetUserPassword($newPassword) $this->updatePassword($newPassword); $this->setNeedPasswordChange(false); $this->save(); - $this->createTimeLineNote("password-changed-admin"); - return; + $this->createTimeLineNote('password-changed-admin'); + } public function userChangePassword($oldPassword, $newPassword) { if (!$this->isPasswordValid($oldPassword)) { - throw new PasswordChangeException("Old", gettext('Incorrect password supplied for current user')); + throw new PasswordChangeException('Old', gettext('Incorrect password supplied for current user')); } if (!$this->GetIsPasswordPermissible($newPassword)) { - throw new PasswordChangeException("New", gettext('Your password choice is too obvious. Please choose something else.')); + throw new PasswordChangeException('New', gettext('Your password choice is too obvious. Please choose something else.')); } if (strlen($newPassword) < SystemConfig::getValue('iMinPasswordLength')) { - throw new PasswordChangeException("New", gettext('Your new password must be at least') . ' ' . SystemConfig::getValue('iMinPasswordLength') . ' ' . gettext('characters')); + throw new PasswordChangeException('New', gettext('Your new password must be at least').' '.SystemConfig::getValue('iMinPasswordLength').' '.gettext('characters')); } if ($newPassword == $oldPassword) { - throw new PasswordChangeException("New", gettext('Your new password must not match your old one.')); + throw new PasswordChangeException('New', gettext('Your new password must not match your old one.')); } if (levenshtein(strtolower($newPassword), strtolower($oldPassword)) < SystemConfig::getValue('iMinPasswordChange')) { - throw new PasswordChangeException("New", gettext('Your new password is too similar to your old one.')); + throw new PasswordChangeException('New', gettext('Your new password is too similar to your old one.')); } $this->updatePassword($newPassword); $this->setNeedPasswordChange(false); $this->save(); - $this->createTimeLineNote("password-changed"); - return; + $this->createTimeLineNote('password-changed'); + } - private function GetIsPasswordPermissible($newPassword) { + + private function GetIsPasswordPermissible($newPassword) + { $aBadPasswords = explode(',', strtolower(SystemConfig::getValue('aDisallowedPasswords'))); $aBadPasswords[] = strtolower($this->getPerson()->getFirstName()); $aBadPasswords[] = strtolower($this->getPerson()->getMiddleName()); $aBadPasswords[] = strtolower($this->getPerson()->getLastName()); - return ! in_array(strtolower($newPassword), $aBadPasswords); - } + + return !in_array(strtolower($newPassword), $aBadPasswords); + } } diff --git a/src/ChurchCRM/model/ChurchCRM/UserQueryQuery.php b/src/ChurchCRM/model/ChurchCRM/UserQueryQuery.php index 58e97c8ea4..64d4be6b66 100644 --- a/src/ChurchCRM/model/ChurchCRM/UserQueryQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/UserQueryQuery.php @@ -15,5 +15,4 @@ */ class UserQueryQuery extends BaseUserQueryQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/UserSetting.php b/src/ChurchCRM/model/ChurchCRM/UserSetting.php index e865168177..1cebd7e82a 100644 --- a/src/ChurchCRM/model/ChurchCRM/UserSetting.php +++ b/src/ChurchCRM/model/ChurchCRM/UserSetting.php @@ -15,14 +15,13 @@ */ class UserSetting extends BaseUserSetting { + public const UI_STYLE = 'ui.style'; + public const UI_BOXED = 'ui.boxed'; + public const UI_SIDEBAR = 'ui.sidebar'; - public const UI_STYLE = "ui.style"; - public const UI_BOXED = "ui.boxed"; - public const UI_SIDEBAR = "ui.sidebar"; - - public const FINANCE_SHOW_PAYMENTS = "finance.show.payments"; - public const FINANCE_SHOW_PLEDGES = "finance.show.pledges"; - public const FINANCE_SHOW_SINCE = "finance.show.since"; + public const FINANCE_SHOW_PAYMENTS = 'finance.show.payments'; + public const FINANCE_SHOW_PLEDGES = 'finance.show.pledges'; + public const FINANCE_SHOW_SINCE = 'finance.show.since'; public function set($user, $name, $value) { diff --git a/src/ChurchCRM/model/ChurchCRM/UserSettingQuery.php b/src/ChurchCRM/model/ChurchCRM/UserSettingQuery.php index d5139e07c4..5b0b086d66 100644 --- a/src/ChurchCRM/model/ChurchCRM/UserSettingQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/UserSettingQuery.php @@ -15,5 +15,4 @@ */ class UserSettingQuery extends BaseUserSettingQuery { - } diff --git a/src/ChurchCRM/model/ChurchCRM/Version.php b/src/ChurchCRM/model/ChurchCRM/Version.php index 50533e6aa9..6c7f65b29c 100644 --- a/src/ChurchCRM/model/ChurchCRM/Version.php +++ b/src/ChurchCRM/model/ChurchCRM/Version.php @@ -18,26 +18,26 @@ class Version extends BaseVersion public function preSave(\Propel\Runtime\Connection\ConnectionInterface $con = null) { //before we try to save this version object to the database, ensure that - //the database has the correct columns to accomedate the version data + //the database has the correct columns to accomedate the version data - $query = 'DESCRIBE version_ver'; + $query = 'DESCRIBE version_ver'; $statement = $con->prepare($query); $resultset = $statement->execute(); $results = $statement->fetchAll(\PDO::FETCH_ASSOC); if (!ArrayUtils::in_array_recursive('ver_update_start', $results)) { //the versions table does not contain the ver_update_start column. - $query = 'ALTER TABLE version_ver CHANGE COLUMN ver_date ver_update_start datetime default NULL;'; + $query = 'ALTER TABLE version_ver CHANGE COLUMN ver_date ver_update_start datetime default NULL;'; $statement = $con->prepare($query); $resultset = $statement->execute(); } if (!ArrayUtils::in_array_recursive('ver_update_start', $results)) { //the versions table does not contain the ver_update_end column. - $query = 'ALTER TABLE version_ver ADD COLUMN ver_update_end datetime default NULL AFTER ver_update_start;'; + $query = 'ALTER TABLE version_ver ADD COLUMN ver_update_end datetime default NULL AFTER ver_update_start;'; $statement = $con->prepare($query); $resultset = $statement->execute(); } - //then save this version + //then save this version - return true; + return true; } } diff --git a/src/ChurchCRM/tasks/CheckExecutionTimeTask.php b/src/ChurchCRM/tasks/CheckExecutionTimeTask.php index de5a16bb0b..de6d6ac0b2 100644 --- a/src/ChurchCRM/tasks/CheckExecutionTimeTask.php +++ b/src/ChurchCRM/tasks/CheckExecutionTimeTask.php @@ -1,6 +1,5 @@ executionTime . ")"; + return gettext('PHP Max Execution Time is too Short').' ('.$this->executionTime.')'; } public function getDesc() { - return gettext("Increase the PHP execution time limit to allow for backup and restore."); + return gettext('Increase the PHP execution time limit to allow for backup and restore.'); } - } diff --git a/src/ChurchCRM/tasks/CheckUploadSizeTask.php b/src/ChurchCRM/tasks/CheckUploadSizeTask.php index aa48087560..0962c3b947 100644 --- a/src/ChurchCRM/tasks/CheckUploadSizeTask.php +++ b/src/ChurchCRM/tasks/CheckUploadSizeTask.php @@ -1,6 +1,5 @@ sizeString = ini_get('upload_max_filesize'); - $this->sizeBytes = Self::return_bytes($this->sizeString); + $this->sizeBytes = self::return_bytes($this->sizeString); } public function isActive() { - return $this->sizeBytes < Self::return_bytes('5M'); + return $this->sizeBytes < self::return_bytes('5M'); } public function isAdmin() @@ -33,15 +32,15 @@ public function getLink() public function getTitle() { - return gettext('PHP Max File size too small') . " (" . $this->sizeString . ")"; + return gettext('PHP Max File size too small').' ('.$this->sizeString.')'; } public function getDesc() { - return gettext("Increase the php upload limits to allow for mobile photo upload, and backup restore."); + return gettext('Increase the php upload limits to allow for mobile photo upload, and backup restore.'); } - static function return_bytes($val) + public static function return_bytes($val) { $val = trim($val); $last = strtolower($val[strlen($val) - 1]); @@ -54,6 +53,7 @@ static function return_bytes($val) case 'k': $val *= 1024; } + return $val; } } diff --git a/src/ChurchCRM/tasks/ChurchAddress.php b/src/ChurchCRM/tasks/ChurchAddress.php index 9848986a36..7e00677d74 100644 --- a/src/ChurchCRM/tasks/ChurchAddress.php +++ b/src/ChurchCRM/tasks/ChurchAddress.php @@ -1,26 +1,35 @@ isAdmin() && empty(SystemConfig::getValue('sChurchAddress')); - } - public function isAdmin(){ - return true; - } - public function getLink(){ - return SystemURLs::getRootPath() . '/SystemSettings.php'; - } - public function getTitle(){ - return gettext('Set Church Address'); - } - public function getDesc(){ - return gettext("Church Address is not Set."); - } + public function isActive() + { + return AuthenticationManager::GetCurrentUser()->isAdmin() && empty(SystemConfig::getValue('sChurchAddress')); + } + + public function isAdmin() + { + return true; + } + + public function getLink() + { + return SystemURLs::getRootPath().'/SystemSettings.php'; + } + + public function getTitle() + { + return gettext('Set Church Address'); + } + public function getDesc() + { + return gettext('Church Address is not Set.'); + } } diff --git a/src/ChurchCRM/tasks/ChurchNameTask.php b/src/ChurchCRM/tasks/ChurchNameTask.php index 0b5cb549d1..8f643880e0 100644 --- a/src/ChurchCRM/tasks/ChurchNameTask.php +++ b/src/ChurchCRM/tasks/ChurchNameTask.php @@ -1,26 +1,35 @@ isAdmin() && SystemConfig::getValue('sChurchName') == 'Some Church'; - } - public function isAdmin(){ - return true; - } - public function getLink(){ - return SystemURLs::getRootPath() . '/SystemSettings.php'; - } - public function getTitle(){ - return gettext('Update Church Info'); - } - public function getDesc(){ - return gettext("Church Name is set to default value"); - } + public function isActive() + { + return AuthenticationManager::GetCurrentUser()->isAdmin() && SystemConfig::getValue('sChurchName') == 'Some Church'; + } + + public function isAdmin() + { + return true; + } + + public function getLink() + { + return SystemURLs::getRootPath().'/SystemSettings.php'; + } + + public function getTitle() + { + return gettext('Update Church Info'); + } + public function getDesc() + { + return gettext('Church Name is set to default value'); + } } diff --git a/src/ChurchCRM/tasks/EmailTask.php b/src/ChurchCRM/tasks/EmailTask.php index 082154a0ad..753908622e 100644 --- a/src/ChurchCRM/tasks/EmailTask.php +++ b/src/ChurchCRM/tasks/EmailTask.php @@ -2,35 +2,34 @@ namespace ChurchCRM\Tasks; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; -use ChurchCRM\Authentication\AuthenticationManager; class EmailTask implements iTask { - public function isActive() - { - return AuthenticationManager::GetCurrentUser()->isAdmin() && empty(SystemConfig::hasValidMailServerSettings()); - } - - public function isAdmin() - { - return true; - } - - public function getLink() - { - return SystemURLs::getRootPath() . '/SystemSettings.php'; - } - - public function getTitle() - { - return gettext('Set Email Settings'); - } - - public function getDesc() - { - return gettext("SMTP Server info are blank"); - } - + public function isActive() + { + return AuthenticationManager::GetCurrentUser()->isAdmin() && empty(SystemConfig::hasValidMailServerSettings()); + } + + public function isAdmin() + { + return true; + } + + public function getLink() + { + return SystemURLs::getRootPath().'/SystemSettings.php'; + } + + public function getTitle() + { + return gettext('Set Email Settings'); + } + + public function getDesc() + { + return gettext('SMTP Server info are blank'); + } } diff --git a/src/ChurchCRM/tasks/HttpsTask.php b/src/ChurchCRM/tasks/HttpsTask.php index dac94e7eb0..012fc9eca9 100644 --- a/src/ChurchCRM/tasks/HttpsTask.php +++ b/src/ChurchCRM/tasks/HttpsTask.php @@ -2,26 +2,33 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\dto\SystemURLs; use ChurchCRM\Authentication\AuthenticationManager; +use ChurchCRM\dto\SystemURLs; class HttpsTask implements iTask { - public function isActive(){ - return AuthenticationManager::GetCurrentUser()->isAdmin() && !isset($_SERVER['HTTPS']); - } - public function isAdmin(){ - return true; - } - public function getLink() - { - return SystemURLs::getSupportURL(array_pop(explode('\\', __CLASS__))); - } - public function getTitle(){ - return gettext('Configure HTTPS'); - } - public function getDesc(){ - return gettext('Your system could be more secure by installing an TLS/SSL Cert.'); - } + public function isActive() + { + return AuthenticationManager::GetCurrentUser()->isAdmin() && !isset($_SERVER['HTTPS']); + } + + public function isAdmin() + { + return true; + } + + public function getLink() + { + return SystemURLs::getSupportURL(array_pop(explode('\\', __CLASS__))); + } + + public function getTitle() + { + return gettext('Configure HTTPS'); + } + public function getDesc() + { + return gettext('Your system could be more secure by installing an TLS/SSL Cert.'); + } } diff --git a/src/ChurchCRM/tasks/IntegrityCheckTask.php b/src/ChurchCRM/tasks/IntegrityCheckTask.php index 6e46d3e80a..36c718e13b 100644 --- a/src/ChurchCRM/tasks/IntegrityCheckTask.php +++ b/src/ChurchCRM/tasks/IntegrityCheckTask.php @@ -2,44 +2,42 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\dto\SystemURLs; use ChurchCRM\Authentication\AuthenticationManager; - +use ChurchCRM\dto\SystemURLs; class IntegrityCheckTask implements iTask { - private $integrityCheckData; + private $integrityCheckData; - public function __construct() - { - if (file_exists(SystemURLs::getDocumentRoot() . '/integrityCheck.json')) { - $this->integrityCheckData = json_decode(file_get_contents(SystemURLs::getDocumentRoot() . '/integrityCheck.json')); + public function __construct() + { + if (file_exists(SystemURLs::getDocumentRoot().'/integrityCheck.json')) { + $this->integrityCheckData = json_decode(file_get_contents(SystemURLs::getDocumentRoot().'/integrityCheck.json')); + } } - } - public function isActive() - { - return AuthenticationManager::GetCurrentUser()->isAdmin() && ($this->integrityCheckData == null || $this->integrityCheckData->status == 'failure'); - } - - public function isAdmin() - { - return true; - } + public function isActive() + { + return AuthenticationManager::GetCurrentUser()->isAdmin() && ($this->integrityCheckData == null || $this->integrityCheckData->status == 'failure'); + } - public function getLink() - { - return SystemURLs::getRootPath() . '/v2/admin/debug'; - } + public function isAdmin() + { + return true; + } - public function getTitle() - { - return gettext('Application Integrity Check Failed'); - } + public function getLink() + { + return SystemURLs::getRootPath().'/v2/admin/debug'; + } - public function getDesc() - { - return gettext('Application Integrity Check Failed'); - } + public function getTitle() + { + return gettext('Application Integrity Check Failed'); + } + public function getDesc() + { + return gettext('Application Integrity Check Failed'); + } } diff --git a/src/ChurchCRM/tasks/LatestReleaseTask.php b/src/ChurchCRM/tasks/LatestReleaseTask.php index 1f6a291aeb..1142b8cd56 100644 --- a/src/ChurchCRM/tasks/LatestReleaseTask.php +++ b/src/ChurchCRM/tasks/LatestReleaseTask.php @@ -1,69 +1,69 @@ installedVersion = ChurchCRMReleaseManager::getReleaseFromString($_SESSION['sSoftwareInstalledVersion']); - } + public function __construct() + { + $this->installedVersion = ChurchCRMReleaseManager::getReleaseFromString($_SESSION['sSoftwareInstalledVersion']); + } - public function isActive() - { - $isCurrent = ChurchCRMReleaseManager::isReleaseCurrent($this->installedVersion); - if (! $isCurrent ) + public function isActive() { - try { - // This can fail with an exception if the currently running software is "not current" - // but there are no more available releases. - // this exception will really only happen when running development versions of the software - // or if the ChurchCRM Release on which the current instance is running has been deleted - $this->latestVersion = ChurchCRMReleaseManager::getNextReleaseStep($this->installedVersion); - } - catch (\Exception $e) { - LoggerUtils::getAppLogger()->warning($e); + $isCurrent = ChurchCRMReleaseManager::isReleaseCurrent($this->installedVersion); + if (!$isCurrent) { + try { + // This can fail with an exception if the currently running software is "not current" + // but there are no more available releases. + // this exception will really only happen when running development versions of the software + // or if the ChurchCRM Release on which the current instance is running has been deleted + $this->latestVersion = ChurchCRMReleaseManager::getNextReleaseStep($this->installedVersion); + } catch (\Exception $e) { + LoggerUtils::getAppLogger()->warning($e); + + return false; + } + + return true; + } + return false; - } - return true; } - return false; - } - - public function isAdmin() - { - return false; - } - public function getLink() - { - if (AuthenticationManager::GetCurrentUser()->isAdmin()) { - return SystemURLs::getRootPath() . '/UpgradeCRM.php'; - } else { - return 'https://github.com/ChurchCRM/CRM/releases/latest'; + public function isAdmin() + { + return false; } - } - public function getTitle() - { - return gettext('New Release') . ' ' . $this->latestVersion; - } + public function getLink() + { + if (AuthenticationManager::GetCurrentUser()->isAdmin()) { + return SystemURLs::getRootPath().'/UpgradeCRM.php'; + } else { + return 'https://github.com/ChurchCRM/CRM/releases/latest'; + } + } - public function getDesc() - { - return $this->latestVersion->GetReleaseNotes(); - } + public function getTitle() + { + return gettext('New Release').' '.$this->latestVersion; + } + public function getDesc() + { + return $this->latestVersion->GetReleaseNotes(); + } } diff --git a/src/ChurchCRM/tasks/PHPPendingDeprecationVersionCheckTask.php b/src/ChurchCRM/tasks/PHPPendingDeprecationVersionCheckTask.php index e549792cc0..1ec7c0f404 100644 --- a/src/ChurchCRM/tasks/PHPPendingDeprecationVersionCheckTask.php +++ b/src/ChurchCRM/tasks/PHPPendingDeprecationVersionCheckTask.php @@ -2,40 +2,39 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; - class PHPPendingDeprecationVersionCheckTask implements iTask, iPreUpgradeTask { - private const REQUIRED_PHP_VERSION = '7.4.0'; - public function isActive() - { - return version_compare(PHP_VERSION, $this::REQUIRED_PHP_VERSION, '<'); - } - - public function isAdmin() - { - return true; - } - - public function getLink() - { - return SystemURLs::getRootPath() . '/v2/admin/debug'; - } - - public function getTitle() - { - return gettext('Unsupported PHP Version'); - } - - public function getDesc() - { - return gettext('Support for this PHP version will soon be removed. Current PHP Version: '. PHP_VERSION. ". Minimum Required PHP Version: " . $this::REQUIRED_PHP_VERSION); - } - - public function getUpgradeBehavior() { - return TaskUpgradeBehavior::WARN; - } - + private const REQUIRED_PHP_VERSION = '7.4.0'; + + public function isActive() + { + return version_compare(PHP_VERSION, $this::REQUIRED_PHP_VERSION, '<'); + } + + public function isAdmin() + { + return true; + } + + public function getLink() + { + return SystemURLs::getRootPath().'/v2/admin/debug'; + } + + public function getTitle() + { + return gettext('Unsupported PHP Version'); + } + + public function getDesc() + { + return gettext('Support for this PHP version will soon be removed. Current PHP Version: '.PHP_VERSION.'. Minimum Required PHP Version: '.$this::REQUIRED_PHP_VERSION); + } + + public function getUpgradeBehavior() + { + return TaskUpgradeBehavior::WARN; + } } diff --git a/src/ChurchCRM/tasks/PHPZipArchiveCheckTask.php b/src/ChurchCRM/tasks/PHPZipArchiveCheckTask.php index b433fe1697..7f247ded29 100644 --- a/src/ChurchCRM/tasks/PHPZipArchiveCheckTask.php +++ b/src/ChurchCRM/tasks/PHPZipArchiveCheckTask.php @@ -2,40 +2,38 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; - class PHPZipArchiveCheckTask implements iTask, iPreUpgradeTask { - // todo: make these const variables private after deprecating PHP7.0 #4948 - public function isActive() - { - return ! class_exists("ZipArchive"); - } - - public function isAdmin() - { - return true; - } - - public function getLink() - { - return SystemURLs::getRootPath() . '/v2/admin/debug'; - } - - public function getTitle() - { - return gettext('Missing PHP ZipArchive'); - } - - public function getDesc() - { - return gettext("PHP ZipArchive required to support upgrade"); - } - - public function getUpgradeBehavior() { - return TaskUpgradeBehavior::WARN; - } - + // todo: make these const variables private after deprecating PHP7.0 #4948 + public function isActive() + { + return !class_exists('ZipArchive'); + } + + public function isAdmin() + { + return true; + } + + public function getLink() + { + return SystemURLs::getRootPath().'/v2/admin/debug'; + } + + public function getTitle() + { + return gettext('Missing PHP ZipArchive'); + } + + public function getDesc() + { + return gettext('PHP ZipArchive required to support upgrade'); + } + + public function getUpgradeBehavior() + { + return TaskUpgradeBehavior::WARN; + } } diff --git a/src/ChurchCRM/tasks/PersonClassificationDataCheck.php b/src/ChurchCRM/tasks/PersonClassificationDataCheck.php index 6f5ad913ae..204b56915d 100644 --- a/src/ChurchCRM/tasks/PersonClassificationDataCheck.php +++ b/src/ChurchCRM/tasks/PersonClassificationDataCheck.php @@ -31,17 +31,16 @@ public function isAdmin() public function getLink() { - return SystemURLs::getRootPath() . '/v2/people?Classification=0'; + return SystemURLs::getRootPath().'/v2/people?Classification=0'; } public function getTitle() { - return gettext('Missing Classification Data') . " (" . $this->count . ")"; + return gettext('Missing Classification Data').' ('.$this->count.')'; } public function getDesc() { - return gettext("Missing Classification Data for Some People"); + return gettext('Missing Classification Data for Some People'); } - } diff --git a/src/ChurchCRM/tasks/PersonGenderDataCheck.php b/src/ChurchCRM/tasks/PersonGenderDataCheck.php index 0951cbdc25..8ac00175dc 100644 --- a/src/ChurchCRM/tasks/PersonGenderDataCheck.php +++ b/src/ChurchCRM/tasks/PersonGenderDataCheck.php @@ -31,17 +31,16 @@ public function isAdmin() public function getLink() { - return SystemURLs::getRootPath() . '/v2/people?Gender=0'; + return SystemURLs::getRootPath().'/v2/people?Gender=0'; } public function getTitle() { - return gettext('Missing Gender Data') . " (" . $this->count . ")"; + return gettext('Missing Gender Data').' ('.$this->count.')'; } public function getDesc() { - return gettext("Missing Gender Data for Some People"); + return gettext('Missing Gender Data for Some People'); } - } diff --git a/src/ChurchCRM/tasks/PersonRoleDataCheck.php b/src/ChurchCRM/tasks/PersonRoleDataCheck.php index 39670757e9..fab0be3080 100644 --- a/src/ChurchCRM/tasks/PersonRoleDataCheck.php +++ b/src/ChurchCRM/tasks/PersonRoleDataCheck.php @@ -8,14 +8,13 @@ class PersonRoleDataCheck implements iTask { - private $count; public function __construct() { $personQuery = PersonQuery::create()->filterByFmrId(0) ->filterById(1, Criteria::NOT_EQUAL) - ->filterByFamId("", Criteria::NOT_EQUAL) + ->filterByFamId('', Criteria::NOT_EQUAL) ->find(); $this->count = $personQuery->count(); } @@ -32,17 +31,16 @@ public function isAdmin() public function getLink() { - return SystemURLs::getRootPath() . '/v2/people?FamilyRole=0'; + return SystemURLs::getRootPath().'/v2/people?FamilyRole=0'; } public function getTitle() { - return gettext('Missing Role Data') . " (" . $this->count . ")"; + return gettext('Missing Role Data').' ('.$this->count.')'; } public function getDesc() { - return gettext("Missing Role Data for Some People"); + return gettext('Missing Role Data for Some People'); } - } diff --git a/src/ChurchCRM/tasks/PrerequisiteCheckTask.php b/src/ChurchCRM/tasks/PrerequisiteCheckTask.php index 2e268b4792..74a1a0986d 100644 --- a/src/ChurchCRM/tasks/PrerequisiteCheckTask.php +++ b/src/ChurchCRM/tasks/PrerequisiteCheckTask.php @@ -5,32 +5,30 @@ use ChurchCRM\dto\SystemURLs; use ChurchCRM\Service\AppIntegrityService; - class PrerequisiteCheckTask implements iTask { - public function isActive() - { - return ! AppIntegrityService::arePrerequisitesMet(); - } - - public function isAdmin() - { - return true; - } - - public function getLink() - { - return SystemURLs::getRootPath() . '/v2/admin/debug'; - } - - public function getTitle() - { - return gettext('Unmet Application Prerequisites'); - } - - public function getDesc() - { - return gettext('Unmet Application Prerequisites'); - } - + public function isActive() + { + return !AppIntegrityService::arePrerequisitesMet(); + } + + public function isAdmin() + { + return true; + } + + public function getLink() + { + return SystemURLs::getRootPath().'/v2/admin/debug'; + } + + public function getTitle() + { + return gettext('Unmet Application Prerequisites'); + } + + public function getDesc() + { + return gettext('Unmet Application Prerequisites'); + } } diff --git a/src/ChurchCRM/tasks/RegisteredTask.php b/src/ChurchCRM/tasks/RegisteredTask.php index e3967dcf61..54e846d496 100644 --- a/src/ChurchCRM/tasks/RegisteredTask.php +++ b/src/ChurchCRM/tasks/RegisteredTask.php @@ -5,32 +5,30 @@ use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; - class RegisteredTask implements iTask { - public function isActive() - { - return SystemConfig::getValue('bRegistered') != 1; - } - - public function isAdmin() - { - return false; - } - - public function getLink() - { - return SystemURLs::getRootPath() . '/Register.php'; - } - - public function getTitle() - { - return gettext('Register Software'); - } - - public function getDesc() - { - return gettext('Let us know that you are using the software'); - } - + public function isActive() + { + return SystemConfig::getValue('bRegistered') != 1; + } + + public function isAdmin() + { + return false; + } + + public function getLink() + { + return SystemURLs::getRootPath().'/Register.php'; + } + + public function getTitle() + { + return gettext('Register Software'); + } + + public function getDesc() + { + return gettext('Let us know that you are using the software'); + } } diff --git a/src/ChurchCRM/tasks/SecretsConfigurationCheckTask.php b/src/ChurchCRM/tasks/SecretsConfigurationCheckTask.php index 889fbffb94..bf82635697 100644 --- a/src/ChurchCRM/tasks/SecretsConfigurationCheckTask.php +++ b/src/ChurchCRM/tasks/SecretsConfigurationCheckTask.php @@ -5,32 +5,30 @@ use ChurchCRM\dto\SystemURLs; use ChurchCRM\KeyManager; - class SecretsConfigurationCheckTask implements iTask { - public function isActive() - { - return ! KeyManager::GetAreAllSecretsDefined(); - } - - public function isAdmin() - { - return true; - } - - public function getLink() - { - return SystemURLs::getSupportURL(array_pop(explode('\\', __CLASS__))); - } - - public function getTitle() - { - return gettext('Secret Keys missing from Config.php'); - } - - public function getDesc() - { - return gettext('Secret Keys missing from Config.php'); - } - + public function isActive() + { + return !KeyManager::GetAreAllSecretsDefined(); + } + + public function isAdmin() + { + return true; + } + + public function getLink() + { + return SystemURLs::getSupportURL(array_pop(explode('\\', __CLASS__))); + } + + public function getTitle() + { + return gettext('Secret Keys missing from Config.php'); + } + + public function getDesc() + { + return gettext('Secret Keys missing from Config.php'); + } } diff --git a/src/ChurchCRM/tasks/UnsupportedDepositCheck.php b/src/ChurchCRM/tasks/UnsupportedDepositCheck.php index 7a27ba3ab6..204fb6f4b7 100644 --- a/src/ChurchCRM/tasks/UnsupportedDepositCheck.php +++ b/src/ChurchCRM/tasks/UnsupportedDepositCheck.php @@ -3,8 +3,8 @@ namespace ChurchCRM\Tasks; use ChurchCRM\DepositQuery; -use Propel\Runtime\ActiveQuery\Criteria; use ChurchCRM\dto\SystemURLs; +use Propel\Runtime\ActiveQuery\Criteria; class UnsupportedDepositCheck implements iTask { @@ -13,7 +13,7 @@ class UnsupportedDepositCheck implements iTask public function __construct() { $UnsupportedQuery = DepositQuery::create() - ->filterByType("Bank", Criteria::NOT_EQUAL) + ->filterByType('Bank', Criteria::NOT_EQUAL) ->find(); $this->count = $UnsupportedQuery->count(); } @@ -35,12 +35,11 @@ public function getLink() public function getTitle() { - return gettext('Unsupported Deposit Types Detected') . " (" . $this->count . ")"; + return gettext('Unsupported Deposit Types Detected').' ('.$this->count.')'; } public function getDesc() { - return gettext("Support for eGive, Credit Card, and Bank Draft payments has been deprecated. Existing non-bank reports may no longer be accessible in future versions."); + return gettext('Support for eGive, Credit Card, and Bank Draft payments has been deprecated. Existing non-bank reports may no longer be accessible in future versions.'); } - } diff --git a/src/ChurchCRM/tasks/UpdateFamilyCoordinatesTask.php b/src/ChurchCRM/tasks/UpdateFamilyCoordinatesTask.php index a2fd57be40..9d2c2d0a78 100644 --- a/src/ChurchCRM/tasks/UpdateFamilyCoordinatesTask.php +++ b/src/ChurchCRM/tasks/UpdateFamilyCoordinatesTask.php @@ -1,10 +1,9 @@ filterByLatitude("")->find(); + $query = FamilyQuery::create()->filterByLatitude('')->find(); $this->count = $query->count(); } @@ -28,16 +27,16 @@ public function isAdmin() public function getLink() { - return SystemURLs::getRootPath() . '/UpdateAllLatLon.php'; + return SystemURLs::getRootPath().'/UpdateAllLatLon.php'; } public function getTitle() { - return gettext('Missing Coordinates') . " (" . $this->count . ")"; + return gettext('Missing Coordinates').' ('.$this->count.')'; } public function getDesc() { - return gettext("Family Coordinates Data for Some Families"); + return gettext('Family Coordinates Data for Some Families'); } } diff --git a/src/ChurchCRM/tasks/iPreUpgradeTask.php b/src/ChurchCRM/tasks/iPreUpgradeTask.php index 2fa4d284bf..30f25045f0 100644 --- a/src/ChurchCRM/tasks/iPreUpgradeTask.php +++ b/src/ChurchCRM/tasks/iPreUpgradeTask.php @@ -2,6 +2,6 @@ namespace ChurchCRM\Tasks; -interface iPreUpgradeTask extends iTask{ - -} \ No newline at end of file +interface iPreUpgradeTask extends iTask +{ +} diff --git a/src/ChurchCRM/tasks/iTask.php b/src/ChurchCRM/tasks/iTask.php index 506b949973..480d340b03 100644 --- a/src/ChurchCRM/tasks/iTask.php +++ b/src/ChurchCRM/tasks/iTask.php @@ -2,14 +2,15 @@ namespace ChurchCRM\Tasks; - interface iTask { + public function isActive(); + + public function isAdmin(); + + public function getLink(); - public function isActive(); - public function isAdmin(); - public function getLink(); - public function getTitle(); - public function getDesc(); + public function getTitle(); + public function getDesc(); } diff --git a/src/ChurchCRM/utils/ExecutionTime.php b/src/ChurchCRM/utils/ExecutionTime.php index f7ccd5f44b..8c678798a3 100644 --- a/src/ChurchCRM/utils/ExecutionTime.php +++ b/src/ChurchCRM/utils/ExecutionTime.php @@ -4,41 +4,47 @@ class ExecutionTime { - // inspired from https://stackoverflow.com/a/22885011 - private $startTime; - private $endTime; - private $startR; - private $endR; - public function __construct(){ - $this->startTime = microtime(TRUE); - $this->startR = getrusage(); - } - - public function End(){ - $this->endTime = microtime(TRUE); - $this->endR = getrusage(); - } - - public function getMilliseconds() { - // if End() has not yet been called, this returns the current number of running seconds. - // Otherwise, returns the ending number of seconds - if (is_null($this->endTime)){ - $value = (microtime(TRUE) - $this->startTime)*1000; + // inspired from https://stackoverflow.com/a/22885011 + private $startTime; + private $endTime; + private $startR; + private $endR; + + public function __construct() + { + $this->startTime = microtime(true); + $this->startR = getrusage(); } - else { - $value = ($this->endTime - $this->startTime)*1000; + + public function End() + { + $this->endTime = microtime(true); + $this->endR = getrusage(); } - return round($value,2); - } - private function runTime($ru, $rus, $index) { - return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000)) - - ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000)); - } + public function getMilliseconds() + { + // if End() has not yet been called, this returns the current number of running seconds. + // Otherwise, returns the ending number of seconds + if (is_null($this->endTime)) { + $value = (microtime(true) - $this->startTime) * 1000; + } else { + $value = ($this->endTime - $this->startTime) * 1000; + } + + return round($value, 2); + } - public function __toString(){ - return "This process used " . $this->runTime($this->endTime, $this->startTime, "utime") . - " ms for its computations\nIt spent " . $this->runTime($this->endTime, $this->startTime, "stime") . + private function runTime($ru, $rus, $index) + { + return ($ru["ru_$index.tv_sec"] * 1000 + intval($ru["ru_$index.tv_usec"] / 1000)) + - ($rus["ru_$index.tv_sec"] * 1000 + intval($rus["ru_$index.tv_usec"] / 1000)); + } + + public function __toString() + { + return 'This process used '.$this->runTime($this->endTime, $this->startTime, 'utime'). + " ms for its computations\nIt spent ".$this->runTime($this->endTime, $this->startTime, 'stime'). " ms in system calls\n"; - } -} \ No newline at end of file + } +} diff --git a/src/ChurchCRM/utils/GeoUtils.php b/src/ChurchCRM/utils/GeoUtils.php index 5b4a0f14a5..bc80953b3c 100644 --- a/src/ChurchCRM/utils/GeoUtils.php +++ b/src/ChurchCRM/utils/GeoUtils.php @@ -2,22 +2,18 @@ namespace ChurchCRM\Utils; -use ChurchCRM\Authentication\AuthenticationManager; +use ChurchCRM\Bootstrapper; use ChurchCRM\dto\SystemConfig; -use ChurchCRM\dto\LocaleInfo; use Geocoder\Provider\BingMaps\BingMaps; use Geocoder\Provider\GoogleMaps\GoogleMaps; +use Geocoder\Query\GeocodeQuery; use Geocoder\StatefulGeocoder; use Http\Adapter\Guzzle7\Client; -use Geocoder\Query\GeocodeQuery; -use ChurchCRM\Bootstrapper; class GeoUtils { - public static function getLatLong($address) { - $logger = LoggerUtils::getAppLogger(); $localeInfo = Bootstrapper::GetCurrentLocale(); @@ -26,19 +22,20 @@ public static function getLatLong($address) $lat = 0; $long = 0; + try { - switch (SystemConfig::getValue("sGeoCoderProvider")) { - case "GoogleMaps": - $provider = new GoogleMaps($adapter, null, SystemConfig::getValue("sGoogleMapsGeocodeKey")); + switch (SystemConfig::getValue('sGeoCoderProvider')) { + case 'GoogleMaps': + $provider = new GoogleMaps($adapter, null, SystemConfig::getValue('sGoogleMapsGeocodeKey')); break; - case "BingMaps": - $provider = new BingMaps($adapter, SystemConfig::getValue("sBingMapKey")); + case 'BingMaps': + $provider = new BingMaps($adapter, SystemConfig::getValue('sBingMapKey')); break; } - $logger->debug("Using: Geo Provider - ". $provider->getName()); + $logger->debug('Using: Geo Provider - '.$provider->getName()); $geoCoder = new StatefulGeocoder($provider, $localeInfo->getShortLocale()); $result = $geoCoder->geocodeQuery(GeocodeQuery::create($address)); - $logger->debug("We have " . $result->count() . " results"); + $logger->debug('We have '.$result->count().' results'); if (!empty($result)) { $firstResult = $result->get(0); $coordinates = $firstResult->getCoordinates(); @@ -46,32 +43,32 @@ public static function getLatLong($address) $long = $coordinates->getLongitude(); } } catch (\Exception $exception) { - $logger->warning("issue creating geoCoder " . $exception->getMessage()); + $logger->warning('issue creating geoCoder '.$exception->getMessage()); } - return array( - 'Latitude' => $lat, - 'Longitude' => $long - ); - + return [ + 'Latitude' => $lat, + 'Longitude' => $long, + ]; } public static function DrivingDistanceMatrix($address1, $address2) { $logger = LoggerUtils::getAppLogger(); $localeInfo = Bootstrapper::GetCurrentLocale(); - $url = "https://maps.googleapis.com/maps/api/distancematrix/json?"; - $url = $url . "language=" . $localeInfo->getShortLocale(); - $url = $url . "&origins=" . urlencode($address1); - $url = $url . "&destinations=" . urlencode($address2); + $url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'; + $url = $url.'language='.$localeInfo->getShortLocale(); + $url = $url.'&origins='.urlencode($address1); + $url = $url.'&destinations='.urlencode($address2); $logger->debug($url); $gMapsResponse = file_get_contents($url); - $details = json_decode($gMapsResponse, TRUE); + $details = json_decode($gMapsResponse, true); $matrixElements = $details['rows'][0]['elements'][0]; - return array( + + return [ 'distance' => $matrixElements['distance']['text'], - 'duration' => $matrixElements['duration']['text'] - ); + 'duration' => $matrixElements['duration']['text'], + ]; } // Function takes latitude and longitude @@ -79,7 +76,6 @@ public static function DrivingDistanceMatrix($address1, $address2) // distance in miles. public static function LatLonDistance($lat1, $lon1, $lat2, $lon2) { - // Formula for calculating radians between // latitude and longitude pairs. diff --git a/src/ChurchCRM/utils/InputUtils.php b/src/ChurchCRM/utils/InputUtils.php index 086b939118..d745218ee1 100644 --- a/src/ChurchCRM/utils/InputUtils.php +++ b/src/ChurchCRM/utils/InputUtils.php @@ -4,88 +4,88 @@ use ChurchCRM\dto\SystemConfig; -class InputUtils { - - private static $AllowedHTMLTags = '


    • '; - - public static function LegacyFilterInputArr($arr, $key, $type = 'string', $size = 1) - { - if (array_key_exists($key, $arr)) { - return InputUtils::LegacyFilterInput($arr[$key], $type, $size); - } else { - return InputUtils::LegacyFilterInput('', $type, $size); - } - } - - public static function translate_special_charset ($string) - { - if (empty($string)) - return ""; - - return (SystemConfig::getValue("sCSVExportCharset") == "UTF-8")?gettext($string):iconv('UTF-8', SystemConfig::getValue("sCSVExportCharset"), gettext($string)); - } +class InputUtils +{ + private static $AllowedHTMLTags = '