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/src/AddDonors.php b/src/AddDonors.php index bdb6f4f1bf..866ceafd5a 100644 --- a/src/AddDonors.php +++ b/src/AddDonors.php @@ -30,7 +30,7 @@ if ($iFundRaiserID > 0) { // Get the current fund raiser record - $sSQL = 'SELECT * from fundraiser_fr WHERE fr_ID = ' . $iFundRaiserID; + $sSQL = 'SELECT * from fundraiser_fr WHERE fr_ID = '.$iFundRaiserID; $rsFRR = RunQuery($sSQL); extract(mysqli_fetch_array($rsFRR)); // Set current fundraiser @@ -42,11 +42,11 @@ // Get all the people listed as donors for this fundraiser $sSQL = "SELECT a.per_id as donorID FROM donateditem_di LEFT JOIN person_per a ON di_donor_ID=a.per_ID - WHERE di_FR_ID = '" . $iFundRaiserID . "' ORDER BY a.per_id"; + WHERE di_FR_ID = '".$iFundRaiserID."' ORDER BY a.per_id"; $rsDonors = RunQuery($sSQL); $extraPaddleNum = 1; -$sSQL = "SELECT MAX(pn_NUM) AS pn_max FROM paddlenum_pn WHERE pn_FR_ID = '" . $iFundRaiserID . "'"; +$sSQL = "SELECT MAX(pn_NUM) AS pn_max FROM paddlenum_pn WHERE pn_FR_ID = '".$iFundRaiserID."'"; $rsMaxPaddle = RunQuery($sSQL); if (mysqli_num_rows($rsMaxPaddle) > 0) { $oneRow = mysqli_fetch_array($rsMaxPaddle); diff --git a/src/CSVCreateFile.php b/src/CSVCreateFile.php index 703d1daab2..f7c81945ec 100644 --- a/src/CSVCreateFile.php +++ b/src/CSVCreateFile.php @@ -15,14 +15,14 @@ use ChurchCRM\Base\PersonQuery; 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(); @@ -79,7 +79,7 @@ // If our source is the cart contents, we don't need to build a WHERE filter string if ($sSource == 'cart') { - $sWhereExt = 'AND per_ID IN (' . convertCartToString($_SESSION['aPeopleCart']) . ')'; + $sWhereExt = 'AND per_ID IN ('.convertCartToString($_SESSION['aPeopleCart']).')'; } else { // If we're filtering by groups, include the p2g2r table if (!empty($_POST['GroupID'])) { @@ -95,12 +95,12 @@ } if ($count == 1) { if ($Class[0]) { - $sWhereExt .= 'AND per_cls_ID = ' . $Class[0] . ' '; + $sWhereExt .= 'AND per_cls_ID = '.$Class[0].' '; } } else { - $sWhereExt .= 'AND (per_cls_ID = ' . $Class[0]; + $sWhereExt .= 'AND (per_cls_ID = '.$Class[0]; for ($i = 1; $i < $count; $i++) { - $sWhereExt .= ' OR per_cls_ID = ' . $Class[$i]; + $sWhereExt .= ' OR per_cls_ID = '.$Class[$i]; } $sWhereExt .= ') '; // this is silly: should be something like.. $sWhereExt .= "AND per_cls_ID IN @@ -114,19 +114,19 @@ } if ($count == 1) { if ($Class[0]) { - $sWhereExt .= 'AND per_fmr_ID = ' . $Class[0] . ' '; + $sWhereExt .= 'AND per_fmr_ID = '.$Class[0].' '; } } else { - $sWhereExt .= 'AND (per_fmr_ID = ' . $Class[0]; + $sWhereExt .= 'AND (per_fmr_ID = '.$Class[0]; for ($i = 1; $i < $count; $i++) { - $sWhereExt .= ' OR per_fmr_ID = ' . $Class[$i]; + $sWhereExt .= ' OR per_fmr_ID = '.$Class[$i]; } $sWhereExt .= ') '; } } if (!empty($_POST['Gender'])) { - $sWhereExt .= 'AND per_Gender = ' . InputUtils::legacyFilterInput($_POST['Gender'], 'int') . ' '; + $sWhereExt .= 'AND per_Gender = '.InputUtils::legacyFilterInput($_POST['Gender'], 'int').' '; } if (!empty($_POST['GroupID'])) { @@ -136,12 +136,12 @@ } if ($count == 1) { if ($Class[0]) { - $sWhereExt .= 'AND per_ID = p2g2r_per_ID AND p2g2r_grp_ID = ' . $Class[0] . ' '; + $sWhereExt .= 'AND per_ID = p2g2r_per_ID AND p2g2r_grp_ID = '.$Class[0].' '; } } else { - $sWhereExt .= 'AND per_ID = p2g2r_per_ID AND (p2g2r_grp_ID = ' . $Class[0]; + $sWhereExt .= 'AND per_ID = p2g2r_per_ID AND (p2g2r_grp_ID = '.$Class[0]; for ($i = 1; $i < $count; $i++) { - $sWhereExt .= ' OR p2g2r_grp_ID = ' . $Class[$i]; + $sWhereExt .= ' OR p2g2r_grp_ID = '.$Class[$i]; } $sWhereExt .= ') '; } @@ -153,20 +153,20 @@ } if (!empty($_POST['MembershipDate1'])) { - $sWhereExt .= "AND per_MembershipDate >= '" . InputUtils::legacyFilterInput($_POST['MembershipDate1'], 'char', 10) . "' "; + $sWhereExt .= "AND per_MembershipDate >= '".InputUtils::legacyFilterInput($_POST['MembershipDate1'], 'char', 10)."' "; } if ($_POST['MembershipDate2'] != date('Y-m-d')) { - $sWhereExt .= "AND per_MembershipDate <= '" . InputUtils::legacyFilterInput($_POST['MembershipDate2'], 'char', 10) . "' "; + $sWhereExt .= "AND per_MembershipDate <= '".InputUtils::legacyFilterInput($_POST['MembershipDate2'], 'char', 10)."' "; } $refDate = getdate(time()); if (!empty($_POST['BirthDate1'])) { - $sWhereExt .= "AND DATE_FORMAT(CONCAT(per_BirthYear,'-',per_BirthMonth,'-',per_BirthDay),'%Y-%m-%d') >= '" . InputUtils::legacyFilterInput($_POST['BirthDate1'], 'char', 10) . "' "; + $sWhereExt .= "AND DATE_FORMAT(CONCAT(per_BirthYear,'-',per_BirthMonth,'-',per_BirthDay),'%Y-%m-%d') >= '".InputUtils::legacyFilterInput($_POST['BirthDate1'], 'char', 10)."' "; } if ($_POST['BirthDate2'] != date('Y-m-d')) { - $sWhereExt .= "AND DATE_FORMAT(CONCAT(per_BirthYear,'-',per_BirthMonth,'-',per_BirthDay),'%Y-%m-%d') <= '" . InputUtils::legacyFilterInput($_POST['BirthDate2'], 'char', 10) . "' "; + $sWhereExt .= "AND DATE_FORMAT(CONCAT(per_BirthYear,'-',per_BirthMonth,'-',per_BirthDay),'%Y-%m-%d') <= '".InputUtils::legacyFilterInput($_POST['BirthDate2'], 'char', 10)."' "; } if (!empty($_POST['AnniversaryDate1'])) { @@ -174,9 +174,9 @@ // Add year to query if not in future if ($annivStart['year'] < date('Y') || ($annivStart['year'] == date('Y') && $annivStart['mon'] <= date('m') && $annivStart['mday'] <= date('d'))) { - $sWhereExt .= "AND fam_WeddingDate >= '" . InputUtils::legacyFilterInput($_POST['AnniversaryDate1'], 'char', 10) . "' "; + $sWhereExt .= "AND fam_WeddingDate >= '".InputUtils::legacyFilterInput($_POST['AnniversaryDate1'], 'char', 10)."' "; } else { - $sWhereExt .= "AND DAYOFYEAR(fam_WeddingDate) >= DAYOFYEAR('" . InputUtils::legacyFilterInput($_POST['AnniversaryDate1'], 'char', 10) . "') "; + $sWhereExt .= "AND DAYOFYEAR(fam_WeddingDate) >= DAYOFYEAR('".InputUtils::legacyFilterInput($_POST['AnniversaryDate1'], 'char', 10)."') "; } } @@ -185,18 +185,18 @@ // Add year to query if not in future if ($annivEnd['year'] < date('Y') || ($annivEnd['year'] == date('Y') && $annivEnd['mon'] <= date('m') && $annivEnd['mday'] <= date('d'))) { - $sWhereExt .= "AND fam_WeddingDate <= '" . InputUtils::legacyFilterInput($_POST['AnniversaryDate2'], 'char', 10) . "' "; + $sWhereExt .= "AND fam_WeddingDate <= '".InputUtils::legacyFilterInput($_POST['AnniversaryDate2'], 'char', 10)."' "; } else { $refDate = getdate(strtotime($_POST['AnniversaryDate2'])); - $sWhereExt .= "AND DAYOFYEAR(fam_WeddingDate) <= DAYOFYEAR('" . InputUtils::legacyFilterInput($_POST['AnniversaryDate2'], 'char', 10) . "') "; + $sWhereExt .= "AND DAYOFYEAR(fam_WeddingDate) <= DAYOFYEAR('".InputUtils::legacyFilterInput($_POST['AnniversaryDate2'], 'char', 10)."') "; } } if (!empty($_POST['EnterDate1'])) { - $sWhereExt .= "AND per_DateEntered >= '" . InputUtils::legacyFilterInput($_POST['EnterDate1'], 'char', 10) . "' "; + $sWhereExt .= "AND per_DateEntered >= '".InputUtils::legacyFilterInput($_POST['EnterDate1'], 'char', 10)."' "; } if ($_POST['EnterDate2'] != date('Y-m-d')) { - $sWhereExt .= "AND per_DateEntered <= '" . InputUtils::legacyFilterInput($_POST['EnterDate2'], 'char', 10) . "' "; + $sWhereExt .= "AND per_DateEntered <= '".InputUtils::legacyFilterInput($_POST['EnterDate2'], 'char', 10)."' "; } } @@ -211,7 +211,7 @@ Cart::addPerson($per_ID); } //// TODO: do this in API - RedirectUtils::redirect("v2/cart"); + RedirectUtils::redirect('v2/cart'); } else { // Build the complete SQL statement @@ -227,90 +227,90 @@ $rsLabelsToWrite = RunQuery($sSQL); //Produce Header Based on Selected Fields - $headerString = '"' . InputUtils::translateSpecialCharset("Family") . ' ID "' . $delimiter; + $headerString = '"'.InputUtils::translateSpecialCharset('Family').' ID "'.$delimiter; if ($sFormat == 'rollup') { - $headerString .= '"' . InputUtils::translateSpecialCharset("Name") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Name').'"'.$delimiter; // Add Salutation for family here... - $headerString .= '"' . InputUtils::translateSpecialCharset("Salutation") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Salutation').'"'.$delimiter; } else { - $headerString .= '"' . InputUtils::translateSpecialCharset("Person") . ' Id"' . $delimiter; - $headerString .= '"' . InputUtils::translateSpecialCharset("Last Name") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Person').' Id"'.$delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Last Name').'"'.$delimiter; if (!empty($_POST['Title'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Title") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Title').'"'.$delimiter; } if (!empty($_POST['FirstName'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("First Name") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('First Name').'"'.$delimiter; } if (!empty($_POST['Suffix'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Suffix") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Suffix').'"'.$delimiter; } if (!empty($_POST['MiddleName'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Middle Name") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Middle Name').'"'.$delimiter; } } if (!empty($_POST['Address1'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Address 1") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Address 1').'"'.$delimiter; } if (!empty($_POST['Address2'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Address 2") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Address 2').'"'.$delimiter; } if (!empty($_POST['City'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("City") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('City').'"'.$delimiter; } if (!empty($_POST['State'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("State") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('State').'"'.$delimiter; } if (!empty($_POST['Zip'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Zip") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Zip').'"'.$delimiter; } if (!empty($_POST['Country'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Country") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Country').'"'.$delimiter; } if (!empty($_POST['HomePhone'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Home Phone") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Home Phone').'"'.$delimiter; } if (!empty($_POST['WorkPhone'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Work Phone") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Work Phone').'"'.$delimiter; } if (!empty($_POST['CellPhone'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Cell Phone") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Cell Phone').'"'.$delimiter; } if (!empty($_POST['Email'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Email") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Email').'"'.$delimiter; } if (!empty($_POST['WorkEmail'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Work Email") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Work Email').'"'.$delimiter; } if (!empty($_POST['Envelope'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Envelope Number") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Envelope Number').'"'.$delimiter; } if (!empty($_POST['MembershipDate'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("MembershipDate") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('MembershipDate').'"'.$delimiter; } if ($sFormat == 'default') { if (!empty($_POST['BirthdayDate'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Birth Date") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Birth Date').'"'.$delimiter; } if (!empty($_POST['Age'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Age") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Age').'"'.$delimiter; } if (!empty($_POST['PrintMembershipStatus'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Classification") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Classification').'"'.$delimiter; } if (!empty($_POST['PrintFamilyRole'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Family Role") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Family Role').'"'.$delimiter; } if (!empty($_POST['PrintGender'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Gender") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Gender').'"'.$delimiter; } } else { if (!empty($_POST['Birthday Date'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("AnnivDate") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('AnnivDate').'"'.$delimiter; } if (!empty($_POST['Age'])) { - $headerString .= '"' . InputUtils::translateSpecialCharset("Anniv") . '"' . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset('Anniv').'"'.$delimiter; } } @@ -321,15 +321,15 @@ extract($aRow); if (isset($_POST["$custom_Field"])) { $bUsedCustomFields = true; - $headerString .= "\"" . InputUtils::translateSpecialCharset($custom_Name) . "\"" . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset($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::translateSpecialCharset($fam_custom_Name) . "\"" . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset($fam_custom_Name).'"'.$delimiter; } } } @@ -338,10 +338,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::translateSpecialCharset($fam_custom_Name) . "\"" . $delimiter; + $headerString .= '"'.InputUtils::translateSpecialCharset($fam_custom_Name).'"'.$delimiter; } } } @@ -350,15 +350,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,82 +433,82 @@ // ** 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; + $sString .= '"'.$delimiter.'"'.$per_ID; + $sString .= '"'.$delimiter.'"'.$per_LastName; if (isset($_POST['Title'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($per_Title); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($per_Title); } if (isset($_POST['FirstName'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($per_FirstName); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($per_FirstName); } if (isset($_POST['Suffix'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($per_Suffix); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($per_Suffix); } if (isset($_POST['MiddleName'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($per_MiddleName); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($per_MiddleName); } } elseif ($sFormat == 'rollup') { $family = FamilyQuery::create()->findPk($fam_ID); if ($memberCount > 1) { - $sString .= '"' . $delimiter . '"' . $family->getSalutation(); - $sString .= '"' . $delimiter . '"' . $family->getFirstNameSalutation(); + $sString .= '"'.$delimiter.'"'.$family->getSalutation(); + $sString .= '"'.$delimiter.'"'.$family->getFirstNameSalutation(); } else { - $sString .= '"' . $delimiter . '"' . $per_FirstName . ' ' . $per_LastName; - $sString .= '"' . $delimiter . '"' . $per_FirstName; + $sString .= '"'.$delimiter.'"'.$per_FirstName.' '.$per_LastName; + $sString .= '"'.$delimiter.'"'.$per_FirstName; } } if (isset($_POST['Address1'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($sAddress1); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($sAddress1); } if (isset($_POST['Address2'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($sAddress2); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($sAddress2); } if (isset($_POST['City'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($sCity); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($sCity); } if (isset($_POST['State'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($sState); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($sState); } if (isset($_POST['Zip'])) { - $sString .= '"' . $delimiter . '"' . $sZip; + $sString .= '"'.$delimiter.'"'.$sZip; } if (isset($_POST['Country'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($sCountry); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($sCountry); } if (isset($_POST['HomePhone'])) { - $sString .= '"' . $delimiter . '"' . $sHomePhone; + $sString .= '"'.$delimiter.'"'.$sHomePhone; } if (isset($_POST['WorkPhone'])) { - $sString .= '"' . $delimiter . '"' . $sWorkPhone; + $sString .= '"'.$delimiter.'"'.$sWorkPhone; } if (isset($_POST['CellPhone'])) { - $sString .= '"' . $delimiter . '"' . $sCellPhone; + $sString .= '"'.$delimiter.'"'.$sCellPhone; } if (isset($_POST['Email'])) { - $sString .= '"' . $delimiter . '"' . $sEmail; + $sString .= '"'.$delimiter.'"'.$sEmail; } if (isset($_POST['WorkEmail'])) { - $sString .= '"' . $delimiter . '"' . $per_WorkEmail; + $sString .= '"'.$delimiter.'"'.$per_WorkEmail; } if (isset($_POST['Envelope'])) { - $sString .= '"' . $delimiter . '"' . $fam_Envelope; + $sString .= '"'.$delimiter.'"'.$fam_Envelope; } if (isset($_POST['MembershipDate'])) { - $sString .= '"' . $delimiter . '"' . $per_MembershipDate; + $sString .= '"'.$delimiter.'"'.$per_MembershipDate; } if ($sFormat == 'default') { if (isset($_POST['BirthdayDate'])) { - $sString .= '"' . $delimiter . '"'; + $sString .= '"'.$delimiter.'"'; if ($per_BirthYear != '') { - $sString .= $per_BirthYear . '-'; + $sString .= $per_BirthYear.'-'; } else { $sString .= ''; } - $sString .= $per_BirthMonth . '-' . $per_BirthDay; + $sString .= $per_BirthMonth.'-'.$per_BirthDay; } if (isset($_POST['Age'])) { @@ -519,21 +518,21 @@ $age = ''; } - $sString .= '"' . $delimiter . '"' . $age; + $sString .= '"'.$delimiter.'"'.$age; } if (isset($_POST['PrintMembershipStatus'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($memberClass[$per_cls_ID]); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($memberClass[$per_cls_ID]); } if (isset($_POST['PrintFamilyRole'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($familyRoles[$per_fmr_ID]); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($familyRoles[$per_fmr_ID]); } if (isset($_POST['PrintGender'])) { - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset($person->getGenderName()); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset($person->getGenderName()); } } else { if (isset($_POST['BirthdayDate'])) { - $sString .= '"' . $delimiter . '"' . $fam_WeddingDate; + $sString .= '"'.$delimiter.'"'.$fam_WeddingDate; } if (isset($_POST['Age'])) { @@ -544,12 +543,12 @@ $age = ''; } - $sString .= '"' . $delimiter . '"' . $age; + $sString .= '"'.$delimiter.'"'.$age; } } if ($bUsedCustomFields && ($sFormat == 'default')) { - $sSQLcustom = 'SELECT * FROM person_custom WHERE per_ID = ' . $per_ID; + $sSQLcustom = 'SELECT * FROM person_custom WHERE per_ID = '.$per_ID; $rsCustomData = RunQuery($sSQLcustom); $aCustomData = mysqli_fetch_array($rsCustomData); @@ -567,13 +566,13 @@ if ($type_ID == 11) { $custom_Special = $sCountry; } - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset(displayCustomField($type_ID, trim($aCustomData[$custom_Field]), $custom_Special)); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset(displayCustomField($type_ID, trim($aCustomData[$custom_Field]), $custom_Special)); } } } } - $sSQLFamCustom = 'SELECT * FROM family_custom WHERE fam_ID = ' . $per_fam_ID; + $sSQLFamCustom = 'SELECT * FROM family_custom WHERE fam_ID = '.$per_fam_ID; $rsFamCustomData = RunQuery($sSQLFamCustom); $aFamCustomData = mysqli_fetch_array($rsFamCustomData); @@ -590,14 +589,14 @@ if ($type_ID == 11) { $fam_custom_Special = $sCountry; } - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset(displayCustomField($type_ID, trim($aFamCustomData[$fam_custom_Field]), $fam_custom_Special)); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset(displayCustomField($type_ID, trim($aFamCustomData[$fam_custom_Field]), $fam_custom_Special)); } } } } if ($bUsedCustomFields && ($sFormat == 'rollup')) { - $sSQLFamCustom = 'SELECT * FROM family_custom WHERE fam_ID = ' . $per_fam_ID; + $sSQLFamCustom = 'SELECT * FROM family_custom WHERE fam_ID = '.$per_fam_ID; $rsFamCustomData = RunQuery($sSQLFamCustom); $aFamCustomData = mysqli_fetch_array($rsFamCustomData); @@ -614,7 +613,7 @@ if ($type_ID == 11) { $fam_custom_Special = $sCountry; } - $sString .= '"' . $delimiter . '"' . InputUtils::translateSpecialCharset(displayCustomField($type_ID, trim($aFamCustomData[$fam_custom_Field]), $fam_custom_Special)); + $sString .= '"'.$delimiter.'"'.InputUtils::translateSpecialCharset(displayCustomField($type_ID, trim($aFamCustomData[$fam_custom_Field]), $fam_custom_Special)); } } } diff --git a/src/ChurchCRM/ArrayUtils.php b/src/ChurchCRM/ArrayUtils.php index 7697d25e48..678c3b4bba 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())); - } - return $currentUser; - } catch (\Exception $e) { - LoggerUtils::getAppLogger()->debug('Failed to get current user', ['exception' => $e]); - throw $e; + 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', ['exception' => $e]); + + throw $e; } + } - public static function endSession($preventRedirect = false) - { - $logger = LoggerUtils::getAuthLogger(); - $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. + public static function endSession($preventRedirect = false) + { + $logger = LoggerUtils::getAuthLogger(); + $currentSessionUserName = 'Unknown'; + + try { + if (self::getCurrentUser() !== null) { + $currentSessionUserName = self::getCurrentUser()->getName(); } - $logCtx = ['username' => $currentSessionUserName]; - - try { - $result = self::getAuthenticationProvider()->endSession(); - $_COOKIE = []; - $_SESSION = []; - session_destroy(); - Bootstrapper::initSession(); - $logger->info( - 'Ended Local session for user', - $logCtx - ); - } catch (\Exception $e) { - $logger->warning( - 'Error destroying session', - array_merge($logCtx, ['exception' => $e]) - ); - } finally { - if (!$preventRedirect) { - RedirectUtils::redirect(self::getSessionBeginURL()); - } + } catch (\Exception $e) { + //unable to get name of user logging out. Don't really care. + } + $logCtx = ['username' => $currentSessionUserName]; + + try { + $result = self::getAuthenticationProvider()->endSession(); + $_COOKIE = []; + $_SESSION = []; + session_destroy(); + Bootstrapper::initSession(); + $logger->info( + 'Ended Local session for user', + $logCtx + ); + } catch (\Exception $e) { + $logger->warning( + 'Error destroying session', + array_merge($logCtx, ['exception' => $e]) + ); + } finally { + if (!$preventRedirect) { + RedirectUtils::redirect(self::getSessionBeginURL()); } } + } - public static function authenticate(AuthenticationRequest $AuthenticationRequest) - { - $logger = LoggerUtils::getAppLogger(); - switch (get_class($AuthenticationRequest)) { - case \ChurchCRM\Authentication\Requests\APITokenAuthenticationRequest::class: - $AuthenticationProvider = new APITokenAuthentication(); - self::setAuthenticationProvider($AuthenticationProvider); - break; - case \ChurchCRM\Authentication\Requests\LocalUsernamePasswordRequest::class: - $AuthenticationProvider = new LocalAuthentication(); - self::setAuthenticationProvider($AuthenticationProvider); - break; - case \ChurchCRM\Authentication\Requests\LocalTwoFactorTokenRequest::class: - try { - self::getAuthenticationProvider(); - } catch (\Exception $e) { - $logger->warning( - "Tried to supply two factor authentication code, but didn't have an existing session. This shouldn't ever happen", - ['exception' => $e] - ); - } - break; - default: - $logger->critical('Unknown AuthenticationRequest type supplied', ['providedAuthenticationRequestClass' => get_class($AuthenticationRequest)]); - break; - } + public static function authenticate(AuthenticationRequest $AuthenticationRequest) + { + $logger = LoggerUtils::getAppLogger(); + switch (get_class($AuthenticationRequest)) { + case \ChurchCRM\Authentication\Requests\APITokenAuthenticationRequest::class: + $AuthenticationProvider = new APITokenAuthentication(); + self::setAuthenticationProvider($AuthenticationProvider); + break; + case \ChurchCRM\Authentication\Requests\LocalUsernamePasswordRequest::class: + $AuthenticationProvider = new LocalAuthentication(); + self::setAuthenticationProvider($AuthenticationProvider); + break; + case \ChurchCRM\Authentication\Requests\LocalTwoFactorTokenRequest::class: + try { + self::getAuthenticationProvider(); + } catch (\Exception $e) { + $logger->warning( + "Tried to supply two factor authentication code, but didn't have an existing session. This shouldn't ever happen", + ['exception' => $e] + ); + } + break; + default: + $logger->critical('Unknown AuthenticationRequest type supplied', ['providedAuthenticationRequestClass' => get_class($AuthenticationRequest)]); + break; + } - $result = self::getAuthenticationProvider()->authenticate($AuthenticationRequest); + $result = self::getAuthenticationProvider()->authenticate($AuthenticationRequest); - if (null !== $result->nextStepURL) { - $logger->debug('Authentication requires additional step: ' . $result->nextStepURL); - RedirectUtils::redirect($result->nextStepURL); - } + if (null !== $result->nextStepURL) { + $logger->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(); - $logger->debug('Authentication Successful; redirecting to: ' . $redirectLocation); - RedirectUtils::redirect($redirectLocation); - } - return $result; + if ($result->isAuthenticated && !$result->preventRedirect) { + $redirectLocation = array_key_exists('location', $_SESSION) ? $_SESSION['location'] : 'Menu.php'; + NotificationService::updateNotifications(); + $logger->debug('Authentication Successful; redirecting to: '.$redirectLocation); + RedirectUtils::redirect($redirectLocation); } - public static function validateUserSessionIsActive(bool $updateLastOperationTimestamp = true): bool - { - try { - $result = self::getAuthenticationProvider()->validateUserSessionIsActive($updateLastOperationTimestamp); - return $result->isAuthenticated; - } catch (\Exception $error) { - LoggerUtils::getAuthLogger()->debug('Error determining session authentication status.', ['exception' => $error]); - return false; - } + return $result; + } + + public static function validateUserSessionIsActive(bool $updateLastOperationTimestamp = true): bool + { + try { + $result = self::getAuthenticationProvider()->validateUserSessionIsActive($updateLastOperationTimestamp); + + return $result->isAuthenticated; + } catch (\Exception $error) { + LoggerUtils::getAuthLogger()->debug('Error determining session authentication status.', ['exception' => $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 + 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); + 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) { + if (!$result->isAuthenticated) { LoggerUtils::getAuthLogger()->debug( - 'Error determining session authentication status. Redirecting to login page.', - ['exception' => $error] + '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.', + ['exception' => $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 7e1a916786..3528d07b8a 100644 --- a/src/ChurchCRM/Authentication/AuthenticationProviders/APITokenAuthentication.php +++ b/src/ChurchCRM/Authentication/AuthenticationProviders/APITokenAuthentication.php @@ -1,62 +1,62 @@ currentUser; + } - class APITokenAuthentication implements IAuthenticationProvider + public function authenticate(AuthenticationRequest $AuthenticationRequest) { - /*** - * @var ChurchCRM\User - */ - private $currentUser; - - public function getCurrentUser() - { - return $this->currentUser; + 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(bool $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(bool $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 768c8603c0..cb818c9390 100644 --- a/src/ChurchCRM/Authentication/AuthenticationProviders/IAuthenticationProvider.php +++ b/src/ChurchCRM/Authentication/AuthenticationProviders/IAuthenticationProvider.php @@ -1,14 +1,18 @@ getQRCodeUrl( - SystemConfig::getValue('s2FAApplicationName'), - $username, - $secret - ); - $qrCode = new QrCode($g2faUrl); - $qrCode->setSize(300); - return $qrCode; - } + public static function getIsTwoFactorAuthSupported() + { + return SystemConfig::getBooleanValue('bEnable2FA') && KeyManager::getAreAllSecretsDefined(); + } - public function getCurrentUser() - { - return $this->currentUser; - } + 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 endSession() - { + public function getCurrentUser() + { + return $this->currentUser; + } - 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) + { + if (!($AuthenticationRequest instanceof LocalUsernamePasswordRequest || $AuthenticationRequest instanceof LocalTwoFactorTokenRequest)) { + throw new \Exception('Unable to process request as LocalUsernamePasswordRequest or LocalTwoFactorTokenRequest'); } - public function authenticate(AuthenticationRequest $AuthenticationRequest) - { - if (!($AuthenticationRequest instanceof LocalUsernamePasswordRequest || $AuthenticationRequest instanceof LocalTwoFactorTokenRequest)) { - throw new \Exception('Unable to process request as LocalUsernamePasswordRequest or LocalTwoFactorTokenRequest'); - } + $authenticationResult = new AuthenticationResult(); + $logCtx = ['username' => $AuthenticationRequest->username]; + if ($AuthenticationRequest instanceof LocalUsernamePasswordRequest) { + LoggerUtils::getAuthLogger()->debug('Processing local login', $logCtx); + // 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'); - $authenticationResult = new AuthenticationResult(); - $logCtx = ['username' => $AuthenticationRequest->username]; - if ($AuthenticationRequest instanceof LocalUsernamePasswordRequest) { - LoggerUtils::getAuthLogger()->debug('Processing local login', $logCtx); - // 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; - } elseif ($this->currentUser->isLocked()) { - // Block the login if a maximum login failure count has been reached - $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', $logCtx); - return $authenticationResult; - } elseif (!$this->currentUser->isPasswordValid($AuthenticationRequest->password)) { - // Does the password match? - - // 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. The account has been locked', $logCtx); - $lockedEmail = new LockedEmail($this->currentUser); - $lockedEmail->send(); - } - $authenticationResult->isAuthenticated = false; - $authenticationResult->message = gettext('Invalid login or password'); - LoggerUtils::getAuthLogger()->warning('Invalid login attempt', $logCtx); - 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', $logCtx); - 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', $logCtx); - return $authenticationResult; - } else { - $this->prepareSuccessfulLoginOperations(); - $authenticationResult->isAuthenticated = true; - LoggerUtils::getAuthLogger()->debug('User successfully logged in without 2FA', $logCtx); - 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', $logCtx); - 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', $logCtx); - return $authenticationResult; - } else { - LoggerUtils::getAuthLogger()->info('Invalid 2FA code provided by partially authenticated user', $logCtx); - $authenticationResult->isAuthenticated = false; - $authenticationResult->nextStepURL = SystemURLs::getRootPath() . '/session/two-factor'; - return $authenticationResult; - } - } - } + return $authenticationResult; + } elseif ($this->currentUser->isLocked()) { + // Block the login if a maximum login failure count has been reached + $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', $logCtx); - public function validateUserSessionIsActive(bool $updateLastOperationTimestamp): AuthenticationResult - { - $authenticationResult = new AuthenticationResult(); + return $authenticationResult; + } elseif (!$this->currentUser->isPasswordValid($AuthenticationRequest->password)) { + // Does the password match? - // First check to see if a `user` key exists on the session. - if (null === $this->currentUser) { + // 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. The account has been locked', $logCtx); + $lockedEmail = new LockedEmail($this->currentUser); + $lockedEmail->send(); + } $authenticationResult->isAuthenticated = false; - LoggerUtils::getAuthLogger()->debug('No active user session.'); + $authenticationResult->message = gettext('Invalid login or password'); + LoggerUtils::getAuthLogger()->warning('Invalid login attempt', $logCtx); + return $authenticationResult; - } - $logCtx = [ - 'username' => $this->currentUser->getUserName(), - 'userFullName' => $this->currentUser->getName(), - ]; - LoggerUtils::getAuthLogger()->debug('Processing session for user', $logCtx); - - // 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', - array_merge($logCtx, ['exception' => $exc]) - ); - AuthenticationManager::endSession(); + } 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', $logCtx); + 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', $logCtx); - // 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', $logCtx); - $authenticationResult->isAuthenticated = false; - return $authenticationResult; - } else if ($updateLastOperationTimestamp) { - $this->tLastOperationTimestamp = time(); - } + return $authenticationResult; + } else { + $this->prepareSuccessfulLoginOperations(); + $authenticationResult->isAuthenticated = true; + LoggerUtils::getAuthLogger()->debug('User successfully logged in without 2FA', $logCtx); + + 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', $logCtx); + + 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', $logCtx); - // 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', $logCtx); + return $authenticationResult; + } else { + LoggerUtils::getAuthLogger()->info('Invalid 2FA code provided by partially authenticated user', $logCtx); $authenticationResult->isAuthenticated = false; - $authenticationResult->nextStepURL = $this->getPasswordChangeURL(); + $authenticationResult->nextStepURL = SystemURLs::getRootPath().'/session/two-factor'; + + return $authenticationResult; } + } + } + + public function validateUserSessionIsActive(bool $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.'); - // Finally, if the above tests pass, this user "is authenticated" - $authenticationResult->isAuthenticated = true; - LoggerUtils::getAuthLogger()->debug('Session validated for user', $logCtx); + return $authenticationResult; + } + $logCtx = [ + 'username' => $this->currentUser->getUserName(), + 'userFullName' => $this->currentUser->getName(), + ]; + LoggerUtils::getAuthLogger()->debug('Processing session for user', $logCtx); + + // 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', + array_merge($logCtx, ['exception' => $exc]) + ); + 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', $logCtx); + $authenticationResult->isAuthenticated = false; + + return $authenticationResult; + } elseif ($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', $logCtx); + $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', $logCtx); + + return $authenticationResult; } } diff --git a/src/ChurchCRM/Authentication/AuthenticationResult.php b/src/ChurchCRM/Authentication/AuthenticationResult.php index 51799deb7d..4f0818702e 100644 --- a/src/ChurchCRM/Authentication/AuthenticationResult.php +++ b/src/ChurchCRM/Authentication/AuthenticationResult.php @@ -1,13 +1,11 @@ AffectedPassword = $OldOrNew; - } - public $AffectedPassword; + parent::__construct($PasswordChangeProblem); + $this->AffectedPassword = $OldOrNew; } + public $AffectedPassword; } diff --git a/src/ChurchCRM/Authentication/Requests/APITokenAuthenticationRequest.php b/src/ChurchCRM/Authentication/Requests/APITokenAuthenticationRequest.php index a2d8dda587..dedef7bbfe 100644 --- a/src/ChurchCRM/Authentication/Requests/APITokenAuthenticationRequest.php +++ b/src/ChurchCRM/Authentication/Requests/APITokenAuthenticationRequest.php @@ -1,14 +1,12 @@ APIToken = $APIToken; - } - public $APIToken; + $this->APIToken = $APIToken; } - + public $APIToken; } diff --git a/src/ChurchCRM/Authentication/Requests/AuthenticationRequest.php b/src/ChurchCRM/Authentication/Requests/AuthenticationRequest.php index 59fb5edc98..f79c77afee 100644 --- a/src/ChurchCRM/Authentication/Requests/AuthenticationRequest.php +++ b/src/ChurchCRM/Authentication/Requests/AuthenticationRequest.php @@ -1,12 +1,10 @@ TwoFACode = $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 ce86c30c0f..223e0c9d36 100644 --- a/src/ChurchCRM/Authentication/Requests/LocalUsernamePasswordRequest.php +++ b/src/ChurchCRM/Authentication/Requests/LocalUsernamePasswordRequest.php @@ -1,17 +1,15 @@ username = $username; - $this->password = $password; - } + public function __construct($username, $password) + { + $this->username = $username; + $this->password = $password; } - } diff --git a/src/ChurchCRM/Backup/BackupDownloader.php b/src/ChurchCRM/Backup/BackupDownloader.php index c31658d049..868107274b 100644 --- a/src/ChurchCRM/Backup/BackupDownloader.php +++ b/src/ChurchCRM/Backup/BackupDownloader.php @@ -10,8 +10,8 @@ class BackupDownloader { public static function downloadBackup($filename) { - $path = SystemURLs::getDocumentRoot() . "/tmp_attach/ChurchCRMBackups/$filename"; - LoggerUtils::getAppLogger()->info("Download requested for :" . $path); + $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); @@ -20,45 +20,46 @@ public static function downloadBackup($filename) switch ($ext) { case 'gz': header('Content-type: application/x-gzip'); - header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); + 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'] . '"'); + header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"'); break; case 'sql': header('Content-type: text/plain'); - header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); + 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'] . '"'); + header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"'); break; case 'zip': header('Content-type: application/zip'); - header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); + 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'] . '"'); + 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"); + 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"); + 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"); + FileSystemUtils::recursiveRemoveDirectory(SystemURLs::getDocumentRoot().'/tmp_attach/', true); + LoggerUtils::getAppLogger()->debug('Removed backup file from server filesystem'); } else { - $message = "Requested download does not exist: " . $path; + $message = 'Requested download does not exist: '.$path; LoggerUtils::getAppLogger()->error($message); + throw new \Exception($message, 500); } } diff --git a/src/ChurchCRM/Backup/BackupJob.php b/src/ChurchCRM/Backup/BackupJob.php index 2f6c26f46b..5512cdce4f 100644 --- a/src/ChurchCRM/Backup/BackupJob.php +++ b/src/ChurchCRM/Backup/BackupJob.php @@ -2,16 +2,16 @@ namespace ChurchCRM\Backup; +use ChurchCRM\Bootstrapper; use ChurchCRM\dto\SystemURLs; use ChurchCRM\Utils\LoggerUtils; +use Defuse\Crypto\File; use Exception; use Ifsnop\Mysqldump\Mysqldump; use PharData; -use RecursiveIteratorIterator; use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; use SplFileInfo; -use Defuse\Crypto\File; -use ChurchCRM\Bootstrapper; class BackupJob extends JobBase { @@ -19,60 +19,55 @@ class BackupJob extends JobBase private ?\SplFileInfo $BackupFile = null; /** - * - * @var Boolean + * @var bool */ private $IncludeExtraneousFiles; /** - * - * @var String + * @var string */ public $BackupDownloadFileName; /** - * - * @var Boolean + * @var bool */ public $shouldEncrypt; /** - * - * @var String + * @var string */ public $BackupPassword; - /** - * - * @param String $BaseName + * @param string $BaseName * @param BackupType $BackupType - * @param Boolean $IncludeExtraneousFiles + * @param bool $IncludeExtraneousFiles */ public function __construct($BaseName, $BackupType, $IncludeExtraneousFiles, $EncryptBackup, $BackupPassword) { $this->BackupType = $BackupType; - $this->TempFolder = $this->createEmptyTempFolder(); - $this->BackupFileBaseName = $this->TempFolder . '/' . $BaseName; + $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') . "'" + "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); + 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; + $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); @@ -80,7 +75,7 @@ public function copyToWebDAV($Endpoint, $Username, $Password) 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"); + LoggerUtils::getAppLogger()->debug('Beginning to send file'); $time = new \ChurchCRM\Utils\ExecutionTime(); $result = curl_exec($ch); if (curl_error($ch)) { @@ -90,36 +85,39 @@ public function copyToWebDAV($Endpoint, $Username, $Password) fclose($fh); if (isset($error_msg)) { - throw new \Exception("Error backing up to remote: " . $error_msg); + throw new \Exception('Error backing up to remote: '.$error_msg); } - LoggerUtils::getAppLogger()->debug("File send complete. Took: " . $time->getMilliseconds() . "ms"); + LoggerUtils::getAppLogger()->debug('File send complete. Took: '.$time->getMilliseconds().'ms'); } catch (\Exception $e) { - LoggerUtils::getAppLogger()->error("Error copying backup: " . $e); + LoggerUtils::getAppLogger()->error('Error copying backup: '.$e); } - LoggerUtils::getAppLogger()->info("Backup copy completed. Curl result: " . $result); + LoggerUtils::getAppLogger()->info('Backup copy completed. Curl result: '.$result); + return $result; } private function captureSQLFile(\SplFileInfo $SqlFilePath) { global $sSERVERNAME, $sDATABASE, $sUSER, $sPASSWORD; - LoggerUtils::getAppLogger()->debug("Beginning to backup database to: " . $SqlFilePath->getPathname()); + 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()); + LoggerUtils::getAppLogger()->debug('Finished backing up database to '.$SqlFilePath->getPathname()); } catch (\Exception $e) { - $message = "Failed to backup database to: " . $SqlFilePath->getPathname() . " Exception: " . $e; + $message = 'Failed to backup database to: '.$SqlFilePath->getPathname().' Exception: '.$e; LoggerUtils::getAppLogger()->error($message); + throw new Exception($message, 500); } } private function shouldBackupImageFile(SplFileInfo $ImageFile) { - $isExtraneousFile = strpos($ImageFile->getFileName(), "-initials") != false || - strpos($ImageFile->getFileName(), "-remote") != false || - strpos($ImageFile->getPathName(), "thumbnails") != false; + $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 } @@ -127,15 +125,15 @@ private function shouldBackupImageFile(SplFileInfo $ImageFile) private function createFullArchive() { $imagesAddedToArchive = []; - $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName . ".tar"); + $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.'.tar'); $phar = new PharData($this->BackupFile->getPathname()); - LoggerUtils::getAppLogger()->debug("Archive opened at: " . $this->BackupFile->getPathname()); + LoggerUtils::getAppLogger()->debug('Archive opened at: '.$this->BackupFile->getPathname()); $phar->startBuffering(); - $SqlFile = new \SplFileInfo($this->TempFolder . "/" . 'ChurchCRM-Database.sql'); + $SqlFile = new \SplFileInfo($this->TempFolder.'/'.'ChurchCRM-Database.sql'); $this->captureSQLFile($SqlFile); $phar->addFile($SqlFile, 'ChurchCRM-Database.sql'); - LoggerUtils::getAppLogger()->debug("Database added to archive"); + LoggerUtils::getAppLogger()->debug('Database added to archive'); $imageFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(SystemURLs::getImagesRoot())); foreach ($imageFiles as $imageFile) { if ($this->shouldBackupImageFile($imageFile)) { @@ -144,25 +142,25 @@ private function createFullArchive() array_push($imagesAddedToArchive, $imageFile->getRealPath()); } } - LoggerUtils::getAppLogger()->debug("Images files added to archive: " . join(";", $imagesAddedToArchive)); + LoggerUtils::getAppLogger()->debug('Images files added to archive: '.join(';', $imagesAddedToArchive)); $phar->stopBuffering(); - LoggerUtils::getAppLogger()->debug("Finished creating archive. Beginning to compress"); + LoggerUtils::getAppLogger()->debug('Finished creating archive. Beginning to compress'); $phar->compress(\Phar::GZ); - LoggerUtils::getAppLogger()->debug("Archive compressed; should now be a .gz file"); + 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); + 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('Temp Database backup deleted: '.$SqlFile); } private function createGZSql() { - $SqlFile = new \SplFileInfo($this->TempFolder . "/" . 'ChurchCRM-Database.sql'); + $SqlFile = new \SplFileInfo($this->TempFolder.'/'.'ChurchCRM-Database.sql'); $this->captureSQLFile($SqlFile); - $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName . '.sql.gz'); + $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.'.sql.gz'); $gzf = gzopen($this->BackupFile->getPathname(), 'w6'); gzwrite($gzf, file_get_contents($SqlFile->getPathname())); gzclose($gzf); @@ -171,20 +169,21 @@ private function createGZSql() private function encryptBackupFile() { - LoggerUtils::getAppLogger()->info("Encrypting backup file: " . $this->BackupFile); - $tempfile = new \SplFileInfo($this->BackupFile->getPathname() . "temp"); + 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"); + 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); + LoggerUtils::getAppLogger()->info('Beginning backup job. Type: '.$this->BackupType.'. BaseName: '.$this->BackupFileBaseName); if ($this->BackupType == BackupType::FULL_BACKUP) { $this->createFullArchive(); } elseif ($this->BackupType == BackupType::SQL) { - $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName . ".sql"); + $this->BackupFile = new \SplFileInfo($this->BackupFileBaseName.'.sql'); $this->captureSQLFile($this->BackupFile); } elseif ($this->BackupType == BackupType::GZSQL) { $this->createGZSql(); @@ -194,12 +193,13 @@ public function execute() } $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"); + 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"); + 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(); + $this->BackupDownloadFileName = $this->BackupFile->getFilename(); + return true; } } diff --git a/src/ChurchCRM/Backup/JobBase.php b/src/ChurchCRM/Backup/JobBase.php index a632b9e0d3..5e2550c145 100644 --- a/src/ChurchCRM/Backup/JobBase.php +++ b/src/ChurchCRM/Backup/JobBase.php @@ -19,14 +19,14 @@ class JobBase protected function createEmptyTempFolder() { // both backup and restore operations require a clean temporary working folder. Create it. - $TempFolder = SystemURLs::getDocumentRoot() . "/tmp_attach/ChurchCRMBackups"; + $TempFolder = SystemURLs::getDocumentRoot().'/tmp_attach/ChurchCRMBackups'; - LoggerUtils::getAppLogger()->debug("Removing temp folder tree at " . $TempFolder); + LoggerUtils::getAppLogger()->debug('Removing temp folder tree at '.$TempFolder); FileSystemUtils::recursiveRemoveDirectory($TempFolder, false); - LoggerUtils::getAppLogger()->debug("Creating temp folder at " . $TempFolder); + LoggerUtils::getAppLogger()->debug('Creating temp folder at '.$TempFolder); mkdir($TempFolder, 0750, true); - LoggerUtils::getAppLogger()->debug("Temp folder created"); + LoggerUtils::getAppLogger()->debug('Temp folder created'); return $TempFolder; } diff --git a/src/ChurchCRM/Backup/RestoreJob.php b/src/ChurchCRM/Backup/RestoreJob.php index bb0457dc6c..46f1726a0c 100644 --- a/src/ChurchCRM/Backup/RestoreJob.php +++ b/src/ChurchCRM/Backup/RestoreJob.php @@ -2,35 +2,32 @@ namespace ChurchCRM\Backup; -use ChurchCRM\dto\SystemURLs; use ChurchCRM\dto\SystemConfig; +use ChurchCRM\dto\SystemURLs; use ChurchCRM\FileSystemUtils; -use ChurchCRM\Utils\LoggerUtils; +use ChurchCRM\Service\SystemService; use ChurchCRM\SQLUtils; -use Exception; -use Propel\Runtime\Propel; -use PharData; use ChurchCRM\Utils\InputUtils; +use ChurchCRM\Utils\LoggerUtils; use Defuse\Crypto\File; -use ChurchCRM\Service\SystemService; +use Exception; +use PharData; +use Propel\Runtime\Propel; class RestoreJob extends JobBase { private \SplFileInfo $RestoreFile; /** - * - * @var Array + * @var array */ public $Messages = []; /** - * - * @var Boolean + * @var bool */ private $IsBackupEncrypted; /** - * - * @var String + * @var string */ private $restorePassword; @@ -42,54 +39,57 @@ private function isIncomingFileFailed() public function __construct() { - LoggerUtils::getAppLogger()->info("Beginning to process incoming archive for restoration"); + LoggerUtils::getAppLogger()->info('Beginning to process incoming archive for restoration'); if ($this->isIncomingFileFailed()) { - $message = "The selected file exceeds this servers maximum upload size of: " . SystemService::getMaxUploadFileSize(); + $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); + $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"); + 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"); + 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); + LoggerUtils::getAppLogger()->info('Decrypting file: '.$this->RestoreFile); $this->restorePassword = InputUtils::filterString($_POST['restorePassword']); - $tempfile = new \SplFileInfo($this->RestoreFile->getPathname() . "temp"); + $tempfile = new \SplFileInfo($this->RestoreFile->getPathname().'temp'); try { File::decryptFileWithPassword($this->RestoreFile, $tempfile, $this->restorePassword); rename($tempfile, $this->RestoreFile); - LoggerUtils::getAppLogger()->info("File decrypted"); + 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": + case 'gz': $basename = $this->RestoreFile->getBasename(); - if (substr($basename, strlen($basename) - 6, 6) == "tar.gz") { + if (substr($basename, strlen($basename) - 6, 6) == 'tar.gz') { $this->BackupType = BackupType::FULL_BACKUP; - } elseif (substr($basename, strlen($basename) - 6, 6) == "sql.gz") { + } elseif (substr($basename, strlen($basename) - 6, 6) == 'sql.gz') { $this->BackupType = BackupType::GZSQL; } break; - case "sql": + case 'sql': $this->BackupType = BackupType::SQL; break; } @@ -98,38 +98,38 @@ private function discoverBackupType() private function restoreSQLBackup($SQLFileInfo) { $connection = Propel::getConnection(); - LoggerUtils::getAppLogger()->debug("Restoring SQL file from: " . $SQLFileInfo); + LoggerUtils::getAppLogger()->debug('Restoring SQL file from: '.$SQLFileInfo); SQLUtils::sqlImport($SQLFileInfo, $connection); - LoggerUtils::getAppLogger()->debug("Finished restoring SQL table"); + LoggerUtils::getAppLogger()->debug('Finished restoring SQL table'); } private function restoreFullBackup() { - LoggerUtils::getAppLogger()->debug("Restoring full archive"); + LoggerUtils::getAppLogger()->debug('Restoring full archive'); $phar = new PharData($this->RestoreFile); - LoggerUtils::getAppLogger()->debug("Extracting " . $this->RestoreFile . " to " . $this->TempFolder); + LoggerUtils::getAppLogger()->debug('Extracting '.$this->RestoreFile.' to '.$this->TempFolder); $phar->extractTo($this->TempFolder); - LoggerUtils::getAppLogger()->debug("Finished extraction"); - $sqlFile = $this->TempFolder . "/ChurchCRM-Database.sql"; + LoggerUtils::getAppLogger()->debug('Finished extraction'); + $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"); + 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 { - throw new Exception(gettext("Backup archive does not contain a database") . ": " . $this->RestoreFile); + throw new Exception(gettext('Backup archive does not contain a database').': '.$this->RestoreFile); } - LoggerUtils::getAppLogger()->debug("Finished restoring full archive"); + LoggerUtils::getAppLogger()->debug('Finished restoring full archive'); } private function restoreGZSQL() { - LoggerUtils::getAppLogger()->debug("Decompressing gzipped SQL file: " . $this->RestoreFile); + 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'); + $SqlFile = new \SplFileInfo($this->TempFolder.'/'.'ChurchCRM-Database.sql'); $out_file = fopen($SqlFile, 'wb'); while (!gzeof($gzf)) { fwrite($out_file, gzread($gzf, $buffer_size)); @@ -145,16 +145,17 @@ 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"); + 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"); + LoggerUtils::getAppLogger()->debug('Reset System Settings for: bEnableExternalBackupTarget and sLastIntegrityCheckTimeStamp'); } public function execute() { - LoggerUtils::getAppLogger()->info("Executing restore job"); + LoggerUtils::getAppLogger()->info('Executing restore job'); + try { $this->decryptBackup(); switch ($this->BackupType) { @@ -169,9 +170,9 @@ public function execute() break; } $this->postRestoreCleanup(); - LoggerUtils::getAppLogger()->info("Finished executing restore job. Cleaning out temp folder."); + LoggerUtils::getAppLogger()->info('Finished executing restore job. Cleaning out temp folder.'); } catch (Exception $ex) { - LoggerUtils::getAppLogger()->error("Error restoring backup: " . $ex); + LoggerUtils::getAppLogger()->error('Error restoring backup: '.$ex); } $this->TempFolder = $this->createEmptyTempFolder(); } diff --git a/src/ChurchCRM/Config/Menu/Menu.php b/src/ChurchCRM/Config/Menu/Menu.php index de50943670..9571d1d92b 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 @@ -32,49 +32,50 @@ public static function getMenu() private static function buildMenuItems() { 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(), + '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,96 +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)) { $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'); + $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/MenuItem.php b/src/ChurchCRM/Config/Menu/MenuItem.php index 67e524e07b..46d8fb7764 100644 --- a/src/ChurchCRM/Config/Menu/MenuItem.php +++ b/src/ChurchCRM/Config/Menu/MenuItem.php @@ -15,7 +15,7 @@ class MenuItem private array $subItems = []; private array $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); } @@ -41,11 +41,13 @@ public function getURI() //Review SessionVar stuff if (!empty($this->uri)) { if (filter_var($this->uri, FILTER_VALIDATE_URL) === false) { - return SystemURLs::getRootPath() . "/" . $this->uri; + 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,6 +114,7 @@ public function isVisible() if ($this->hasPermission && (!empty($this->uri) || $this->hasVisibleSubMenus())) { return true; } + return false; } @@ -120,6 +125,7 @@ public function openMenu() return true; } } + return false; } @@ -128,6 +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 152b007309..779c148949 100644 --- a/src/ChurchCRM/Dashboard/ClassificationDashboardItem.php.php +++ b/src/ChurchCRM/Dashboard/ClassificationDashboardItem.php.php @@ -6,12 +6,12 @@ class ClassificationDashboardItem implements DashboardItemInterface { public static function getDashboardItemName() { - return "ClassificationBreakdown"; + return 'ClassificationBreakdown'; } public static function getDashboardItemValue() { - $data = []; + $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 @@ -27,6 +27,6 @@ public static function getDashboardItemValue() public static function shouldInclude($PageName) { - return $PageName == "PeopleDashboard.php"; // this ID would be found on all pages. + 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 97c1c1aed3..a383c9b792 100644 --- a/src/ChurchCRM/Dashboard/CurrentLocaleMetadata.php +++ b/src/ChurchCRM/Dashboard/CurrentLocaleMetadata.php @@ -2,14 +2,14 @@ namespace ChurchCRM\Dashboard; -use ChurchCRM\dto\SystemURLs; use ChurchCRM\Bootstrapper; +use ChurchCRM\dto\SystemURLs; class CurrentLocaleMetadata implements DashboardItemInterface { public static function getDashboardItemName() { - return "PageLocale"; + return 'PageLocale'; } public static function shouldInclude($PageName) @@ -20,20 +20,20 @@ public static function shouldInclude($PageName) public static function getDashboardItemValue() { $localeInfo = Bootstrapper::getCurrentLocale(); - $data["name"] = $localeInfo->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, 512, JSON_THROW_ON_ERROR); - $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 ae1f29e745..61e5943f5c 100644 --- a/src/ChurchCRM/Dashboard/DashboardItemInterface.php +++ b/src/ChurchCRM/Dashboard/DashboardItemInterface.php @@ -4,12 +4,12 @@ interface DashboardItemInterface { - //must be all one word - no spaces + //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. + //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 + // 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 5ee8c6374e..6667994682 100644 --- a/src/ChurchCRM/Dashboard/EventsMenuItems.php +++ b/src/ChurchCRM/Dashboard/EventsMenuItems.php @@ -12,15 +12,15 @@ class EventsMenuItems implements DashboardItemInterface { public static function getDashboardItemName() { - return "EventsCounters"; + return 'EventsCounters'; } public static function getDashboardItemValue() { $activeEvents = [ - "Events" => self::getNumberEventsOfToday(), - "Birthdays" => self::getNumberBirthDates(), - "Anniversaries" => self::getNumberAnniversaries() + 'Events' => self::getNumberEventsOfToday(), + 'Birthdays' => self::getNumberBirthDates(), + 'Anniversaries' => self::getNumberAnniversaries(), ]; return $activeEvents; @@ -33,12 +33,12 @@ public static function shouldInclude($PageName) 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 */ - ->_or()->where("event_start>='" . $start_date . "' AND event_end <= '" . $end_date . "'") /* the events of the day */ + ->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(); } @@ -57,8 +57,8 @@ 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 356febbdfa..452fc4cd5d 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 { @@ -27,27 +27,26 @@ public function __construct($toAddresses) // use .html instead of .mustache for default template extension $options = ['extension' => '.html']; - $this->mustache = new Mustache_Engine(['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'; } } @@ -56,6 +55,7 @@ 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. } @@ -76,31 +76,31 @@ protected function buildMessage() protected function getMustacheTemplateName() { - return "BaseEmail"; + return 'BaseEmail'; } 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); } @@ -109,6 +109,8 @@ protected function getCommonTokens() } abstract public function getTokens(); + abstract protected function getFullURL(); + abstract protected function getButtonText(); } diff --git a/src/ChurchCRM/Emails/notifications/NewPersonOrFamilyEmail.php b/src/ChurchCRM/Emails/notifications/NewPersonOrFamilyEmail.php index b52be19b2d..66588c67f2 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 { @@ -16,7 +15,7 @@ public function __construct($RelatedObject) $this->relatedObject = $RelatedObject; $toAddresses = []; - $recipientPeople = explode(",", SystemConfig::getValue("sNewPersonNotificationRecipientIDs")); + $recipientPeople = explode(',', SystemConfig::getValue('sNewPersonNotificationRecipientIDs')); foreach ($recipientPeople as $PersonID) { $Person = PersonQuery::create()->findOneById($PersonID); @@ -29,7 +28,7 @@ public function __construct($RelatedObject) } 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()); } @@ -37,39 +36,39 @@ public function __construct($RelatedObject) protected function getSubSubject() { if (get_class($this->relatedObject) == \ChurchCRM\Person::class) { - return gettext("New Person Added"); - } else if (get_class($this->relatedObject) == \ChurchCRM\Family::class) { - return gettext("New Family Added"); + return gettext('New Person Added'); + } elseif (get_class($this->relatedObject) == \ChurchCRM\Family::class) { + return gettext('New Family Added'); } } public function getTokens() { - $myTokens = [ - "toName" => gettext("Church Greeter") + $myTokens = [ + 'toName' => gettext('Church Greeter'), ]; if (get_class($this->relatedObject) == \ChurchCRM\Family::class) { - /* @var $family 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['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"); + $myTokens['FamilyAddress'] = $family->getAddress(); + $myTokens['IncludeDataInNewFamilyNotifications'] = SystemConfig::getBooleanValue('IncludeDataInNewPersonNotifications'); } elseif (get_class($this->relatedObject) == \ChurchCRM\Person::class) { - /* @var $person ChurchCRM\Person */ + /* @var $person ChurchCRM\Person */ $person = $this->relatedObject; - $myTokens['body'] = gettext("New Person Added") . "\r\n" . - gettext("Person Name") . ": " . $person->getFullName(); + $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['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); } @@ -77,18 +76,18 @@ public function getTokens() protected function getFullURL() { if (get_class($this->relatedObject) == \ChurchCRM\Family::class) { - return SystemURLs::getURL() . "/v2/family/" . $this->relatedObject->getId(); + return SystemURLs::getURL().'/v2/family/'.$this->relatedObject->getId(); } elseif (get_class($this->relatedObject) == \ChurchCRM\Person::class) { - return SystemURLs::getURL() . "/PersonView.php?PersonID=" . $this->relatedObject->getId(); + return SystemURLs::getURL().'/PersonView.php?PersonID='.$this->relatedObject->getId(); } } protected function getButtonText() { if (get_class($this->relatedObject) == \ChurchCRM\Family::class) { - return gettext("View Family Page"); + return gettext('View Family Page'); } elseif (get_class($this->relatedObject) == \ChurchCRM\Person::class) { - return gettext("View Person Page"); + return gettext('View Person Page'); } } } diff --git a/src/ChurchCRM/Emails/notifications/NotificationEmail.php b/src/ChurchCRM/Emails/notifications/NotificationEmail.php index a8017d5ede..fce5ed046e 100644 --- a/src/ChurchCRM/Emails/notifications/NotificationEmail.php +++ b/src/ChurchCRM/Emails/notifications/NotificationEmail.php @@ -12,22 +12,23 @@ 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() { - $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); } diff --git a/src/ChurchCRM/Emails/users/AccountDeletedEmail.php b/src/ChurchCRM/Emails/users/AccountDeletedEmail.php index d68bf885c1..43324292a5 100644 --- a/src/ChurchCRM/Emails/users/AccountDeletedEmail.php +++ b/src/ChurchCRM/Emails/users/AccountDeletedEmail.php @@ -6,11 +6,11 @@ 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 63dc79a905..7d0e367784 100644 --- a/src/ChurchCRM/Emails/users/BaseUserEmail.php +++ b/src/ChurchCRM/Emails/users/BaseUserEmail.php @@ -12,13 +12,14 @@ abstract class BaseUserEmail extends BaseEmail /** * 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()); } @@ -27,17 +28,18 @@ abstract protected function getSubSubject(); 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); } protected function getFullURL() { - return SystemURLs::getURL() . "/session/begin?username=" . $this->user->getUserName(); + return SystemURLs::getURL().'/session/begin?username='.$this->user->getUserName(); } protected function getButtonText() diff --git a/src/ChurchCRM/Emails/users/LockedEmail.php b/src/ChurchCRM/Emails/users/LockedEmail.php index 4329581e52..134604ac50 100644 --- a/src/ChurchCRM/Emails/users/LockedEmail.php +++ b/src/ChurchCRM/Emails/users/LockedEmail.php @@ -6,11 +6,11 @@ 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 88b1adc66c..d96e2ca47d 100644 --- a/src/ChurchCRM/Emails/users/NewAccountEmail.php +++ b/src/ChurchCRM/Emails/users/NewAccountEmail.php @@ -14,19 +14,20 @@ public function __construct($user, $password) 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 5881d2db4a..ebc363a488 100644 --- a/src/ChurchCRM/Emails/users/PasswordChangeEmail.php +++ b/src/ChurchCRM/Emails/users/PasswordChangeEmail.php @@ -14,19 +14,20 @@ public function __construct($user, $password) 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 0e29ae9ecb..749a20012d 100644 --- a/src/ChurchCRM/Emails/users/ResetPasswordEmail.php +++ b/src/ChurchCRM/Emails/users/ResetPasswordEmail.php @@ -14,19 +14,20 @@ public function __construct($user, $password) 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 f9d23a36a7..c931efa54b 100644 --- a/src/ChurchCRM/Emails/users/ResetPasswordTokenEmail.php +++ b/src/ChurchCRM/Emails/users/ResetPasswordTokenEmail.php @@ -16,17 +16,17 @@ public function __construct($user, $token) 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').':'; } protected function getFullURL() { - return SystemURLs::getURL() . "/session/forgot-password/set/" . $this->token; + return SystemURLs::getURL().'/session/forgot-password/set/'.$this->token; } protected function getButtonText() diff --git a/src/ChurchCRM/Emails/users/UnlockedEmail.php b/src/ChurchCRM/Emails/users/UnlockedEmail.php index 6e9eccb801..157762e34f 100644 --- a/src/ChurchCRM/Emails/users/UnlockedEmail.php +++ b/src/ChurchCRM/Emails/users/UnlockedEmail.php @@ -6,11 +6,11 @@ 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 901ba92430..ce142752af 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); } protected function getFullURL() { - return SystemURLs::getURL() . "/external/verify/" . $this->token->getToken(); + return SystemURLs::getURL().'/external/verify/'.$this->token->getToken(); } protected function getButtonText() { - return gettext("Verify"); + return gettext('Verify'); } } diff --git a/src/ChurchCRM/FileSystemUtils.php b/src/ChurchCRM/FileSystemUtils.php index 4ef1176e3f..f68566f874 100644 --- a/src/ChurchCRM/FileSystemUtils.php +++ b/src/ChurchCRM/FileSystemUtils.php @@ -1,82 +1,84 @@ 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(string $src, string $dest) - { - $logger = LoggerUtils::getAppLogger(); + public static function moveDir(string $src, string $dest) + { + $logger = LoggerUtils::getAppLogger(); - if (!is_dir($src)) { - $msg = 'provided src path is not a directory: ' . $src; - $logger->error($msg); - throw new \Exception($msg); - } - if (!is_dir($dest)) { - $msg = 'provided dest path is not a directory: ' . $dest; - $logger->error($msg); - throw new \Exception($msg); - } + if (!is_dir($src)) { + $msg = 'provided src path is not a directory: '.$src; + $logger->error($msg); - $logger->info('Moving files: ' . $src . ' to ' . $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"); - } + throw new \Exception($msg); + } + if (!is_dir($dest)) { + $msg = 'provided dest path is not a directory: '.$dest; + $logger->error($msg); + + throw new \Exception($msg); + } + + $logger->info('Moving files: '.$src.' to '.$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 4a902bcce6..c5cba9ac25 100644 --- a/src/ChurchCRM/Interfaces/SystemCalendar.php +++ b/src/ChurchCRM/Interfaces/SystemCalendar.php @@ -5,11 +5,18 @@ 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(); } diff --git a/src/ChurchCRM/KeyManager.php b/src/ChurchCRM/KeyManager.php index 1c96c57f5f..eedeeef529 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'); $this->writeAt(SystemConfig::getValue('leftX'), $curY, SystemConfig::getValue('sChurchAddress')); $curY += SystemConfig::getValue('incrementY'); - $this->writeAt(SystemConfig::getValue('leftX'), $curY, SystemConfig::getValue('sChurchCity') . ', ' . SystemConfig::getValue('sChurchState') . ' ' . SystemConfig::getValue('sChurchZip')); + $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)); @@ -126,19 +126,21 @@ public function startLetterPage($fam_ID, $fam_Name, $fam_Address1, $fam_Address2 $this->writeAt(SystemConfig::getValue('leftX'), $curY, $fam_Address2); $curY += SystemConfig::getValue('incrementY'); } - $this->writeAt(SystemConfig::getValue('leftX'), $curY, $fam_City . ', ' . $fam_State . ' ' . $fam_Zip); + $this->writeAt(SystemConfig::getValue('leftX'), $curY, $fam_City.', '.$fam_State.' '.$fam_Zip); $curY += SystemConfig::getValue('incrementY'); if ($fam_Country != '' && $fam_Country != SystemConfig::getValue('sDefaultCountry')) { $this->writeAt(SystemConfig::getValue('leftX'), $curY, $fam_Country); $curY += SystemConfig::getValue('incrementY'); } $curY += 5.0; // mm to get away from the second window + return $curY; } public function makeSalutation($famID) { $family = FamilyQuery::create()->findPk($famID); + return $family->getSalutation(); } } diff --git a/src/ChurchCRM/Reports/PDF_AddressReport.php b/src/ChurchCRM/Reports/PDF_AddressReport.php index 72a1022944..ec49bd5940 100644 --- a/src/ChurchCRM/Reports/PDF_AddressReport.php +++ b/src/ChurchCRM/Reports/PDF_AddressReport.php @@ -110,7 +110,7 @@ public function checkLines($numlines) // Number of lines is only for the $text parameter public function addRecord($fam_Str, $sLuStr, $sErrStr) { - $sLuStr .= "\n" . $sErrStr; + $sLuStr .= "\n".$sErrStr; $numlines1 = $this->numLinesInFpdfCell(90, $fam_Str); $numlines2 = $this->numLinesInFpdfCell(90, $sLuStr); diff --git a/src/ChurchCRM/Reports/PDF_Attendance.php b/src/ChurchCRM/Reports/PDF_Attendance.php index e3a19e7cb8..72b10e39e9 100644 --- a/src/ChurchCRM/Reports/PDF_Attendance.php +++ b/src/ChurchCRM/Reports/PDF_Attendance.php @@ -15,13 +15,13 @@ class PdfAttendance 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() @@ -86,41 +86,40 @@ public function drawAttendanceCalendar( $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()); + $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) + // 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]; + $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++] = ''; + $NameList[$aNameCount] = ' '; + $imgList[$aNameCount++] = ''; } $numMembers = count($NameList); $nPages = ceil($numMembers / $MaxLinesPerPage); - // echo "nPages = {$nPages} \n\r"; // // Main loop which draws each page @@ -141,20 +140,20 @@ public function drawAttendanceCalendar( $yDays = $yTop + $yIncrement; $y = $yDays + $yIncrement; // - // put title on the page + // 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 + // calculate the starting and ending rows for the page // $pRowStart = $p * $MaxLinesPerPage; - $pRowEnd = min(((($p + 1) * $MaxLinesPerPage)), $numMembers); + $pRowEnd = min(($p + 1) * $MaxLinesPerPage, $numMembers); // echo "pRowStart = {$pRowStart} and pRowEnd= {$pRowEnd}\n\r"; // - // Write the names down the page and draw lines between + // Write the names down the page and draw lines between // $this->SetLineWidth(0.25); @@ -173,7 +172,6 @@ public function drawAttendanceCalendar( $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])) { [$width, $height] = getimagesize($imgList[$row]); $factor = $yIncrement / $height; @@ -187,7 +185,7 @@ public function drawAttendanceCalendar( $y += $yIncrement; } // - // write a totals text at the bottom + // write a totals text at the bottom // $this->SetFont('Times', 'B', $fontTitleNormal); $this->writeAt($nameX, $y + 1, gettext('Totals')); @@ -195,7 +193,7 @@ public function drawAttendanceCalendar( $bottomY = $y + $yIncrement; // - // Paint the calendar grid + // Paint the calendar grid // $dayCounter = 0; $monthCounter = 0; @@ -253,7 +251,7 @@ public function drawAttendanceCalendar( $aLightVerticalX[$lightVerticalXCnt++] = $dayX; } $dayX += $dayWid; - ++$dayCounter; + $dayCounter++; // if ($tWhichSunday == $tLastSunday) $doneFlag = true; // @@ -264,7 +262,7 @@ public function drawAttendanceCalendar( $doneFlag = true; } - // Increment the date by one week + // Increment the date by one week // $sundayDay = date('d', $dWhichSunday); $sundayMonth = date('m', $dWhichSunday); @@ -277,17 +275,17 @@ public function drawAttendanceCalendar( $rightEdgeX = $dayX; - // Draw vertical lines now that we know how far down the list goes + // 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); + // 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; + // 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 + // 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); @@ -303,7 +301,7 @@ public function drawAttendanceCalendar( $this->SetLineWidth(0.5); $this->Line($dayX, $yMonths, $dayX, $bottomY); - // Fill the no-school days + // Fill the no-school days $this->SetFillColor(200, 200, 200); $this->SetLineWidth(0.25); for ($i = 0; $i < count($aNoSchoolX); $i++) { @@ -323,7 +321,7 @@ public function drawAttendanceCalendar( $this->Line($nameX, $yBottom, $rightEdgeX, $yBottom); $this->Line($nameX, $yBottom + $yIncrement, $rightEdgeX, $yBottom + $yIncrement); // - // add in horizontal lines between names + // add in horizontal lines between names // $y = $yTop; for ($s = $pRowStart; $s < $pRowEnd + 4; $s++) { diff --git a/src/ChurchCRM/Reports/PDF_CertificatesReport.php b/src/ChurchCRM/Reports/PDF_CertificatesReport.php index 33998c7255..d2631278dc 100644 --- a/src/ChurchCRM/Reports/PDF_CertificatesReport.php +++ b/src/ChurchCRM/Reports/PDF_CertificatesReport.php @@ -21,12 +21,12 @@ public function addPage($orientation = '', $format = '', $rotation = 0) parent::addPage($orientation, $format, $rotation); $this->SetFont('Times', 'B', 16); - $this->Write(8, $fr_title . "\n"); + $this->Write(8, $fr_title."\n"); $curY += 8; - $this->Write(8, $fr_description . "\n\n"); + $this->Write(8, $fr_description."\n\n"); $curY += 8; $this->SetFont('Times', 'B', 36); - $this->Write(8, gettext('Certificate of Ownership') . "\n\n"); + $this->Write(8, gettext('Certificate of Ownership')."\n\n"); $curY += 8; $this->SetFont('Times', '', 10); } diff --git a/src/ChurchCRM/Reports/PDF_DepositReport.php b/src/ChurchCRM/Reports/PDF_DepositReport.php index 6ef7d5185e..86ccff3633 100644 --- a/src/ChurchCRM/Reports/PDF_DepositReport.php +++ b/src/ChurchCRM/Reports/PDF_DepositReport.php @@ -8,8 +8,8 @@ class PdfDepositReport extends ChurchInfoReport public $_Char_Size = 10; // Character size public $_Font = 'Courier'; - // Sets the character size - // This changes the line height too + // Sets the character size + // This changes the line height too public function setCharSize($pt) { if ($pt > 3) { @@ -26,7 +26,7 @@ public function printRightJustified($x, $y, $str) $this->Write(8, $str); } - // Constructor + // Constructor public function __construct() { parent::__construct('P', 'mm', $this->paperFormat); diff --git a/src/ChurchCRM/Reports/PDF_Directory.php b/src/ChurchCRM/Reports/PDF_Directory.php index e8a8c2692b..621476836d 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 PdfDirectory extends ChurchInfoReport { @@ -38,7 +38,7 @@ public function header() //Move to the right $this->SetX($this->_Margin_Left); //Framed title - $this->Cell($this->w - ($this->_Margin_Left * 2), 10, SystemConfig::getValue('sChurchName') . ' - ' . gettext('Directory'), 1, 0, 'C'); + $this->Cell($this->w - ($this->_Margin_Left * 2), 10, SystemConfig::getValue('sChurchName').' - '.gettext('Directory'), 1, 0, 'C'); $this->SetY(25); } } @@ -57,7 +57,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 } } @@ -74,10 +74,10 @@ public function titlePage() //Line break $this->Ln(5); //Move to the right - $this->MultiCell(197, 10, "\n\n\n" . SystemConfig::getValue('sChurchName') . "\n\n" . gettext('Directory') . "\n\n", 0, 'C'); + $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")); - $this->MultiCell(197, 10, $today . "\n\n", 0, 'C'); + $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')); $this->MultiCell(197, 10, $sContact, 0, 'C'); @@ -202,7 +202,7 @@ public function addHeader($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) ; @@ -218,7 +218,7 @@ public function printName($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); @@ -233,7 +233,7 @@ public function sGetCustomString($rsCustomFields, $aRow) $numCustomFields = mysqli_num_rows($rsCustomFields); if ($numCustomFields > 0) { extract($aRow); - $sSQL = 'SELECT * FROM person_custom WHERE per_ID = ' . $per_ID; + $sSQL = 'SELECT * FROM person_custom WHERE per_ID = '.$per_ID; $rsCustomData = RunQuery($sSQL); $aCustomData = mysqli_fetch_array($rsCustomData, MYSQLI_BOTH); $numCustomData = mysqli_num_rows($rsCustomData); @@ -241,13 +241,13 @@ public function sGetCustomString($rsCustomFields, $aRow) $OutStr = ''; while ($rowCustomField = mysqli_fetch_array($rsCustomFields, MYSQLI_BOTH)) { extract($rowCustomField); - $sCustom = 'bCustom' . $custom_Order; + $sCustom = 'bCustom'.$custom_Order; if ($this->_Custom[$custom_Order]) { $currentFieldData = displayCustomField($type_ID, $aCustomData[$custom_Field], $custom_Special); // $currentFieldData = trim($aCustomData[$custom_Field]); if ($currentFieldData != '') { - $OutStr .= ' ' . $custom_Name . ': ' . $currentFieldData .= "\n"; + $OutStr .= ' '.$custom_Name.': '.$currentFieldData .= "\n"; } } } @@ -261,8 +261,9 @@ 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 MiscUtils::formatBirthDate($per_BirthYear, $per_BirthMonth, $per_BirthDay, '/', $per_Flags); } + return ''; } @@ -287,28 +288,28 @@ public function sGetFamilyString($aRow) $sFamilyStr .= $fam_Address1; } if (strlen($fam_Address2)) { - $sFamilyStr .= ' ' . $fam_Address2; + $sFamilyStr .= ' '.$fam_Address2; } $sFamilyStr .= "\n"; if (strlen($fam_City)) { - $sFamilyStr .= $fam_City . ', ' . $fam_State . ' ' . $fam_Zip . "\n"; + $sFamilyStr .= $fam_City.', '.$fam_State.' '.$fam_Zip."\n"; } } if ($bDirFamilyPhone && strlen($fam_HomePhone)) { - $sFamilyStr .= ' ' . gettext('Phone') . ': ' . ExpandPhoneNumber($fam_HomePhone, $fam_Country, $bWierd) . "\n"; + $sFamilyStr .= ' '.gettext('Phone').': '.ExpandPhoneNumber($fam_HomePhone, $fam_Country, $bWierd)."\n"; } if ($bDirFamilyWork && strlen($fam_WorkPhone)) { - $sFamilyStr .= ' ' . gettext('Work') . ': ' . ExpandPhoneNumber($fam_WorkPhone, $fam_Country, $bWierd) . "\n"; + $sFamilyStr .= ' '.gettext('Work').': '.ExpandPhoneNumber($fam_WorkPhone, $fam_Country, $bWierd)."\n"; } if ($bDirFamilyCell && strlen($fam_CellPhone)) { - $sFamilyStr .= ' ' . gettext('Cell') . ': ' . ExpandPhoneNumber($fam_CellPhone, $fam_Country, $bWierd) . "\n"; + $sFamilyStr .= ' '.gettext('Cell').': '.ExpandPhoneNumber($fam_CellPhone, $fam_Country, $bWierd)."\n"; } if ($bDirFamilyEmail && strlen($fam_Email)) { - $sFamilyStr .= ' ' . gettext('Email') . ': ' . $fam_Email . "\n"; + $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; @@ -337,54 +338,54 @@ public function sGetHeadString($rsCustomFields, $aHead) // First time build with last name, second time append spouse name. if (strlen($this->sRecordName)) { - $this->sRecordName .= ' ' . gettext('and') . ' ' . $per_FirstName; + $this->sRecordName .= ' '.gettext('and').' '.$per_FirstName; if ($bDifferentLastName) { - $this->sRecordName .= ' ' . $per_LastName; + $this->sRecordName .= ' '.$per_LastName; } if (strlen($per_Suffix)) { - $this->sRecordName .= ' ' . $per_Suffix; + $this->sRecordName .= ' '.$per_Suffix; } } else { - $this->sRecordName = $this->sLastName . ', ' . $per_FirstName; + $this->sRecordName = $this->sLastName.', '.$per_FirstName; if ($bDifferentLastName) { - $this->sRecordName .= ' ' . $per_LastName; + $this->sRecordName .= ' '.$per_LastName; } if (strlen($per_Suffix)) { - $this->sRecordName .= ' ' . $per_Suffix; + $this->sRecordName .= ' '.$per_Suffix; } } $sHeadStr .= $per_FirstName; if ($bDifferentLastName) { - $sHeadStr .= ' ' . $per_LastName; + $sHeadStr .= ' '.$per_LastName; } if (strlen($per_Suffix)) { - $sHeadStr .= ' ' . $per_Suffix; + $sHeadStr .= ' '.$per_Suffix; } $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); if ($bDirPersonalPhone && strlen($per_HomePhone)) { $TempStr = ExpandPhoneNumber($per_HomePhone, $sCountry, $bWierd); - $sHeadStr .= ' ' . gettext('Phone') . ': ' . $TempStr .= "\n"; + $sHeadStr .= ' '.gettext('Phone').': '.$TempStr .= "\n"; } if ($bDirPersonalWork && strlen($per_WorkPhone)) { $TempStr = ExpandPhoneNumber($per_WorkPhone, $sCountry, $bWierd); - $sHeadStr .= ' ' . gettext('Work') . ': ' . $TempStr .= "\n"; + $sHeadStr .= ' '.gettext('Work').': '.$TempStr .= "\n"; } if ($bDirPersonalCell && strlen($per_CellPhone)) { $TempStr = ExpandPhoneNumber($per_CellPhone, $sCountry, $bWierd); - $sHeadStr .= ' ' . gettext('Cell') . ': ' . $TempStr .= "\n"; + $sHeadStr .= ' '.gettext('Cell').': '.$TempStr .= "\n"; } if ($bDirPersonalEmail && strlen($per_Email)) { - $sHeadStr .= ' ' . gettext('Email') . ': ' . $per_Email .= "\n"; + $sHeadStr .= ' '.gettext('Email').': '.$per_Email .= "\n"; } if ($bDirPersonalWorkEmail && strlen($per_WorkEmail)) { - $sHeadStr .= ' ' . gettext('Work/Other Email') . ': ' . $per_WorkEmail .= "\n"; + $sHeadStr .= ' '.gettext('Work/Other Email').': '.$per_WorkEmail .= "\n"; } $sHeadStr .= $this->sGetCustomString($rsCustomFields, $aHead); @@ -415,33 +416,33 @@ public function sGetMemberString($aRow) // Check to see if family member has different last name if (strlen($per_LastName) && ($per_LastName != $this->sLastName)) { - $sMemberStr .= ' ' . $per_LastName; + $sMemberStr .= ' '.$per_LastName; } if (strlen($per_Suffix)) { - $sMemberStr .= ' ' . $per_Suffix; + $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); if ($bDirPersonalPhone && strlen($per_HomePhone)) { $TempStr = ExpandPhoneNumber($per_HomePhone, $sCountry, $bWierd); - $sMemberStr .= ' ' . gettext('Phone') . ': ' . $TempStr .= "\n"; + $sMemberStr .= ' '.gettext('Phone').': '.$TempStr .= "\n"; } if ($bDirPersonalWork && strlen($per_WorkPhone)) { $TempStr = ExpandPhoneNumber($per_WorkPhone, $sCountry, $bWierd); - $sMemberStr .= ' ' . gettext('Work') . ': ' . $TempStr .= "\n"; + $sMemberStr .= ' '.gettext('Work').': '.$TempStr .= "\n"; } if ($bDirPersonalCell && strlen($per_CellPhone)) { $TempStr = ExpandPhoneNumber($per_CellPhone, $sCountry, $bWierd); - $sMemberStr .= ' ' . gettext('Cell') . ': ' . $TempStr .= "\n"; + $sMemberStr .= ' '.gettext('Cell').': '.$TempStr .= "\n"; } if ($bDirPersonalEmail && strlen($per_Email)) { - $sMemberStr .= ' ' . gettext('Email') . ': ' . $per_Email .= "\n"; + $sMemberStr .= ' '.gettext('Email').': '.$per_Email .= "\n"; } if ($bDirPersonalWorkEmail && strlen($per_WorkEmail)) { - $sMemberStr .= ' ' . gettext('Work/Other Email') . ': ' . $per_WorkEmail .= "\n"; + $sMemberStr .= ' '.gettext('Work/Other Email').': '.$per_WorkEmail .= "\n"; } return $sMemberStr; @@ -453,13 +454,13 @@ public function addRecord($sName, $text, $numlines, $fid, $pid) $dirimg = ''; if ($fid !== null) { $family = FamilyQuery::create()->findOneById($fid); - if ($family && !($family->getPhoto()->isInitials()) && file_exists($family->getPhoto()->getPhotoURI())) { + if ($family && !$family->getPhoto()->isInitials() && file_exists($family->getPhoto()->getPhotoURI())) { $dirimg = $family->getPhoto()->getPhotoURI(); } } if ($pid !== null) { $person = PersonQuery::create()->findOneById($pid); - if ($person && !($person->getPhoto()->isInitials()) && file_exists($person->getPhoto()->getPhotoURI())) { + if ($person && !$person->getPhoto()->isInitials() && file_exists($person->getPhoto()->getPhotoURI())) { $dirimg = $person->getPhoto()->getPhotoURI(); } } diff --git a/src/ChurchCRM/Reports/PDF_GroupDirectory.php b/src/ChurchCRM/Reports/PDF_GroupDirectory.php index 37cdec1338..0c212b0290 100644 --- a/src/ChurchCRM/Reports/PDF_GroupDirectory.php +++ b/src/ChurchCRM/Reports/PDF_GroupDirectory.php @@ -26,9 +26,9 @@ public function header() //Move to the right $this->Cell(10); //Framed title - $sTitle = $sGroupName . ' - ' . gettext('Group Directory'); + $sTitle = $sGroupName.' - '.gettext('Group Directory'); if (strlen($sRoleName)) { - $sTitle .= ' (' . $sRoleName . ')'; + $sTitle .= ' ('.$sRoleName.')'; } $this->Cell(197, 10, $sTitle, 1, 0, 'C'); } @@ -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 @@ -87,20 +87,20 @@ public function checkLines($numlines) // This function prints out the heading when a letter // changes. -/* function addHeader($sLetter) - { - $this->checkLines(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 addHeader($sLetter) + { + $this->checkLines(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 printName($sName) diff --git a/src/ChurchCRM/Reports/PDF_Label.php b/src/ChurchCRM/Reports/PDF_Label.php index 07e303029e..32e955a8a9 100644 --- a/src/ChurchCRM/Reports/PDF_Label.php +++ b/src/ChurchCRM/Reports/PDF_Label.php @@ -64,14 +64,14 @@ class PdfLabel extends ChurchInfoReport // List of all Avery formats public $_Avery_Labels = [ 'Tractor' => ['name' => 'Tractor', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 6.5, 'marginTop' => 5, 'NX' => 1, 'NY' => 10, 'SpaceX' => 3.175, 'SpaceY' => 0, 'width' => 120, 'height' => 26.5, 'font-size' => 12], - '5160' => ['name' => '5160', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 4, 'marginTop' => 11.5, 'NX' => 3, 'NY' => 10, 'SpaceX' => 3.175, 'SpaceY' => 0, 'width' => 66.675, 'height' => 25.4, 'font-size' => 11], - '5161' => ['name' => '5161', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 1, 'marginTop' => 10.7, 'NX' => 2, 'NY' => 10, 'SpaceX' => 3.967, 'SpaceY' => 0, 'width' => 101.6, 'height' => 25.4, 'font-size' => 11], - '5162' => ['name' => '5162', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 4, 'marginTop' => 20.224, 'NX' => 2, 'NY' => 7, 'SpaceX' => 4.762, 'SpaceY' => 0, 'width' => 100.807, 'height' => 34, 'font-size' => 12], - '5163' => ['name' => '5163', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 1.762, 'marginTop' => 10.7, 'NX' => 2, 'NY' => 5, 'SpaceX' => 3.175, 'SpaceY' => 0, 'width' => 101.6, 'height' => 50.8, 'font-size' => 8], - '5164' => ['name' => '5164', 'paper-size' => 'letter', 'metric' => 'in', 'marginLeft' => 0.148, 'marginTop' => 0.5, 'NX' => 2, 'NY' => 3, 'SpaceX' => 0.2031, 'SpaceY' => 0, 'width' => 4.0, 'height' => 3.33, 'font-size' => 12], - '8600' => ['name' => '8600', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 7.1, 'marginTop' => 19, 'NX' => 3, 'NY' => 10, 'SpaceX' => 9.5, 'SpaceY' => 3.1, 'width' => 66.6, 'height' => 25.4, 'font-size' => 8], - '74536' => ['name' => '74536(name tags)', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 7.0, 'marginTop' => 25, 'NX' => 2, 'NY' => 3, 'SpaceX' => 0, 'SpaceY' => 0, 'width' => 102, 'height' => 76, 'font-size' => 18], - 'L7163' => ['name' => 'L7163', 'paper-size' => 'A4', 'metric' => 'mm', 'marginLeft' => 5, 'marginTop' => 15, 'NX' => 2, 'NY' => 7, 'SpaceX' => 2.5, 'SpaceY' => 0, 'width' => 99.1, 'height' => 38.1, 'font-size' => 10], + '5160' => ['name' => '5160', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 4, 'marginTop' => 11.5, 'NX' => 3, 'NY' => 10, 'SpaceX' => 3.175, 'SpaceY' => 0, 'width' => 66.675, 'height' => 25.4, 'font-size' => 11], + '5161' => ['name' => '5161', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 1, 'marginTop' => 10.7, 'NX' => 2, 'NY' => 10, 'SpaceX' => 3.967, 'SpaceY' => 0, 'width' => 101.6, 'height' => 25.4, 'font-size' => 11], + '5162' => ['name' => '5162', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 4, 'marginTop' => 20.224, 'NX' => 2, 'NY' => 7, 'SpaceX' => 4.762, 'SpaceY' => 0, 'width' => 100.807, 'height' => 34, 'font-size' => 12], + '5163' => ['name' => '5163', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 1.762, 'marginTop' => 10.7, 'NX' => 2, 'NY' => 5, 'SpaceX' => 3.175, 'SpaceY' => 0, 'width' => 101.6, 'height' => 50.8, 'font-size' => 8], + '5164' => ['name' => '5164', 'paper-size' => 'letter', 'metric' => 'in', 'marginLeft' => 0.148, 'marginTop' => 0.5, 'NX' => 2, 'NY' => 3, 'SpaceX' => 0.2031, 'SpaceY' => 0, 'width' => 4.0, 'height' => 3.33, 'font-size' => 12], + '8600' => ['name' => '8600', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 7.1, 'marginTop' => 19, 'NX' => 3, 'NY' => 10, 'SpaceX' => 9.5, 'SpaceY' => 3.1, 'width' => 66.6, 'height' => 25.4, 'font-size' => 8], + '74536' => ['name' => '74536(name tags)', 'paper-size' => 'letter', 'metric' => 'mm', 'marginLeft' => 7.0, 'marginTop' => 25, 'NX' => 2, 'NY' => 3, 'SpaceX' => 0, 'SpaceY' => 0, 'width' => 102, 'height' => 76, 'font-size' => 18], + 'L7163' => ['name' => 'L7163', 'paper-size' => 'A4', 'metric' => 'mm', 'marginLeft' => 5, 'marginTop' => 15, 'NX' => 2, 'NY' => 7, 'SpaceX' => 2.5, 'SpaceY' => 0, 'width' => 99.1, 'height' => 38.1, 'font-size' => 10], ]; // convert units (in to mm, mm to in) diff --git a/src/ChurchCRM/SQLUtils.php b/src/ChurchCRM/SQLUtils.php index 61bc52fdbf..3d43039906 100644 --- a/src/ChurchCRM/SQLUtils.php +++ b/src/ChurchCRM/SQLUtils.php @@ -1,154 +1,153 @@ 0) { - self::query($row, $mysqli); + // 3. parse delimiter row + if (preg_match('/^DELIMITER\s+[^ ]+/sUi', $row)) { + $delimiter = preg_replace('/^DELIMITER\s+([^ ]+)$/sUi', '$1', $row); + continue; } - 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, (string) $delimiter, $offset) !== false) { + $delimiterOffset = strpos($row, (string) $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)) { - [$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)) { + [$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 8f2a90cf31..49c5379155 100644 --- a/src/ChurchCRM/Search/AddressSearchResultProvider.php +++ b/src/ChurchCRM/Search/AddressSearchResultProvider.php @@ -2,26 +2,25 @@ 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 { 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)); + if (SystemConfig::getBooleanValue('bSearchIncludeAddresses')) { + $this->addSearchResults($this->getPersonSearchResultsByPartialAddress($SearchQuery)); } + return $this->formatSearchGroup(); } @@ -29,20 +28,21 @@ private function getPersonSearchResultsByPartialAddress(string $SearchQuery) { $searchResults = []; $id = 0; + try { - $searchLikeString = '%' . $SearchQuery . '%'; + $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) { diff --git a/src/ChurchCRM/Search/BaseSearchResultProvider.php b/src/ChurchCRM/Search/BaseSearchResultProvider.php index 94dd9e8618..987293e585 100644 --- a/src/ChurchCRM/Search/BaseSearchResultProvider.php +++ b/src/ChurchCRM/Search/BaseSearchResultProvider.php @@ -2,26 +2,29 @@ namespace ChurchCRM\Search; -use ChurchCRM\Search\SearchResult; - abstract class BaseSearchResultProvider { /* @var string */ protected $pluralNoun; /* @var ChurchCRM\Search\SearchResult[] */ protected $searchResults = []; + 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) { $this->searchResults = array_merge($this->searchResults, $results); } + protected function __construct() { } diff --git a/src/ChurchCRM/Search/CalendarEventSearchResultProvider.php b/src/ChurchCRM/Search/CalendarEventSearchResultProvider.php index 0b3926a6b4..7e828a8b38 100644 --- a/src/ChurchCRM/Search/CalendarEventSearchResultProvider.php +++ b/src/ChurchCRM/Search/CalendarEventSearchResultProvider.php @@ -3,25 +3,24 @@ 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 { public function __construct() { - $this->pluralNoun = "Calendar Events"; + $this->pluralNoun = 'Calendar Events'; parent::__construct(); } public function getSearchResults(string $SearchQuery) { - if (SystemConfig::getBooleanValue("bSearchIncludeCalendarEvents")) { + if (SystemConfig::getBooleanValue('bSearchIncludeCalendarEvents')) { $this->addSearchResults($this->getCalendarEventSearchResultsByPartialName($SearchQuery)); } + return $this->formatSearchGroup(); } @@ -29,6 +28,7 @@ private function getCalendarEventSearchResultsByPartialName(string $SearchQuery) { $searchResults = []; $id = 0; + try { $events = EventQuery::create() ->filterByTitle("%$SearchQuery%", Criteria::LIKE) @@ -36,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 e33530e99d..4447e1b98b 100644 --- a/src/ChurchCRM/Search/FamilySearchResultProvider.php +++ b/src/ChurchCRM/Search/FamilySearchResultProvider.php @@ -2,29 +2,27 @@ 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 { public function __construct() { - $this->pluralNoun = "Families"; + $this->pluralNoun = 'Families'; parent::__construct(); } public function getSearchResults(string $SearchQuery) { $searchResults = []; - if (SystemConfig::getBooleanValue("bSearchIncludeFamilies")) { + if (SystemConfig::getBooleanValue('bSearchIncludeFamilies')) { $this->addSearchResults($this->getFamilySearchResultsByPartialName($SearchQuery)); } - if (SystemConfig::getBooleanValue("bSearchIncludeFamilyCustomProperties")) { + if (SystemConfig::getBooleanValue('bSearchIncludeFamilyCustomProperties')) { $this->addSearchResults($this->getFamilySearchResultsByCustomProperties($SearchQuery)); } @@ -35,6 +33,7 @@ private function getFamilySearchResultsByPartialName(string $SearchQuery) { $searchResults = []; $id = 0; + try { $families = FamilyQuery::create()-> filterByName("%$SearchQuery%", Criteria::LIKE)-> @@ -42,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())); } } @@ -58,10 +55,12 @@ private function getFamilySearchResultsByPartialName(string $SearchQuery) LoggerUtils::getAppLogger()->warning($e->getMessage()); } } + private function getFamilySearchResultsByCustomProperties(string $SearchQuery) { $searchResults = []; $id = 0; + try { $customFields = FamilyCustomMasterQuery::create()->find(); $familyQuery = FamilyQuery::create() @@ -69,17 +68,18 @@ private function getFamilySearchResultsByCustomProperties(string $SearchQuery) ->useFamilyCustomQuery(); 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 5b21e0c2db..224d555072 100644 --- a/src/ChurchCRM/Search/FinanceDepositSearchResultProvider.php +++ b/src/ChurchCRM/Search/FinanceDepositSearchResultProvider.php @@ -2,30 +2,29 @@ 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 { public function __construct() { - $this->pluralNoun = "Deposits"; + $this->pluralNoun = 'Deposits'; parent::__construct(); } 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(); } @@ -33,23 +32,25 @@ 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 850d867477..b0283c24e9 100644 --- a/src/ChurchCRM/Search/FinancePaymentSearchResultProvider.php +++ b/src/ChurchCRM/Search/FinancePaymentSearchResultProvider.php @@ -2,34 +2,33 @@ 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 { public function __construct() { - $this->pluralNoun = "Payments"; + $this->pluralNoun = 'Payments'; parent::__construct(); } 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(); } @@ -40,12 +39,13 @@ private function getPaymentsWithValuesInRange(int $min, int $max) 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(); @@ -54,39 +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 = []; $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 04080180ea..ee9f8ff023 100644 --- a/src/ChurchCRM/Search/GroupSearchResultProvider.php +++ b/src/ChurchCRM/Search/GroupSearchResultProvider.php @@ -2,26 +2,25 @@ 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 { public function __construct() { - $this->pluralNoun = "Groups"; + $this->pluralNoun = 'Groups'; parent::__construct(); } public function getSearchResults(string $SearchQuery) { - if (SystemConfig::getBooleanValue("bSearchIncludeGroups")) { + if (SystemConfig::getBooleanValue('bSearchIncludeGroups')) { $this->addSearchResults($this->getPersonSearchResultsByPartialName($SearchQuery)); } + return $this->formatSearchGroup(); } @@ -29,20 +28,22 @@ 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 949379f45f..a5b24c2b4b 100644 --- a/src/ChurchCRM/Search/PersonSearchResultProvider.php +++ b/src/ChurchCRM/Search/PersonSearchResultProvider.php @@ -2,27 +2,25 @@ 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 { public function __construct() { - $this->pluralNoun = "Persons"; + $this->pluralNoun = 'Persons'; parent::__construct(); } public function getSearchResults(string $SearchQuery) { - if (SystemConfig::getBooleanValue("bSearchIncludePersons")) { + if (SystemConfig::getBooleanValue('bSearchIncludePersons')) { $this->addSearchResults($this->getPersonSearchResultsByPartialName($SearchQuery)); } + return $this->formatSearchGroup(); } @@ -30,8 +28,9 @@ 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)-> @@ -40,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 292fa83373..7fae57d540 100644 --- a/src/ChurchCRM/Search/SearchResult.php +++ b/src/ChurchCRM/Search/SearchResult.php @@ -7,6 +7,7 @@ class SearchResult public $id; public $text; public $uri; + public function __construct(string $id, string $text, string $uri) { $this->id = $id; diff --git a/src/ChurchCRM/Search/SearchResultGroup.php b/src/ChurchCRM/Search/SearchResultGroup.php index 2f2e6a5167..52762c7cb0 100644 --- a/src/ChurchCRM/Search/SearchResultGroup.php +++ b/src/ChurchCRM/Search/SearchResultGroup.php @@ -16,7 +16,7 @@ public function __construct(string $groupName, array $results) public function jsonSerialize(): array { return [ - 'text' => $this->groupName, + 'text' => $this->groupName, 'children' => $this->results, ]; } diff --git a/src/ChurchCRM/Service/AppIntegrityService.php b/src/ChurchCRM/Service/AppIntegrityService.php index 6b6d93599e..c2d7dbeff4 100644 --- a/src/ChurchCRM/Service/AppIntegrityService.php +++ b/src/ChurchCRM/Service/AppIntegrityService.php @@ -2,8 +2,8 @@ namespace ChurchCRM\Service; -use ChurchCRM\dto\SystemURLs; use ChurchCRM\dto\Prerequisite; +use ChurchCRM\dto\SystemURLs; use ChurchCRM\Utils\LoggerUtils; use ChurchCRM\Utils\MiscUtils; @@ -15,27 +15,27 @@ private static function getIntegrityCheckData() { $logger = LoggerUtils::getAppLogger(); - $integrityCheckFile = SystemURLs::getDocumentRoot() . '/integrityCheck.json'; + $integrityCheckFile = SystemURLs::getDocumentRoot().'/integrityCheck.json'; if (AppIntegrityService::$IntegrityCheckDetails === null) { $logger->debug('Integrity check results not cached; reloading from file'); if (is_file($integrityCheckFile)) { - $logger->info('Integrity check result file found at: ' . $integrityCheckFile); + $logger->info('Integrity check result file found at: '.$integrityCheckFile); try { $integrityCheckFileContents = file_get_contents($integrityCheckFile); MiscUtils::throwIfFailed($integrityCheckFileContents); AppIntegrityService::$IntegrityCheckDetails = json_decode($integrityCheckFileContents, null, 512, JSON_THROW_ON_ERROR); } catch (\Exception $e) { - $logger->warning("Error decoding integrity check result file: " . $integrityCheckFile, ['exception' => $e]); + $logger->warning('Error decoding integrity check result file: '.$integrityCheckFile, ['exception' => $e]); AppIntegrityService::$IntegrityCheckDetails = new \stdClass(); AppIntegrityService::$IntegrityCheckDetails->status = 'failure'; - AppIntegrityService::$IntegrityCheckDetails->message = gettext("Error decoding integrity check result file"); + AppIntegrityService::$IntegrityCheckDetails->message = gettext('Error decoding integrity check result file'); } } else { - $logger->debug('Integrity check result file not found at: ' . $integrityCheckFile); + $logger->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"); + AppIntegrityService::$IntegrityCheckDetails->message = gettext('integrityCheck.json file missing'); } } else { $logger->debug('Integrity check results already cached; not reloading from file'); @@ -46,16 +46,16 @@ private static function getIntegrityCheckData() public static function getIntegrityCheckStatus(): string { - if (AppIntegrityService::getIntegrityCheckData()->status === "failure") { - return gettext("Failed"); + if (AppIntegrityService::getIntegrityCheckData()->status === 'failure') { + return gettext('Failed'); } - return gettext("Passed"); + return gettext('Passed'); } public static function getIntegrityCheckMessage(): string { - if (AppIntegrityService::getIntegrityCheckData()->status !== "failure") { + if (AppIntegrityService::getIntegrityCheckData()->status !== 'failure') { AppIntegrityService::$IntegrityCheckDetails->message = gettext('The previous integrity check passed. All system file hashes match the expected values.'); } @@ -71,42 +71,42 @@ public static function verifyApplicationIntegrity(): array { $logger = LoggerUtils::getAppLogger(); - $signatureFile = SystemURLs::getDocumentRoot() . '/signatures.json'; + $signatureFile = SystemURLs::getDocumentRoot().'/signatures.json'; $signatureFailures = []; if (is_file($signatureFile)) { - $logger->info('Signature file found at: ' . $signatureFile); + $logger->info('Signature file found at: '.$signatureFile); try { $signatureFileContents = file_get_contents($signatureFile); MiscUtils::throwIfFailed($signatureFileContents); $signatureData = json_decode($signatureFileContents, null, 512, JSON_THROW_ON_ERROR); } catch (\Exception $e) { - $logger->warning('Error decoding signature definition file: ' . $signatureFile, ['exception' => $e]); + $logger->warning('Error decoding signature definition file: '.$signatureFile, ['exception' => $e]); return [ - 'status' => 'failure', - 'message' => gettext('Error decoding signature definition file') + '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; + $currentFile = SystemURLs::getDocumentRoot().'/'.$file->filename; if (file_exists($currentFile)) { $actualHash = sha1_file($currentFile); if ($actualHash != $file->sha1) { - $logger->warning('File hash mismatch: ' . $file->filename . ". Expected: " . $file->sha1 . "; Got: " . $actualHash); + $logger->warning('File hash mismatch: '.$file->filename.'. Expected: '.$file->sha1.'; Got: '.$actualHash); array_push($signatureFailures, [ - 'filename' => $file->filename, - 'status' => 'Hash Mismatch', + 'filename' => $file->filename, + 'status' => 'Hash Mismatch', 'expectedhash' => $file->sha1, - 'actualhash' => $actualHash + 'actualhash' => $actualHash, ]); } } else { - $logger->warning('File Missing: ' . $file->filename); + $logger->warning('File Missing: '.$file->filename); array_push($signatureFailures, [ 'filename' => $file->filename, - 'status' => 'File Missing' + 'status' => 'File Missing', ]); } } @@ -114,36 +114,37 @@ public static function verifyApplicationIntegrity(): array $logger->warning('Signature definition file signature failed validation'); return [ - 'status' => 'failure', - 'message' => gettext('Signature definition file signature failed validation') + 'status' => 'failure', + 'message' => gettext('Signature definition file signature failed validation'), ]; } } else { - $logger->warning('Signature definition file not found at: ' . $signatureFile); + $logger->warning('Signature definition file not found at: '.$signatureFile); + return [ - 'status' => 'failure', - 'message' => gettext('Signature definition File Missing') + 'status' => 'failure', + 'message' => gettext('Signature definition File Missing'), ]; } if (count($signatureFailures) > 0) { return [ - 'status' => 'failure', + 'status' => 'failure', 'message' => gettext('One or more files failed signature validation'), - 'files' => $signatureFailures + 'files' => $signatureFailures, ]; } else { return [ - 'status' => 'success' + 'status' => 'success', ]; } } private static function testImagesWriteable(): bool { - return is_writable(SystemURLs::getDocumentRoot() . '/Images/') && - is_writable(SystemURLs::getDocumentRoot() . '/Images/Family') && - is_writable(SystemURLs::getDocumentRoot() . '/Images/Person'); + return is_writable(SystemURLs::getDocumentRoot().'/Images/') && + is_writable(SystemURLs::getDocumentRoot().'/Images/Family') && + is_writable(SystemURLs::getDocumentRoot().'/Images/Person'); } /** @@ -152,24 +153,24 @@ private static function testImagesWriteable(): bool public static function getApplicationPrerequisites(): array { $prerequisites = [ - new Prerequisite('PHP 8.1+', fn() => version_compare(PHP_VERSION, '8.1.0', '>=')), - new Prerequisite('PCRE and UTF-8 Support', fn() => function_exists('preg_match') && @preg_match('/^.$/u', 'ñ') && @preg_match('/^\pL$/u', 'ñ')), - new Prerequisite('Multibyte Encoding', fn() => extension_loaded('mbstring')), - new Prerequisite('PHP Phar', fn() => extension_loaded('phar')), - new Prerequisite('PHP Session', fn() => extension_loaded('session')), - new Prerequisite('PHP XML', fn() => extension_loaded('xml')), - new Prerequisite('PHP EXIF', fn() => extension_loaded('exif')), - new Prerequisite('PHP iconv', fn() => extension_loaded('iconv')), - new Prerequisite('Mod Rewrite or Equivalent', fn() => AppIntegrityService::hasModRewrite()), - new Prerequisite('GD Library for image manipulation', fn() => extension_loaded('gd') && function_exists('gd_info')), - new Prerequisite('FreeType Library', fn() => function_exists('imagettftext')), - new Prerequisite('FileInfo Extension for image manipulation', fn() => extension_loaded('fileinfo')), - new Prerequisite('cURL', fn() => function_exists('curl_version')), - new Prerequisite('locale gettext', fn() => function_exists('bindtextdomain') && function_exists("gettext")), - new Prerequisite('Include/Config file is writeable', fn() => is_writable(SystemURLs::getDocumentRoot() . '/Include/') || is_writable(SystemURLs::getDocumentRoot() . '/Include/Config.php')), - new Prerequisite('Images directory is writeable', fn() => AppIntegrityService::testImagesWriteable()), - new Prerequisite('PHP ZipArchive', fn() => extension_loaded('zip')), - new Prerequisite('Mysqli Functions', fn() => function_exists('mysqli_connect')) + new Prerequisite('PHP 8.1+', fn () => version_compare(PHP_VERSION, '8.1.0', '>=')), + new Prerequisite('PCRE and UTF-8 Support', fn () => function_exists('preg_match') && @preg_match('/^.$/u', 'ñ') && @preg_match('/^\pL$/u', 'ñ')), + new Prerequisite('Multibyte Encoding', fn () => extension_loaded('mbstring')), + new Prerequisite('PHP Phar', fn () => extension_loaded('phar')), + new Prerequisite('PHP Session', fn () => extension_loaded('session')), + new Prerequisite('PHP XML', fn () => extension_loaded('xml')), + new Prerequisite('PHP EXIF', fn () => extension_loaded('exif')), + new Prerequisite('PHP iconv', fn () => extension_loaded('iconv')), + new Prerequisite('Mod Rewrite or Equivalent', fn () => AppIntegrityService::hasModRewrite()), + new Prerequisite('GD Library for image manipulation', fn () => extension_loaded('gd') && function_exists('gd_info')), + new Prerequisite('FreeType Library', fn () => function_exists('imagettftext')), + new Prerequisite('FileInfo Extension for image manipulation', fn () => extension_loaded('fileinfo')), + new Prerequisite('cURL', fn () => function_exists('curl_version')), + new Prerequisite('locale gettext', fn () => function_exists('bindtextdomain') && function_exists('gettext')), + new Prerequisite('Include/Config file is writeable', fn () => is_writable(SystemURLs::getDocumentRoot().'/Include/') || is_writable(SystemURLs::getDocumentRoot().'/Include/Config.php')), + new Prerequisite('Images directory is writeable', fn () => AppIntegrityService::testImagesWriteable()), + new Prerequisite('PHP ZipArchive', fn () => extension_loaded('zip')), + new Prerequisite('Mysqli Functions', fn () => function_exists('mysqli_connect')), ]; return $prerequisites; @@ -182,7 +183,7 @@ public static function getUnmetPrerequisites(): array { return array_filter( AppIntegrityService::getApplicationPrerequisites(), - fn($prereq) => !$prereq->isPrerequisiteMet() + fn ($prereq) => !$prereq->isPrerequisiteMet() ); } @@ -193,12 +194,12 @@ public static function arePrerequisitesMet(): bool public static function hasModRewrite(): bool { - // 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) + // 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(); @@ -210,7 +211,7 @@ public static function hasModRewrite(): bool $logger->debug('PHP is running through Apache; looking for mod_rewrite'); if (function_exists('apache_get_modules')) { $check = in_array('mod_rewrite', apache_get_modules()); - } + } $logger->debug("Apache mod_rewrite check status: $check"); } else { $logger->debug('PHP is not running through Apache'); @@ -222,7 +223,7 @@ public static function hasModRewrite(): bool $ch = curl_init(); $request_url_parser = parse_url($_SERVER['HTTP_REFERER']); $request_scheme = $request_url_parser['scheme'] ?? 'http'; - $rewrite_chk_url = $request_scheme . '://' . $_SERVER['SERVER_ADDR'] . SystemURLs::getRootPath() . '/INVALID'; + $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); @@ -242,8 +243,8 @@ public static function hasModRewrite(): bool $headers[trim($middle[0])] = trim($middle[1]); } } - $check = $headers['CRM'] == 'would redirect'; - $logger->debug('CURL loopback check headers observed: ' . ($check ? 'true' : 'false')); + $check = $headers['CRM'] == 'would redirect'; + $logger->debug('CURL loopback check headers observed: '.($check ? 'true' : 'false')); } } diff --git a/src/ChurchCRM/Service/DashboardService.php b/src/ChurchCRM/Service/DashboardService.php index 9d5aeb3038..51502be261 100644 --- a/src/ChurchCRM/Service/DashboardService.php +++ b/src/ChurchCRM/Service/DashboardService.php @@ -12,7 +12,7 @@ public function getAgeStats() $ageStats = []; $people = PersonQuery::create()->find(); foreach ($people as $person) { - $personNumericAge = (int)$person->getNumericAge(); + $personNumericAge = (int) $person->getNumericAge(); if ($personNumericAge == 0) { continue; } @@ -22,8 +22,10 @@ public function getAgeStats() $ageStats[$personNumericAge]++; } ksort($ageStats); + return $ageStats; } + public function getFamilyCount() { $familyCount = FamilyQuery::Create() @@ -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 467eb979e7..b68d1d82db 100644 --- a/src/ChurchCRM/Service/FinancialService.php +++ b/src/ChurchCRM/Service/FinancialService.php @@ -3,14 +3,14 @@ namespace ChurchCRM\Service; $bSuppressSessionTests = true; // DO NOT MOVE -require_once dirname(__DIR__) . '/../Include/Functions.php'; +require_once dirname(__DIR__).'/../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 { @@ -28,12 +28,12 @@ public function getMemberByScanString($sstrnig) $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 . '"'; + $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 . '"}'; + return '{"ScanString": "'.$tScanString.'" , "RouteAndAccount": "'.$routeAndAccount.'" , "CheckNumber": "'.$iCheckNo.'" ,"fam_ID": "'.$fam_ID.'" , "fam_Name": "'.$fam_Name.'"}'; } else { throw new \Exception('error in locating family'); } @@ -45,17 +45,17 @@ public function getMemberByScanString($sstrnig) public function setDeposit($depositType, $depositComment, $depositDate, $iDepositSlipID = null, $depositClosed = false) { if ($iDepositSlipID) { - $sSQL = "UPDATE deposit_dep SET dep_Date = '" . $depositDate . "', dep_Comment = '" . $depositComment . "', dep_EnteredBy = " . AuthenticationManager::getCurrentUser()->getId() . ', dep_Closed = ' . intval($depositClosed) . ' WHERE dep_ID = ' . $iDepositSlipID . ';'; + $sSQL = "UPDATE deposit_dep SET dep_Date = '".$depositDate."', dep_Comment = '".$depositComment."', dep_EnteredBy = ".AuthenticationManager::getCurrentUser()->getId().', dep_Closed = '.intval($depositClosed).' WHERE dep_ID = '.$iDepositSlipID.';'; $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); } else { $sSQL = "INSERT INTO deposit_dep (dep_Date, dep_Comment, dep_EnteredBy, dep_Type) - VALUES ('" . $depositDate . "','" . $depositComment . "'," . AuthenticationManager::getCurrentUser()->getId() . ",'" . $depositType . "')"; + VALUES ('".$depositDate."','".$depositComment."',".AuthenticationManager::getCurrentUser()->getId().",'".$depositType."')"; RunQuery($sSQL); $sSQL = 'SELECT MAX(dep_ID) AS iDepositSlipID FROM deposit_dep'; $rsDepositSlipID = RunQuery($sSQL); @@ -71,10 +71,10 @@ public function getDepositTotal($id, $type = null) requireUserGroupMembership('bFinance'); $sqlClause = ''; if ($type) { - $sqlClause = "AND plg_method = '" . $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); [$deposit_total] = mysqli_fetch_row($rsDepositTotal); @@ -84,7 +84,7 @@ public function getDepositTotal($id, $type = null) public function getPaymentJSON($payments) { if ($payments) { - return '{"payments":' . json_encode($payments, JSON_THROW_ON_ERROR) . '}'; + return '{"payments":'.json_encode($payments, JSON_THROW_ON_ERROR).'}'; } else { return false; } @@ -100,7 +100,7 @@ public function getPayments($depID) pledge_plg.plg_fundID = donationfund_fun.fun_ID'; if ($depID) { - $sSQL .= ' WHERE plg_depID = ' . $depID; + $sSQL .= ' WHERE plg_depID = '.$depID; } $rsDep = RunQuery($sSQL); @@ -142,12 +142,12 @@ public function getPayments($depID) public function getPaymentViewURI($groupKey) { - return SystemURLs::getRootPath() . '/PledgeEditor.php?GroupKey=' . $groupKey; + return SystemURLs::getRootPath().'/PledgeEditor.php?GroupKey='.$groupKey; } public function getViewURI($Id) { - return SystemURLs::getRootPath() . '/DepositSlipEditor.php?DepositSlipID=' . $Id; + return SystemURLs::getRootPath().'/DepositSlipEditor.php?DepositSlipID='.$Id; } private function validateDate($payment) @@ -164,15 +164,15 @@ private function validateDate($payment) 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. + //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, null, 512, JSON_THROW_ON_ERROR); if (count($FundSplit) >= 1 && $FundSplit[0]->FundID != 'None') { // split $nonZeroFundAmountEntered = 0; foreach ($FundSplit as $fun_id => $fund) { //$fun_active = $fundActive[$fun_id]; if ($fund->Amount > 0) { - ++$nonZeroFundAmountEntered; + $nonZeroFundAmountEntered++; } if (SystemConfig::getValue('bEnableNonDeductible') && isset($fund->NonDeductible)) { //Validate the NonDeductible Amount @@ -193,8 +193,8 @@ public function locateFamilyCheck($checkNumber, $fam_ID) { requireUserGroupMembership('bFinance'); $sSQL = 'SELECT count(plg_FamID) from pledge_plg - WHERE plg_CheckNo = ' . $checkNumber . ' AND - plg_FamID = ' . $fam_ID; + WHERE plg_CheckNo = '.$checkNumber.' AND + plg_FamID = '.$fam_ID; $rCount = RunQuery($sSQL); return mysqli_fetch_array($rCount)[0]; @@ -203,19 +203,19 @@ 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 + //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' && $payment->iMethod == 'CHECK' && !isset($payment->iCheckNo)) { throw new \Exception(gettext('Must specify non-zero check number')); } - // detect check inconsistencies + // detect check inconsistencies if ($payment->type == 'Payment' && isset($payment->iCheckNo)) { if ($payment->iMethod == 'CASH') { throw new \Exception(gettext("Check number not valid for 'CASH' payment")); } elseif ($payment->iMethod == 'CHECK' && $this->locateFamilyCheck($payment->iCheckNo, $payment->FamilyID)) { //build routine to make sure this check number hasn't been used by this family yet (look at group key) - throw new \Exception("Check number '" . $payment->iCheckNo . "' for selected family already exists."); + throw new \Exception("Check number '".$payment->iCheckNo."' for selected family already exists."); } } } @@ -225,7 +225,7 @@ public function processCurrencyDenominations($payment, $groupKey) $currencyDenoms = json_decode($payment->cashDenominations, null, 512, JSON_THROW_ON_ERROR); foreach ($currencyDenoms as $cdom) { $sSQL = "INSERT INTO pledge_denominations_pdem (pdem_plg_GroupKey, plg_depID, pdem_denominationID, pdem_denominationQuantity) - VALUES ('" . $groupKey . "','" . $payment->DepositID . "','" . $cdom->currencyID . "','" . $cdom->Count . "')"; + VALUES ('".$groupKey."','".$payment->DepositID."','".$cdom->currencyID."','".$cdom->Count."')"; if (isset($sSQL)) { RunQuery($sSQL); unset($sSQL); @@ -236,8 +236,8 @@ 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 + // 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, null, 512, JSON_THROW_ON_ERROR); foreach ($FundSplit as $Fund) { @@ -247,12 +247,12 @@ public function insertPledgeorPayment($payment) $sGroupKey = genGroupKey($payment->iCheckNo, $payment->FamilyID, $Fund->FundID, $payment->Date); } elseif ($payment->iMethod == 'BANKDRAFT') { if (!$iAutID) { - $iAutID = 'draft'; + $iAutID = 'draft'; } $sGroupKey = genGroupKey($iAutID, $payment->FamilyID, $Fund->FundID, $payment->Date); } elseif ($payment->iMethod == 'CREDITCARD') { if (!$iAutID) { - $iAutID = 'credit'; + $iAutID = 'credit'; } $sGroupKey = genGroupKey($iAutID, $payment->FamilyID, $Fund->FundID, $payment->Date); } else { @@ -277,24 +277,24 @@ public function insertPledgeorPayment($payment) plg_aut_ID, plg_NonDeductible, plg_GroupKey) - VALUES ('" . - $payment->FamilyID . "','" . - $payment->FYID . "','" . - $payment->Date . "','" . - $Fund->Amount . "','" . - ($payment->schedule ?? 'NULL') . "','" . - $payment->iMethod . "','" . - $Fund->Comment . "','" . - date('YmdHis') . "'," . - AuthenticationManager::getCurrentUser()->getId() . ",'" . - $payment->type . "'," . - $Fund->FundID . ',' . - $payment->DepositID . ',' . - ($payment->iCheckNo ?? 'NULL') . ",'" . - ($payment->tScanString ?? 'NULL') . "','" . - ($payment->iAutID ?? 'NULL') . "','" . - ($Fund->NonDeductible ?? 'NULL') . "','" . - $sGroupKey . "')"; + VALUES ('". + $payment->FamilyID."','". + $payment->FYID."','". + $payment->Date."','". + $Fund->Amount."','". + ($payment->schedule ?? 'NULL')."','". + $payment->iMethod."','". + $Fund->Comment."','". + date('YmdHis')."',". + AuthenticationManager::getCurrentUser()->getId().",'". + $payment->type."',". + $Fund->FundID.','. + $payment->DepositID.','. + ($payment->iCheckNo ?? 'NULL').",'". + ($payment->tScanString ?? 'NULL')."','". + ($payment->iAutID ?? 'NULL')."','". + ($Fund->NonDeductible ?? 'NULL')."','". + $sGroupKey."')"; if (isset($sSQL)) { RunQuery($sSQL); @@ -321,7 +321,7 @@ public function getPledgeorPayment($GroupKey) { requireUserGroupMembership('bFinance'); $total = 0; - $sSQL = 'SELECT plg_plgID, plg_FamID, plg_date, plg_fundID, plg_amount, plg_NonDeductible,plg_comment, plg_FYID, plg_method, plg_EditedBy from pledge_plg where plg_GroupKey="' . $GroupKey . '"'; + $sSQL = 'SELECT plg_plgID, plg_FamID, plg_date, plg_fundID, plg_amount, plg_NonDeductible,plg_comment, plg_FYID, plg_method, plg_EditedBy from pledge_plg where plg_GroupKey="'.$GroupKey.'"'; $rsKeys = RunQuery($sSQL); $payment = new \stdClass(); $payment->funds = []; @@ -351,10 +351,10 @@ public function getPledgeorPayment($GroupKey) private function generateBankDepositSlip($thisReport) { // -------------------------------- - // BEGIN FRONT OF BANK DEPOSIT SLIP + // 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->Write(8, $thisReport->deposit->dep_Date); @@ -386,8 +386,8 @@ 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]); $numItems = 0; @@ -428,7 +428,7 @@ private function generateDepositSummary($thisReport) $thisReport->pdf->SetXY($thisReport->depositSummaryParameters->title->x, $thisReport->depositSummaryParameters->title->y); $thisReport->pdf->SetFont('Courier', 'B', 20); - $thisReport->pdf->Write(8, 'Deposit Summary ' . $thisReport->deposit->dep_ID); + $thisReport->pdf->Write(8, 'Deposit Summary '.$thisReport->deposit->dep_ID); $thisReport->pdf->SetFont('Times', 'B', 10); $thisReport->curX = $thisReport->depositSummaryParameters->summary->x; @@ -456,22 +456,22 @@ private function generateDepositSummary($thisReport) $totalAmount = 0; - //while ($aRow = mysqli_fetch_array($rsPledges)) + //while ($aRow = mysqli_fetch_array($rsPledges)) foreach ($thisReport->payments as $payment) { $thisReport->pdf->SetFont('Times', '', 10); - // Format Data + // Format Data if (strlen($payment->plg_CheckNo) > 8) { - $payment->plg_CheckNo = '...' . mb_substr($payment->plg_CheckNo, -8, 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) . '...'; + $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) . '...'; + $payment->plg_comment = mb_substr($payment->plg_comment, 0, 38).'...'; } if (strlen($payment->familyName) > 25) { - $payment->familyName = mb_substr($payment->familyName, 0, 24) . '...'; + $payment->familyName = mb_substr($payment->familyName, 0, 24).'...'; } $thisReport->pdf->printRightJustified($thisReport->curX + 2, $thisReport->curY, $payment->plg_CheckNo); @@ -508,7 +508,7 @@ 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 + // Now print deposit totals by fund $thisReport->curY += 2 * $thisReport->depositSummaryParameters->summary->intervalY; if ($thisReport->depositSummaryParameters->displayBillCounts) { $this->generateCashDenominations($thisReport); @@ -560,20 +560,20 @@ public function getDepositCSV($depID) foreach ($payments[0] as $key => $value) { array_push($line, $key); } - $retstring = implode(',', $line) . "\n"; + $retstring = implode(',', $line)."\n"; $line = []; foreach ($payments as $payment) { $line = []; foreach ($payment as $key => $value) { array_push($line, str_replace(',', '', $value)); } - $retstring .= implode(',', $line) . "\n"; + $retstring .= implode(',', $line)."\n"; } $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; } @@ -581,11 +581,11 @@ public function getDepositCSV($depID) public function getCurrencyTypeOnDeposit($currencyID, $depositID) { $currencies = []; - // Get the list of Currency denominations + // Get the list of Currency denominations $sSQL = 'select sum(pdem_denominationQuantity) from pledge_denominations_pdem - where plg_depID = ' . $depositID . ' + where plg_depID = '.$depositID.' AND - pdem_denominationID = ' . $currencyID; + pdem_denominationID = '.$currencyID; $rscurrencyDenomination = RunQuery($sSQL); return mysqli_fetch_array($rscurrencyDenomination)[0]; @@ -594,7 +594,7 @@ public function getCurrencyTypeOnDeposit($currencyID, $depositID) public function getCurrency() { $currencies = []; - // Get the list of Currency denominations + // Get the list of Currency denominations $sSQL = 'SELECT * FROM currency_denominations_cdem'; $rscurrencyDenomination = RunQuery($sSQL); mysqli_data_seek($rscurrencyDenomination, 0); @@ -606,6 +606,7 @@ public function getCurrency() $currency->cClass = $row['cdem_denominationClass']; array_push($currencies, $currency); } // end while + return $currencies; } @@ -624,6 +625,7 @@ public function getActiveFunds() $fund->Description = $aRow['fun_Description']; array_push($funds, $fund); } // end while + return $funds; } } diff --git a/src/ChurchCRM/Service/GroupService.php b/src/ChurchCRM/Service/GroupService.php index 59cf0b854b..3461e16cc1 100644 --- a/src/ChurchCRM/Service/GroupService.php +++ b/src/ChurchCRM/Service/GroupService.php @@ -15,33 +15,33 @@ class GroupService public function removeUserFromGroup($groupID, $personID) { requireUserGroupMembership('bManageGroups'); - $sSQL = 'DELETE FROM person2group2role_p2g2r WHERE p2g2r_per_ID = ' . $personID . ' AND p2g2r_grp_ID = ' . $groupID; + $sSQL = 'DELETE FROM person2group2role_p2g2r WHERE p2g2r_per_ID = '.$personID.' AND p2g2r_grp_ID = '.$groupID; RunQuery($sSQL); // Check if this group has special properties - $sSQL = 'SELECT grp_hasSpecialProps FROM group_grp WHERE grp_ID = ' . $groupID; + $sSQL = 'SELECT grp_hasSpecialProps FROM group_grp WHERE grp_ID = '.$groupID; $rsTemp = RunQuery($sSQL); $rowTemp = mysqli_fetch_row($rsTemp); $bHasProp = $rowTemp[0]; if ($bHasProp == 'true') { - $sSQL = 'DELETE FROM groupprop_' . $groupID . " WHERE per_ID = '" . $personID . "'"; + $sSQL = 'DELETE FROM groupprop_'.$groupID." WHERE per_ID = '".$personID."'"; RunQuery($sSQL); } // Reset any group specific property fields of type "Person from Group" with this person assigned - $sSQL = 'SELECT grp_ID, prop_Field FROM groupprop_master WHERE type_ID = 9 AND prop_Special = ' . $groupID; + $sSQL = 'SELECT grp_ID, prop_Field FROM groupprop_master WHERE type_ID = 9 AND prop_Special = '.$groupID; $result = RunQuery($sSQL); while ($aRow = mysqli_fetch_array($result)) { - $sSQL = 'UPDATE groupprop_' . $aRow['grp_ID'] . ' SET ' . $aRow['prop_Field'] . ' = NULL WHERE ' . $aRow['prop_Field'] . ' = ' . $personID; + $sSQL = 'UPDATE groupprop_'.$aRow['grp_ID'].' SET '.$aRow['prop_Field'].' = NULL WHERE '.$aRow['prop_Field'].' = '.$personID; RunQuery($sSQL); } // Reset any custom person fields of type "Person from Group" with this person assigned - $sSQL = 'SELECT custom_Field FROM person_custom_master WHERE type_ID = 9 AND custom_Special = ' . $groupID; + $sSQL = 'SELECT custom_Field FROM person_custom_master WHERE type_ID = 9 AND custom_Special = '.$groupID; $result = RunQuery($sSQL); while ($aRow = mysqli_fetch_array($result)) { - $sSQL = 'UPDATE person_custom SET ' . $aRow['custom_Field'] . ' = NULL WHERE ' . $aRow['custom_Field'] . ' = ' . $personID; + $sSQL = 'UPDATE person_custom SET '.$aRow['custom_Field'].' = NULL WHERE '.$aRow['custom_Field'].' = '.$personID; RunQuery($sSQL); } } @@ -65,23 +65,23 @@ public function addUserToGroup($iGroupID, $iPersonID, $iRoleID) // Was a RoleID passed in? if ($iRoleID == 0) { // No, get the Default Role for this Group - $sSQL = 'SELECT grp_DefaultRole FROM group_grp WHERE grp_ID = ' . $iGroupID; + $sSQL = 'SELECT grp_DefaultRole FROM group_grp WHERE grp_ID = '.$iGroupID; $rsRoleID = RunQuery($sSQL); $Row = mysqli_fetch_row($rsRoleID); $iRoleID = $Row[0]; } - $sSQL = 'INSERT INTO person2group2role_p2g2r (p2g2r_per_ID, p2g2r_grp_ID, p2g2r_rle_ID) VALUES (' . $iPersonID . ', ' . $iGroupID . ', ' . $iRoleID . ')'; + $sSQL = 'INSERT INTO person2group2role_p2g2r (p2g2r_per_ID, p2g2r_grp_ID, p2g2r_rle_ID) VALUES ('.$iPersonID.', '.$iGroupID.', '.$iRoleID.')'; $result = RunQuery($sSQL, false); if ($result) { // Check if this group has special properties - $sSQL = 'SELECT grp_hasSpecialProps FROM group_grp WHERE grp_ID = ' . $iGroupID; + $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 . "')"; + $sSQL = 'INSERT INTO groupprop_'.$iGroupID." (per_ID) VALUES ('".$iPersonID."')"; RunQuery($sSQL); } } @@ -103,7 +103,7 @@ public function getGroupRoles($groupID) FROM group_grp LEFT JOIN list_lst ON list_lst.lst_ID = group_grp.grp_RoleListID - WHERE group_grp.grp_ID = ' . $groupID; + WHERE group_grp.grp_ID = '.$groupID; $rsList = RunQuery($sSQL); // Validate that this list ID is really for a group roles list. (for security) @@ -118,17 +118,15 @@ public function getGroupRoles($groupID) return $groupRoles; } - - public function setGroupRoleOrder($groupID, $groupRoleID, $groupRoleOrder) { requireUserGroupMembership('bManageGroups'); $sSQL = 'UPDATE list_lst INNER JOIN group_grp ON group_grp.grp_RoleListID = list_lst.lst_ID - SET list_lst.lst_OptionSequence = "' . $groupRoleOrder . '" - WHERE group_grp.grp_ID = "' . $groupID . '" - AND list_lst.lst_OptionID = ' . $groupRoleID; + SET list_lst.lst_OptionSequence = "'.$groupRoleOrder.'" + WHERE group_grp.grp_ID = "'.$groupID.'" + AND list_lst.lst_OptionID = '.$groupRoleID; RunQuery($sSQL); } @@ -137,8 +135,8 @@ public function getGroupRoleOrder($groupID, $groupRoleID) $sSQL = 'SELECT list_lst.lst_OptionSequence FROM list_lst INNER JOIN group_grp ON group_grp.grp_RoleListID = list_lst.lst_ID - WHERE group_grp.grp_ID = "' . $groupID . '" - AND list_lst.lst_OptionID = ' . $groupRoleID; + WHERE group_grp.grp_ID = "'.$groupID.'" + AND list_lst.lst_OptionID = '.$groupRoleID; $rsPropList = RunQuery($sSQL); $rowOrder = mysqli_fetch_array($rsPropList); @@ -152,7 +150,7 @@ public function deleteGroupRole($groupID, $groupRoleID) $sSQL = 'SELECT * FROM list_lst INNER JOIN group_grp ON group_grp.grp_RoleListID = list_lst.lst_ID - WHERE group_grp.grp_ID = "' . $groupID . '"'; + WHERE group_grp.grp_ID = "'.$groupID.'"'; $rsPropList = RunQuery($sSQL); $numRows = mysqli_num_rows($rsPropList); // Make sure we never delete the only option @@ -161,8 +159,8 @@ public function deleteGroupRole($groupID, $groupRoleID) $sSQL = 'DELETE list_lst.* FROM list_lst INNER JOIN group_grp ON group_grp.grp_RoleListID = list_lst.lst_ID - WHERE group_grp.grp_ID = "' . $groupID . '" - AND lst_OptionID = ' . $groupRoleID; + WHERE group_grp.grp_ID = "'.$groupID.'" + AND lst_OptionID = '.$groupRoleID; RunQuery($sSQL); @@ -187,8 +185,8 @@ public function deleteGroupRole($groupID, $groupRoleID) INNER JOIN group_grp ON group_grp.grp_RoleListID = list_lst.lst_ID SET list_lst.lst_OptionID = list_lst.lst_OptionID -1 - WHERE group_grp.grp_ID = ' . $groupID . ' - AND list_lst.lst_OptionID >= ' . $groupRoleID; + WHERE group_grp.grp_ID = '.$groupID.' + AND list_lst.lst_OptionID >= '.$groupRoleID; RunQuery($sSQL); @@ -198,8 +196,8 @@ public function deleteGroupRole($groupID, $groupRoleID) INNER JOIN group_grp ON group_grp.grp_RoleListID = list_lst.lst_ID SET list_lst.lst_OptionSequence = list_lst.lst_OptionSequence -1 - WHERE group_grp.grp_ID =' . $groupID . ' - AND list_lst.lst_OptionSequence >= ' . $thisSequence; + WHERE group_grp.grp_ID ='.$groupID.' + AND list_lst.lst_OptionSequence >= '.$thisSequence; //echo $sSQL; @@ -221,11 +219,11 @@ public function addGroupRole($groupID, $groupRoleName) $sSQL = 'SELECT \'\' FROM list_lst INNER JOIN group_grp ON group_grp.grp_RoleListID = list_lst.lst_ID - WHERE group_grp.grp_ID = "' . $groupID . '" AND - lst_OptionName = "' . $groupRoleName . '"'; + WHERE group_grp.grp_ID = "'.$groupID.'" AND + lst_OptionName = "'.$groupRoleName.'"'; $rsCount = RunQuery($sSQL); if (mysqli_num_rows($rsCount) > 0) { - throw new \Exception('Field ' . $groupRoleName . ' already exists'); + throw new \Exception('Field '.$groupRoleName.' already exists'); } else { $sSQL = "SELECT grp_RoleListID FROM group_grp WHERE grp_ID = $groupID"; $rsTemp = RunQuery($sSQL); @@ -245,23 +243,23 @@ public function addGroupRole($groupID, $groupRoleName) // Insert into the appropriate options table $sSQL = 'INSERT INTO list_lst (lst_ID, lst_OptionID, lst_OptionName, lst_OptionSequence) - VALUES (' . $listID . ',' . $newOptionID . ",'" . $groupRoleName . "'," . $newOptionSequence . ')'; + VALUES ('.$listID.','.$newOptionID.",'".$groupRoleName."',".$newOptionSequence.')'; RunQuery($sSQL); $iNewNameError = 0; } } - return '{"newRole":{"roleID":"' . $newOptionID . '", "roleName":"' . $groupRoleName . '", "sequence":"' . $newOptionSequence . '"}}'; + return '{"newRole":{"roleID":"'.$newOptionID.'", "roleName":"'.$groupRoleName.'", "sequence":"'.$newOptionSequence.'"}}'; } public function enableGroupSpecificProperties($groupID) { requireUserGroupMembership('bManageGroups'); $sSQL = 'UPDATE group_grp SET grp_hasSpecialProps = true - WHERE grp_ID = ' . $groupID; + WHERE grp_ID = '.$groupID; RunQuery($sSQL); - $sSQLp = 'CREATE TABLE groupprop_' . $groupID . " ( + $sSQLp = 'CREATE TABLE groupprop_'.$groupID." ( per_ID mediumint(8) unsigned NOT NULL default '0', PRIMARY KEY (per_ID), UNIQUE KEY per_ID (per_ID) @@ -271,7 +269,7 @@ public function enableGroupSpecificProperties($groupID) $groupMembers = $this->getGroupMembers($groupID); foreach ($groupMembers as $member) { - $sSQLr = 'INSERT INTO groupprop_' . $groupID . " ( per_ID ) VALUES ( '" . $member['per_ID'] . "' );"; + $sSQLr = 'INSERT INTO groupprop_'.$groupID." ( per_ID ) VALUES ( '".$member['per_ID']."' );"; RunQuery($sSQLr); } } @@ -279,15 +277,15 @@ public function enableGroupSpecificProperties($groupID) public function disableGroupSpecificProperties($groupID) { requireUserGroupMembership('bManageGroups'); - $sSQLp = 'DROP TABLE groupprop_' . $groupID; + $sSQLp = 'DROP TABLE groupprop_'.$groupID; RunQuery($sSQLp); // need to delete the master index stuff - $sSQLp = 'DELETE FROM groupprop_master WHERE grp_ID = ' . $groupID; + $sSQLp = 'DELETE FROM groupprop_master WHERE grp_ID = '.$groupID; RunQuery($sSQLp); $sSQL = 'UPDATE group_grp SET grp_hasSpecialProps = false - WHERE grp_ID = ' . $groupID; + WHERE grp_ID = '.$groupID; RunQuery($sSQL); } @@ -297,7 +295,7 @@ public function getGroupMembers($groupID, $personID = null) global $cnInfoCentral; $whereClause = ''; if (is_numeric($personID)) { - $whereClause = ' AND p2g2r_per_ID = ' . $personID; + $whereClause = ' AND p2g2r_per_ID = '.$personID; } $members = []; @@ -311,7 +309,7 @@ public function getGroupMembers($groupID, $personID = null) group_grp.grp_RoleListID = list_lst.lst_ID AND person2group2role_p2g2r.p2g2r_rle_ID = list_lst.lst_OptionID - WHERE p2g2r_grp_ID =' . $groupID . ' ' . $whereClause; + 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 diff --git a/src/ChurchCRM/Service/MailChimpService.php b/src/ChurchCRM/Service/MailChimpService.php index 44a5513671..1c0ba48520 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,50 @@ 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"); + 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"); + $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', + '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"] - ]); + '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 +88,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,6 +101,7 @@ public function getLists() if (!$this->isActive()) { return new Exception(gettext('Mailchimp is not active')); } + return $this->getListsFromCache(); } @@ -104,7 +109,7 @@ 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 7c6854632a..1529ee0cde 100644 --- a/src/ChurchCRM/Service/NewDashboardService.php +++ b/src/ChurchCRM/Service/NewDashboardService.php @@ -9,7 +9,7 @@ public static function getDashboardItems($PageName) $DashboardItems = [ \ChurchCRM\Dashboard\EventsMenuItems::class, \ChurchCRM\Dashboard\ClassificationDashboardItem::class, - \ChurchCRM\Dashboard\CurrentLocaleMetadata::class + \ChurchCRM\Dashboard\CurrentLocaleMetadata::class, ]; $ReturnValues = []; foreach ($DashboardItems as $DashboardItem) { @@ -17,6 +17,7 @@ public static function getDashboardItems($PageName) array_push($ReturnValues, $DashboardItem); } } + return $ReturnValues; } @@ -26,6 +27,7 @@ public static function getValues($PageName) foreach (self::getDashboardItems($PageName) as $DashboardItem) { $ReturnValues[$DashboardItem::getDashboardItemName()] = $DashboardItem::getDashboardItemValue(); } + return $ReturnValues; } } diff --git a/src/ChurchCRM/Service/NotificationService.php b/src/ChurchCRM/Service/NotificationService.php index b6a057dd66..4738b2c3ac 100644 --- a/src/ChurchCRM/Service/NotificationService.php +++ b/src/ChurchCRM/Service/NotificationService.php @@ -2,8 +2,8 @@ namespace ChurchCRM\Service; -use ChurchCRM\dto\SystemConfig; use ChurchCRM\Authentication\AuthenticationManager; +use ChurchCRM\dto\SystemConfig; use ChurchCRM\Utils\MiscUtils; class NotificationService @@ -12,19 +12,19 @@ public static function updateNotifications(): void { /** Get the latest notifications from the source. Store in session variable */ try { - $notificationFileContents = file_get_contents(SystemConfig::getValue("sNotificationsURL")); + $notificationFileContents = file_get_contents(SystemConfig::getValue('sNotificationsURL')); MiscUtils::throwIfFailed($notificationFileContents); $tempNotifications = json_decode($notificationFileContents, null, 512, JSON_THROW_ON_ERROR); if (isset($tempNotifications->TTL)) { $_SESSION['SystemNotifications'] = $tempNotifications; $expires = (new \DateTimeImmutable()) - ->add(new \DateInterval("PT" . $_SESSION['SystemNotifications']->TTL . "S")); + ->add(new \DateInterval('PT'.$_SESSION['SystemNotifications']->TTL.'S')); $_SESSION['SystemNotifications']->expires = $expires; } } 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. + //a failure here should never prevent the page from loading. + //Possibly log an exception when a unified logger is implemented. + //for now, do nothing. } } @@ -35,7 +35,7 @@ public static function getNotifications(): array if (isset($_SESSION['SystemNotifications'])) { foreach ($_SESSION['SystemNotifications']->messages as $message) { if ($message->targetVersion === $_SESSION['sSoftwareInstalledVersion']) { - if (!$message->adminOnly || AuthenticationManager::getCurrentUser()->isAdmin()) { + if (!$message->adminOnly || AuthenticationManager::getCurrentUser()->isAdmin()) { array_push($notifications, $message); } } diff --git a/src/ChurchCRM/Service/PersonService.php b/src/ChurchCRM/Service/PersonService.php index 365881b88d..daecbe14eb 100644 --- a/src/ChurchCRM/Service/PersonService.php +++ b/src/ChurchCRM/Service/PersonService.php @@ -9,7 +9,7 @@ class PersonService { public function search($searchTerm, $includeFamilyRole = true) { - $searchLikeString = '%' . $searchTerm . '%'; + $searchLikeString = '%'.$searchTerm.'%'; $people = PersonQuery::create()-> filterByFirstName($searchLikeString, Criteria::LIKE)-> _or()->filterByLastName($searchLikeString, Criteria::LIKE)-> @@ -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 f38ce6b269..ce97ee1b35 100644 --- a/src/ChurchCRM/Service/SundaySchoolService.php +++ b/src/ChurchCRM/Service/SundaySchoolService.php @@ -49,13 +49,13 @@ public function getClassByRole($groupId, $role) { $sql = 'select person_per.* from person_per,group_grp grp, person2group2role_p2g2r person_grp, list_lst lst - where grp.grp_ID = ' . $groupId . " + where grp.grp_ID = '.$groupId." and grp_Type = 4 and grp.grp_ID = person_grp.p2g2r_grp_ID and person_grp.p2g2r_per_ID = per_ID and lst.lst_ID = grp.grp_RoleListID and lst.lst_OptionID = person_grp.p2g2r_rle_ID - and lst.lst_OptionName = '" . $role . "' + and lst.lst_OptionName = '".$role."' order by per_FirstName"; $rsMembers = RunQuery($sql); $members = []; @@ -146,18 +146,18 @@ public function getKidsBirthdayMonth($groupId) } } - 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, ]; } @@ -180,7 +180,7 @@ public function getKidsFullDetails($groupId) left Join person_per dad on fam.fam_id = dad.per_fam_id and dad.per_Gender = 1 and ( dad.per_fmr_ID = 1 or dad.per_fmr_ID = 2) left join person_per mom on fam.fam_id = mom.per_fam_id and mom.per_Gender = 2 and (mom.per_fmr_ID = 1 or mom.per_fmr_ID = 2),`group_grp` grp, `person2group2role_p2g2r` person_grp - where kid.per_fam_id = fam.fam_ID and grp.grp_ID = ' . $groupId . " + where kid.per_fam_id = fam.fam_ID and grp.grp_ID = '.$groupId." and fam.fam_DateDeactivated is null and grp_Type = 4 and grp.grp_ID = person_grp.p2g2r_grp_ID and person_grp.p2g2r_per_ID = kid.per_ID and lst.lst_OptionID = person_grp.p2g2r_rle_ID and lst.lst_ID = grp.grp_RoleListID and lst.lst_OptionName = 'Student' diff --git a/src/ChurchCRM/Service/SystemService.php b/src/ChurchCRM/Service/SystemService.php index 5bad845d11..6bed7bbe77 100644 --- a/src/ChurchCRM/Service/SystemService.php +++ b/src/ChurchCRM/Service/SystemService.php @@ -7,19 +7,17 @@ use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; use ChurchCRM\Utils\ChurchCRMReleaseManager; -use ChurchCRM\Utils\InputUtils; use ChurchCRM\Utils\LoggerUtils; 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 { 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, 512, JSON_THROW_ON_ERROR); $version = $composerJson['version']; @@ -28,7 +26,7 @@ public static function getInstalledVersion() public static function getCopyrightDate() { - return (new \DateTime())->format("Y"); + return (new \DateTime())->format('Y'); } public function getConfigurationSetting($settingName, $settingValue) @@ -49,6 +47,7 @@ public static function getDBVersion() $statement->execute(); $results = $statement->fetchAll(\PDO::FETCH_ASSOC); rsort($results); + return $results[0]['ver_version']; } @@ -57,19 +56,20 @@ public static function getDBServerVersion() try { return Propel::getServiceContainer()->getConnection()->getAttribute(PDO::ATTR_SERVER_VERSION); } catch (\Exception $exc) { - return "Could not obtain DB Server Version"; + return 'Could not obtain DB Server Version'; } } public static function getPrerequisiteStatus() { if (AppIntegrityService::arePrerequisitesMet()) { - return "All Prerequisites met"; + return 'All Prerequisites met'; } else { $unmet = AppIntegrityService::getUnmetPrerequisites(); - $unmetNames = array_map(fn($o) => (string)($o->getName()), $unmet); - return "Missing Prerequisites: " . json_encode(array_values($unmetNames), JSON_THROW_ON_ERROR); + $unmetNames = array_map(fn ($o) => (string) $o->getName(), $unmet); + + return 'Missing Prerequisites: '.json_encode(array_values($unmetNames), JSON_THROW_ON_ERROR); } } @@ -79,83 +79,81 @@ private static function isTimerThresholdExceeded(string $LastTime, int $Threshol return true; } $tz = new \DateTimeZone(SystemConfig::getValue('sTimeZone')); - $now = new \DateTime("now", $tz); //get the current time + $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 ; + $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")); + // 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::FULL_BACKUP, 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"); + LoggerUtils::getAppLogger()->info('Backup job successful'); } else { - LoggerUtils::getAppLogger()->info("Not starting a backup job. Last backup run: " . SystemConfig::getValue('sLastBackupTimeStamp') . "."); + 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()); + 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 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, JSON_THROW_ON_ERROR)); $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"); + LoggerUtils::getAppLogger()->info('Application integrity check passed'); } else { - LoggerUtils::getAppLogger()->warning("Application integrity check failed: " . $appIntegrity['message']); + 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')); + 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 + // 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 + //select maximum upload size $max_upload = SystemService::parseSize(ini_get('upload_max_filesize')); - //select post limit + //select post limit $max_post = SystemService::parseSize(ini_get('post_max_size')); - //select memory limit + //select memory limit $memory_limit = SystemService::parseSize(ini_get('memory_limit')); - // return the smallest of them, this defines the real limit + // return the smallest of them, this defines the real limit if ($humanFormat) { return SystemService::humanFilesize(min($max_upload, $max_post, $memory_limit)); } else { @@ -168,7 +166,7 @@ private static function parseSize(string $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. + // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. return round($size * 1024 ** stripos('bkmgtpezy', $unit[0])); } else { return round($size); @@ -179,6 +177,7 @@ private static function humanFilesize($bytes, $decimals = 2) { $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; $factor = floor((strlen($bytes) - 1) / 3); - return sprintf("%.{$decimals}f", $bytes / 1024 ** $factor) . @$size[$factor]; + + return sprintf("%.{$decimals}f", $bytes / 1024 ** $factor).@$size[$factor]; } } diff --git a/src/ChurchCRM/Service/TaskService.php b/src/ChurchCRM/Service/TaskService.php index bb07bfc185..d0fa71122c 100644 --- a/src/ChurchCRM/Service/TaskService.php +++ b/src/ChurchCRM/Service/TaskService.php @@ -2,27 +2,27 @@ 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\TaskInterface; use ChurchCRM\Tasks\LatestReleaseTask; use ChurchCRM\Tasks\PersonClassificationDataCheck; use ChurchCRM\Tasks\PersonGenderDataCheck; use ChurchCRM\Tasks\PersonRoleDataCheck; -use ChurchCRM\Tasks\PrerequisiteCheckTask; -use ChurchCRM\Tasks\UpdateFamilyCoordinatesTask; -use ChurchCRM\Tasks\CheckExecutionTimeTask; -use ChurchCRM\Tasks\PreUpgradeTaskInterface; use ChurchCRM\Tasks\PHPPendingDeprecationVersionCheckTask; -use ChurchCRM\Tasks\UnsupportedDepositCheck; use ChurchCRM\Tasks\PHPZipArchiveCheckTask; +use ChurchCRM\Tasks\PrerequisiteCheckTask; +use ChurchCRM\Tasks\PreUpgradeTaskInterface; use ChurchCRM\Tasks\SecretsConfigurationCheckTask; +use ChurchCRM\Tasks\TaskInterface; +use ChurchCRM\Tasks\UnsupportedDepositCheck; +use ChurchCRM\Tasks\UpdateFamilyCoordinatesTask; class TaskService { @@ -31,7 +31,7 @@ class TaskService */ private $taskClasses; private array $notificationClasses = [ - // new LatestReleaseTask() + // new LatestReleaseTask() ]; public function __construct() @@ -53,7 +53,7 @@ public function __construct() new UnsupportedDepositCheck(), new SecretsConfigurationCheckTask(), new PHPPendingDeprecationVersionCheckTask(), - new PHPZipArchiveCheckTask() + new PHPZipArchiveCheckTask(), ]; } @@ -63,11 +63,12 @@ public function getCurrentUserTasks(): array 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; } @@ -78,15 +79,16 @@ public function getTaskNotifications(): array if ($taskClass->isActive()) { array_push( $tasks, - new UiNotification($taskClass->getTitle(), "wrench", $taskClass->getLink(), $taskClass->getDesc(), ($taskClass->isAdmin() ? "warning" : "info"), "12000", "bottom", "left") + new UiNotification($taskClass->getTitle(), 'wrench', $taskClass->getLink(), $taskClass->getDesc(), $taskClass->isAdmin() ? 'warning' : 'info', '12000', 'bottom', 'left') ); } } + return $tasks; } public function getActivePreUpgradeTasks(): array { - return array_filter($this->taskClasses, fn($k) => $k instanceof PreUpgradeTaskInterface && $k->isActive()); + return array_filter($this->taskClasses, fn ($k) => $k instanceof PreUpgradeTaskInterface && $k->isActive()); } } diff --git a/src/ChurchCRM/Service/TimelineService.php b/src/ChurchCRM/Service/TimelineService.php index 29e0579f8c..814a633cd2 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 { @@ -60,6 +60,7 @@ private function eventsForPerson($personID) $timeline[$item['key']] = $item; } } + return $timeline; } @@ -122,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()); @@ -134,8 +135,8 @@ public function noteToTimelineItem($dbNote) $dbNote->getId(), $dbNote->getType(), $dbNote->getDisplayEditedDate(), - $dbNote->getDisplayEditedDate("Y"), - gettext('by') . ' ' . $displayEditedBy, + $dbNote->getDisplayEditedDate('Y'), + gettext('by').' '.$displayEditedBy, '', $dbNote->getText(), $dbNote->getEditLink(), @@ -190,7 +191,7 @@ public function createTimeLineItem($id, $type, $datetime, $year, $header, $heade $item['datetime'] = $datetime; $item['year'] = $year; - $item['key'] = $datetime . '-' . $id; + $item['key'] = $datetime.'-'.$id; return $item; } diff --git a/src/ChurchCRM/Service/UpgradeService.php b/src/ChurchCRM/Service/UpgradeService.php index 0217498a09..5738145d19 100644 --- a/src/ChurchCRM/Service/UpgradeService.php +++ b/src/ChurchCRM/Service/UpgradeService.php @@ -4,16 +4,16 @@ * 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\Utils\MiscUtils; +use ChurchCRM\Version; use Propel\Runtime\Propel; class UpgradeService @@ -26,8 +26,8 @@ public static function upgradeDatabaseVersion() $logger->info( "Current Version: $db_version", [ - 'dbVersion' => $db_version, - 'softwareInstalledVersion' => $_SESSION['sSoftwareInstalledVersion'] + 'dbVersion' => $db_version, + 'softwareInstalledVersion' => $_SESSION['sSoftwareInstalledVersion'], ] ); if ($db_version === $_SESSION['sSoftwareInstalledVersion']) { @@ -38,7 +38,7 @@ public static function upgradeDatabaseVersion() try { $connection = Propel::getConnection(); - $dbUpdatesFile = file_get_contents(SystemURLs::getDocumentRoot() . '/mysql/upgrade.json'); + $dbUpdatesFile = file_get_contents(SystemURLs::getDocumentRoot().'/mysql/upgrade.json'); MiscUtils::throwIfFailed($dbUpdatesFile); $dbUpdates = json_decode($dbUpdatesFile, true, 512, JSON_THROW_ON_ERROR); @@ -52,16 +52,16 @@ public static function upgradeDatabaseVersion() $version->setVersion($dbUpdate['dbVersion']); $version->setUpdateStart(new \DateTimeImmutable()); - $logger->info("New Version: " . $version->getVersion()); + $logger->info('New Version: '.$version->getVersion()); $scriptName = null; foreach ($dbUpdate['scripts'] as $dbScript) { - $scriptName = SystemURLs::getDocumentRoot() . $dbScript; + $scriptName = SystemURLs::getDocumentRoot().$dbScript; - $logger->info("Upgrade DB - " . $scriptName); - if (pathinfo($scriptName, PATHINFO_EXTENSION) === "sql") { + $logger->info('Upgrade DB - '.$scriptName); + if (pathinfo($scriptName, PATHINFO_EXTENSION) === 'sql') { SQLUtils::sqlImport($scriptName, $connection); - } elseif (pathinfo($scriptName, PATHINFO_EXTENSION) === "php") { - require_once($scriptName); + } elseif (pathinfo($scriptName, PATHINFO_EXTENSION) === 'php') { + require_once $scriptName; } else { throw new \Exception("Invalid upgrade file specified: $scriptName"); } @@ -72,18 +72,18 @@ public static function upgradeDatabaseVersion() sleep(2); } - // increment the number of scripts executed. - // If no scripts run, then there is no supported upgrade path defined in the JSON file + // 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( - 'Failure executing upgrade script(s): ' . $exc->getMessage(), + 'Failure executing upgrade script(s): '.$exc->getMessage(), [ - 'exception' => $exc, - 'scriptName' => $scriptName, - 'version' => $version->getVersion(), - 'numUpgradeScriptsExecuted' => $upgradeScriptsExecuted, + 'exception' => $exc, + 'scriptName' => $scriptName, + 'version' => $version->getVersion(), + 'numUpgradeScriptsExecuted' => $upgradeScriptsExecuted, ] ); @@ -92,15 +92,15 @@ public static function upgradeDatabaseVersion() } if ($upgradeScriptsExecuted === 0) { - $logger->warning("No upgrade path for " . SystemService::getDBVersion() . " to " . $_SESSION['sSoftwareInstalledVersion']); + $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( - "Database upgrade failed: " . $exc->getMessage(), + 'Database upgrade failed: '.$exc->getMessage(), ['exception' => $exc] ); diff --git a/src/ChurchCRM/Slim/Middleware/AuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/AuthMiddleware.php index 2ea56be32d..52de91c535 100644 --- a/src/ChurchCRM/Slim/Middleware/AuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/AuthMiddleware.php @@ -11,15 +11,16 @@ 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')); } - } else if (AuthenticationManager::validateUserSessionIsActive(!$this->isPath($request, "background"))) { + } elseif (AuthenticationManager::validateUserSessionIsActive(!$this->isPath($request, 'background'))) { // validate the user session; however, do not update tLastOperation if the requested path is "/background" // since /background operations do not connotate user activity. @@ -29,17 +30,19 @@ public function __invoke(Request $request, Response $response, callable $next) 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); } private function isPath(Request $request, $pathPart) { - $pathAry = explode("/", $request->getUri()->getPath()); + $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 69725380c5..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 5193d27985..7daca37589 100644 --- a/src/ChurchCRM/Slim/Middleware/MailChimpMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/MailChimpMiddleware.php @@ -12,10 +12,11 @@ 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); + $request = $request->withAttribute('mailchimpService', $mailchimpService); + return $next($request, $response); } } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Auth/BaseAuthRoleMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Auth/BaseAuthRoleMiddleware.php index d0c3b6cafc..8b0de2e832 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Auth/BaseAuthRoleMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Auth/BaseAuthRoleMiddleware.php @@ -10,7 +10,7 @@ abstract class BaseAuthRoleMiddleware { /** - * @var User $user + * @var User */ protected $user; @@ -24,6 +24,7 @@ public function __invoke(Request $request, Response $response, callable $next) if (!$this->hasRole()) { return $response->withStatus(403, $this->noRoleMessage()); } + return $next($request, $response); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/FamilyAPIMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/FamilyAPIMiddleware.php index 36ee189d20..93dc95c3fd 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/FamilyAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/FamilyAPIMiddleware.php @@ -10,18 +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 82d6924eba..7adb3bc6df 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/GroupAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/GroupAPIMiddleware.php @@ -10,18 +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 42ab4d43da..d23bec915c 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/PersonAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/PersonAPIMiddleware.php @@ -10,18 +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 1573a90e06..226f40cdfe 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/PropertyAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/PropertyAPIMiddleware.php @@ -18,23 +18,24 @@ public function __construct(string $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 65aa3417b0..d13b709945 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(); } diff --git a/src/ChurchCRM/Slim/Middleware/Request/Setting/BaseAuthSettingMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Setting/BaseAuthSettingMiddleware.php index 2a0ae0641e..001fb63338 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Setting/BaseAuthSettingMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Setting/BaseAuthSettingMiddleware.php @@ -11,7 +11,7 @@ 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); diff --git a/src/ChurchCRM/Slim/Middleware/Request/Setting/PublicRegistrationAuthMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/Setting/PublicRegistrationAuthMiddleware.php index c2b9a3fc10..51664fc67a 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/Setting/PublicRegistrationAuthMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/Setting/PublicRegistrationAuthMiddleware.php @@ -6,6 +6,6 @@ class PublicRegistrationAuthMiddleware extends BaseAuthSettingMiddleware { protected function getSettingName() { - return "bEnableSelfRegistration"; + return 'bEnableSelfRegistration'; } } diff --git a/src/ChurchCRM/Slim/Middleware/Request/UserAPIMiddleware.php b/src/ChurchCRM/Slim/Middleware/Request/UserAPIMiddleware.php index 119b9c65f9..24c1051ace 100644 --- a/src/ChurchCRM/Slim/Middleware/Request/UserAPIMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/Request/UserAPIMiddleware.php @@ -11,9 +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(); @@ -22,13 +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 ed8a383125..5828737c19 100644 --- a/src/ChurchCRM/Slim/Middleware/VersionMiddleware.php +++ b/src/ChurchCRM/Slim/Middleware/VersionMiddleware.php @@ -10,6 +10,6 @@ class VersionMiddleware { public function __invoke(Request $request, Response $response, callable $next) { - return $next($request, $response)->withHeader("CRM_VERSION", SystemService::getInstalledVersion()); + return $next($request, $response)->withHeader('CRM_VERSION', SystemService::getInstalledVersion()); } } diff --git a/src/ChurchCRM/SystemCalendars/AnniversariesCalendar.php b/src/ChurchCRM/SystemCalendars/AnniversariesCalendar.php index 277dfb1205..cb42388c19 100644 --- a/src/ChurchCRM/SystemCalendars/AnniversariesCalendar.php +++ b/src/ChurchCRM/SystemCalendars/AnniversariesCalendar.php @@ -2,12 +2,11 @@ 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 { @@ -23,12 +22,12 @@ public function getAccessToken() public function getBackgroundColor() { - return "000000"; + return '000000'; } public function getForegroundColor() { - return "FFFFFF"; + return 'FFFFFF'; } public function getId() @@ -38,7 +37,7 @@ public function getId() public function getName() { - return gettext("Anniversaries"); + return gettext('Anniversaries'); } public function getEvents($start, $end) @@ -46,6 +45,7 @@ public function getEvents($start, $end) $families = FamilyQuery::create() ->filterByWeddingdate('', Criteria::NOT_EQUAL) ->find(); + return $this->familyCollectionToEvents($families); } @@ -55,6 +55,7 @@ public function getEventById($Id) ->filterByWeddingdate('', Criteria::NOT_EQUAL) ->filterById($Id) ->find(); + return $this->familyCollectionToEvents($families); } @@ -66,12 +67,13 @@ private function familyCollectionToEvents(ObjectCollection $Families) $anniversary = new Event(); $anniversary->setId($family->getId()); $anniversary->setEditable(false); - $anniversary->setTitle(gettext("Anniversary") . ": " . $family->getFamilyString()); + $anniversary->setTitle(gettext('Anniversary').': '.$family->getFamilyString()); $year = date('Y'); - $anniversary->setStart($year . '-' . $family->getWeddingMonth() . '-' . $family->getWeddingDay()); + $anniversary->setStart($year.'-'.$family->getWeddingMonth().'-'.$family->getWeddingDay()); $anniversary->setURL($family->getViewURI()); $events->push($anniversary); } + return $events; } } diff --git a/src/ChurchCRM/SystemCalendars/BirthdaysCalendar.php b/src/ChurchCRM/SystemCalendars/BirthdaysCalendar.php index 80751e9a90..29a550f39a 100644 --- a/src/ChurchCRM/SystemCalendars/BirthdaysCalendar.php +++ b/src/ChurchCRM/SystemCalendars/BirthdaysCalendar.php @@ -2,12 +2,11 @@ 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 { @@ -23,12 +22,12 @@ public function getAccessToken() public function getBackgroundColor() { - return "0000FF"; + return '0000FF'; } public function getForegroundColor() { - return "FFFFFF"; + return 'FFFFFF'; } public function getId() @@ -38,7 +37,7 @@ public function getId() public function getName() { - return gettext("Birthdays"); + return gettext('Birthdays'); } public function getEvents($start, $end) @@ -46,6 +45,7 @@ public function getEvents($start, $end) $people = PersonQuery::create() ->filterByBirthDay('', Criteria::NOT_EQUAL) ->find(); + return $this->peopleCollectionToEvents($people); } @@ -55,6 +55,7 @@ public function getEventById($Id) ->filterByBirthDay('', Criteria::NOT_EQUAL) ->filterById($Id) ->find(); + return $this->peopleCollectionToEvents($people); } @@ -67,12 +68,13 @@ private function peopleCollectionToEvents(ObjectCollection $People) $birthday->setId($person->getId()); $birthday->setEditable(false); $year = date('Y'); - $birthday->setStart($year . '-' . $person->getBirthMonth() . '-' . $person->getBirthDay()); + $birthday->setStart($year.'-'.$person->getBirthMonth().'-'.$person->getBirthDay()); $age = $person->getAge($birthday->getStart()); - $birthday->setTitle(gettext("Birthday") . ": " . $person->getFullName() . ( $age ? " (" . $age . ")" : '' )); + $birthday->setTitle(gettext('Birthday').': '.$person->getFullName().($age ? ' ('.$age.')' : '')); $birthday->setURL($person->getViewURI()); $events->push($birthday); } + return $events; } } diff --git a/src/ChurchCRM/SystemCalendars/HolidayCalendar.php b/src/ChurchCRM/SystemCalendars/HolidayCalendar.php index 19befcad6e..0642fd3560 100644 --- a/src/ChurchCRM/SystemCalendars/HolidayCalendar.php +++ b/src/ChurchCRM/SystemCalendars/HolidayCalendar.php @@ -2,23 +2,19 @@ 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")); + $systemCountry = Countries::getCountryByName(SystemConfig::getValue('sChurchCountry')); if (!empty($systemCountry)) { return $systemCountry->getCountryNameYasumi() !== null; } @@ -31,12 +27,12 @@ public function getAccessToken() public function getBackgroundColor() { - return "6dfff5"; + return '6dfff5'; } public function getForegroundColor() { - return "000000"; + return '000000'; } public function getId() @@ -46,12 +42,12 @@ public function getId() public function getName() { - return gettext("Holidays"); + return gettext('Holidays'); } public function getEvents($start, $end) { - $Country = Countries::getCountryByName(SystemConfig::getValue("sChurchCountry")); + $Country = Countries::getCountryByName(SystemConfig::getValue('sChurchCountry')); $year = date('Y'); $holidays = Yasumi::create($Country->getCountryNameYasumi(), $year); $events = new ObjectCollection(); @@ -61,6 +57,7 @@ public function getEvents($start, $end) $event = $this->yasumiHolidayToEvent($holiday); $events->push($event); } + return $events; } @@ -71,12 +68,13 @@ public function getEventById($Id) private function yasumiHolidayToEvent(Holiday $holiday) { - $id = crc32($holiday->getName() . $holiday->getTimestamp()); + $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 15ccf312f1..619ba98190 100644 --- a/src/ChurchCRM/SystemCalendars/UnpinnedEvents.php +++ b/src/ChurchCRM/SystemCalendars/UnpinnedEvents.php @@ -2,10 +2,8 @@ namespace ChurchCRM\SystemCalendars; -use ChurchCRM\Interfaces\SystemCalendar; -use ChurchCRM\PersonQuery; use ChurchCRM\EventQuery; -use Propel\Runtime\ActiveQuery\Criteria; +use ChurchCRM\Interfaces\SystemCalendar; class UnpinnedEvents implements SystemCalendar { @@ -21,12 +19,12 @@ public function getAccessToken() public function getBackgroundColor() { - return "FF0000"; + return 'FF0000'; } public function getForegroundColor() { - return "FFFFFF"; + return 'FFFFFF'; } public function getId() @@ -36,18 +34,19 @@ public function getId() public function getName() { - return gettext("Unpinned Events"); + return gettext('Unpinned Events'); } public function getEvents($start, $end) { $Events = EventQuery::create() - ->filterByStart(["min" => $start]) - ->filterByEnd(["max" => $end]) + ->filterByStart(['min' => $start]) + ->filterByEnd(['max' => $end]) ->useCalendarEventQuery(null, \Propel\Runtime\ActiveQuery\Criteria::LEFT_JOIN) ->filterByCalendarId(null) ->endUse() ->find(); + return $Events; } @@ -55,6 +54,7 @@ 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 6403221312..7aa1e06326 100644 --- a/src/ChurchCRM/data/Countries.php +++ b/src/ChurchCRM/data/Countries.php @@ -9,264 +9,265 @@ class Countries 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') + '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(); @@ -275,32 +276,35 @@ private static function getSingleName(Country $Country) public static function getNames() { self::initializeCountries(); - return array_map(["self","getSingleName"], self::$countries); + + return array_map(['self', 'getSingleName'], self::$countries); } public static function getAll() { self::initializeCountries(); + return self::$countries; } public static function getCountry(string $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, fn($e) => $e->getCountryName() === $CountryName); + $result = array_filter(self::$countries, fn ($e) => $e->getCountryName() === $CountryName); if (count($result) === 1) { return current($result); } - throw new \Exception(gettext("Invalid country name supplied")); + + throw new \Exception(gettext('Invalid country name supplied')); } } diff --git a/src/ChurchCRM/data/Country.php b/src/ChurchCRM/data/Country.php index d68885fbf3..0abb42bd0f 100644 --- a/src/ChurchCRM/data/Country.php +++ b/src/ChurchCRM/data/Country.php @@ -33,8 +33,8 @@ public function getCountryNameYasumi(): ?string public function jsonSerialize(): array { return [ - 'name' => $this->countryName, - 'code' => $this->countryCode, + 'name' => $this->countryName, + 'code' => $this->countryCode, ]; } } diff --git a/src/ChurchCRM/data/States.php b/src/ChurchCRM/data/States.php index dd1f69bdba..17aaf42867 100644 --- a/src/ChurchCRM/data/States.php +++ b/src/ChurchCRM/data/States.php @@ -14,7 +14,7 @@ public function __construct($countryCode) { $this->countryCode = $countryCode; - $stateFileName = SystemURLs::getDocumentRoot() . '/locale/states/' . $countryCode . '.json'; + $stateFileName = SystemURLs::getDocumentRoot().'/locale/states/'.$countryCode.'.json'; if (is_file($stateFileName)) { $statesFile = file_get_contents($stateFileName); MiscUtils::throwIfFailed($statesFile); diff --git a/src/ChurchCRM/dto/Cart.php b/src/ChurchCRM/dto/Cart.php index 340e49c92b..0c6717e95e 100644 --- a/src/ChurchCRM/dto/Cart.php +++ b/src/ChurchCRM/dto/Cart.php @@ -15,14 +15,15 @@ private static function checkCart() $_SESSION['aPeopleCart'] = []; } } + public static function addPerson($PersonID) { self::checkCart(); if (!is_numeric($PersonID)) { - throw new \Exception(gettext("PersonID for Cart must be numeric"), 400); + throw new \Exception(gettext('PersonID for Cart must be numeric'), 400); } if ($PersonID !== null && !in_array($PersonID, $_SESSION['aPeopleCart'], false)) { - array_push($_SESSION['aPeopleCart'], (int)$PersonID); + array_push($_SESSION['aPeopleCart'], (int) $PersonID); } } @@ -36,7 +37,7 @@ public static function addPersonArray($PersonArray) public static function addGroup($GroupID) { if (!is_numeric($GroupID)) { - throw new \Exception(gettext("GroupID for Cart must be numeric"), 400); + throw new \Exception(gettext('GroupID for Cart must be numeric'), 400); } $GroupMembers = Person2group2roleP2g2rQuery::create() ->filterByGroupId($GroupID) @@ -49,7 +50,7 @@ public static function addGroup($GroupID) public static function addFamily($FamilyID) { if (!is_numeric($FamilyID)) { - throw new \Exception(gettext("FamilyID for Cart must be numeric"), 400); + throw new \Exception(gettext('FamilyID for Cart must be numeric'), 400); } $FamilyMembers = PersonQuery::create() ->filterByFamId($FamilyID) @@ -68,10 +69,10 @@ public static function intersectArrayWithPeopleCart($aIDs) public static function removePerson($PersonID) { - // make sure the cart array exists - // we can't remove anybody if there is no cart + // 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); + 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 @@ -81,8 +82,8 @@ public static function removePerson($PersonID) public static function removePersonArray($aIDs) { - // make sure the cart array exists - // we can't remove anybody if there is no cart + // 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)); } @@ -91,7 +92,7 @@ public static function removePersonArray($aIDs) public static function removeGroup($GroupID) { if (!is_numeric($GroupID)) { - throw new \Exception(gettext("GroupID for Cart must be numeric"), 400); + throw new \Exception(gettext('GroupID for Cart must be numeric'), 400); } $GroupMembers = Person2group2roleP2g2rQuery::create() ->filterByGroupId($GroupID) @@ -116,12 +117,12 @@ public static function convertCartToString($aCartArray) // Implode the array $sCartString = implode(',', $aCartArray); - // Make sure the comma is chopped off the end + // 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 + // Make sure there are no duplicate commas $sCartString = str_replace(',,', '', $sCartString); return $sCartString; @@ -135,6 +136,7 @@ public static function countFamilies() ->filterById($_SESSION['aPeopleCart']) ->orderByFamId() ->find(); + return $persons->count(); } @@ -156,19 +158,19 @@ public static function emptyToGroup($GroupID, $RoleID) ->setRoleId($RoleID) ->save(); - /* - This part of code should be done - */ + /* + 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]; + /* $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); - } */ + if ($bHasProp == 'true') { + $sSQL = 'INSERT INTO groupprop_'.$iGroupID." (per_ID) VALUES ('".$iPersonID."')"; + RunQuery($sSQL); + } */ $iCount += 1; } @@ -178,16 +180,16 @@ public static function emptyToGroup($GroupID, $RoleID) public static function getCartPeople() { - $people = PersonQuery::create() ->filterById($_SESSION['aPeopleCart']) ->find(); + return $people; } public static function getEmailLink() { - /* @var $cartPerson ChurchCRM\Person */ + /* @var $cartPerson ChurchCRM\Person */ $people = Cart::getCartPeople(); $emailAddressArray = []; foreach ($people as $cartPerson) { @@ -195,18 +197,18 @@ public static function getEmailLink() array_push($emailAddressArray, $cartPerson->getEmail()); } } - $delimiter = AuthenticationManager::getCurrentUser()->getUserConfigString("sMailtoDelimiter"); + $delimiter = AuthenticationManager::getCurrentUser()->getUserConfigString('sMailtoDelimiter'); $sEmailLink = implode($delimiter, array_unique(array_filter($emailAddressArray))); if (!empty(SystemConfig::getValue('sToEmailAddress')) && !stristr($sEmailLink, (string) SystemConfig::getValue('sToEmailAddress'))) { - $sEmailLink .= $delimiter . SystemConfig::getValue('sToEmailAddress'); + $sEmailLink .= $delimiter.SystemConfig::getValue('sToEmailAddress'); } + return $sEmailLink; } public static function getSMSLink() { - - /* @var $cartPerson ChurchCRM\Person */ + /* @var $cartPerson ChurchCRM\Person */ $people = Cart::getCartPeople(); $SMSNumberArray = []; foreach ($people as $cartPerson) { @@ -214,7 +216,8 @@ public static function getSMSLink() array_push($SMSNumberArray, $cartPerson->getCellPhone()); } } - $sSMSLink = implode(",", $SMSNumberArray); + $sSMSLink = implode(',', $SMSNumberArray); + return $sSMSLink; } diff --git a/src/ChurchCRM/dto/ChurchCRMRelease.php b/src/ChurchCRM/dto/ChurchCRMRelease.php index 7b6a3f0997..1480ccce38 100644 --- a/src/ChurchCRM/dto/ChurchCRMRelease.php +++ b/src/ChurchCRM/dto/ChurchCRMRelease.php @@ -13,13 +13,12 @@ class ChurchCRMRelease public function __construct(array $releaseArray) { $this->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) { return $this->MAJOR == $b->MAJOR && $this->MINOR == $b->MINOR && $this->PATCH == $b->PATCH; @@ -31,7 +30,7 @@ public function compareTo(ChurchCRMRelease $b) return -1; } 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) { @@ -51,7 +50,7 @@ public function compareTo(ChurchCRMRelease $b) public function __toString() { try { - return (string) $this->MAJOR . "." . $this->MINOR . "." . $this->PATCH; + return (string) $this->MAJOR.'.'.$this->MINOR.'.'.$this->PATCH; } catch (\Exception $exception) { return ''; } @@ -60,10 +59,11 @@ public function __toString() public function getDownloadURL() { foreach ($this->rawRelease['assets'] as $asset) { - if ($asset['name'] == "ChurchCRM-" . $this->rawRelease['name'] . ".zip") { + if ($asset['name'] == 'ChurchCRM-'.$this->rawRelease['name'].'.zip') { $url = $asset['browser_download_url']; } } + return $url; } diff --git a/src/ChurchCRM/dto/ChurchCRMReleaseManager.php b/src/ChurchCRM/dto/ChurchCRMReleaseManager.php index 87b2b335e5..676697ed34 100644 --- a/src/ChurchCRM/dto/ChurchCRMReleaseManager.php +++ b/src/ChurchCRM/dto/ChurchCRMReleaseManager.php @@ -24,23 +24,26 @@ public static function getReleaseFromString(string $releaseString): ChurchCRMRel // 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]); + 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'], fn($r) => $r->__toString() === $releaseString)); + LoggerUtils::getAppLogger()->debug('Attempting to service query for release string '.$releaseString.' from GitHub release cache'); + $requestedRelease = array_values(array_filter($_SESSION['ChurchCRMReleases'], fn ($r) => $r->__toString() === $releaseString)); 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) { // 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]); + 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, JSON_THROW_ON_ERROR)); + throw new \Exception('Provided string matched more than one ChurchCRM Release: '.\json_encode($requestedRelease, JSON_THROW_ON_ERROR)); } } } @@ -52,32 +55,31 @@ private static function populateReleases(): array { $client = new Client(); $eligibleReleases = []; - LoggerUtils::getAppLogger()->debug("Querying GitHub '" . ChurchCRMReleaseManager::GITHUB_USER_NAME . "/" . ChurchCRMReleaseManager::GITHUB_REPOSITORY_NAME . "' for ChurchCRM Releases"); + 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"); + 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"); + 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"); + 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"); + LoggerUtils::getAppLogger()->debug($release.' is not a pre-release version. Including for consideration'); array_push($eligibleReleases, $release); } } - usort($eligibleReleases, fn(ChurchCRMRelease $a, ChurchCRMRelease $b) => $a->compareTo($b) < 0); + usort($eligibleReleases, fn (ChurchCRMRelease $a, ChurchCRMRelease $b) => $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() { $_SESSION['ChurchCRMReleases'] = self::populateReleases(); @@ -93,7 +95,8 @@ public static function isReleaseCurrent(ChurchCRMRelease $Release): bool return true; } 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); } } @@ -101,9 +104,11 @@ public static function isReleaseCurrent(ChurchCRMRelease $Release): bool private static function getHighestReleaseInArray(array $eligibleUpgradeTargetReleases) { if (count($eligibleUpgradeTargetReleases) > 0) { - usort($eligibleUpgradeTargetReleases, fn(ChurchCRMRelease $a, ChurchCRMRelease $b) => $a->compareTo($b) < 0); + usort($eligibleUpgradeTargetReleases, fn (ChurchCRMRelease $a, ChurchCRMRelease $b) => $a->compareTo($b) < 0); + return $eligibleUpgradeTargetReleases[0]; } + return null; } @@ -111,9 +116,11 @@ private static function getReleaseNextPatch(array $rs, ChurchCRMRelease $current { $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); } @@ -121,9 +128,11 @@ private static function getReleaseNextMinor(array $rs, ChurchCRMRelease $current { $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); } @@ -131,16 +140,17 @@ private static function getReleaseNextMajor(array $rs, ChurchCRMRelease $current { $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); + LoggerUtils::getAppLogger()->debug('Determining the next-step release step for '.$currentRelease); if (empty($_SESSION['ChurchCRMReleases'])) { $_SESSION['ChurchCRMReleases'] = self::populateReleases(); } @@ -148,49 +158,51 @@ public static function getNextReleaseStep(ChurchCRMRelease $currentRelease): Chu // 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) ?? self::getReleaseNextMinor($rs, $currentRelease) ?? 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]) ; + 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); + $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; } @@ -205,14 +217,15 @@ public static function preShutdown() if (self::$isUpgradeInProgress) { // the PHP script was stopped while an upgrade was still in progress. $logger = LoggerUtils::getAppLogger(); - $logger->warning("Maximum execution time threshold exceeded: " . ini_get("max_execution_time")); + $logger->warning('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', ], JSON_THROW_ON_ERROR); } } + public static function doUpgrade($zipFilename, $sha1) { self::$isUpgradeInProgress = true; @@ -222,35 +235,35 @@ public static function doUpgrade($zipFilename, $sha1) // PHP instance's max_execution_time $displayErrors = ini_get('display_errors'); ini_set('display_errors', 0); - register_shutdown_function(fn() => ChurchCRMReleaseManager::preShutdown()); + register_shutdown_function(fn () => ChurchCRMReleaseManager::preShutdown()); $logger = LoggerUtils::getAppLogger(); - $logger->info("Beginning upgrade process"); - $logger->info("PHP max_execution_time is now: " . ini_get("max_execution_time")); - $logger->info("Beginning hash validation on " . $zipFilename); + $logger->info('Beginning 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(); - $isSuccessful = $zip->extractTo(SystemURLs::getDocumentRoot() . '/Upgrade'); - MiscUtils::throwIfFailed($isSuccessful); - $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(); + $isSuccessful = $zip->extractTo(SystemURLs::getDocumentRoot().'/Upgrade'); + MiscUtils::throwIfFailed($isSuccessful); + $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"); + $logger->debug('Set sLastIntegrityCheckTimeStamp to null'); + $logger->info('Upgrade process complete'); ini_set('display_errors', $displayErrors); self::$isUpgradeInProgress = false; @@ -258,7 +271,7 @@ public static function doUpgrade($zipFilename, $sha1) } else { self::$isUpgradeInProgress = false; ini_set('display_errors', $displayErrors); - $logger->error("Hash validation failed on " . $zipFilename . ". Expected: " . $sha1 . ". Got: " . sha1_file($zipFilename)); + $logger->error('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 8557339913..e0b220ce3b 100644 --- a/src/ChurchCRM/dto/ChurchMetaData.php +++ b/src/ChurchCRM/dto/ChurchMetaData.php @@ -19,7 +19,7 @@ public static function getChurchFullAddress() } if (!empty(self::getChurchCity())) { - array_push($address, self::getChurchCity() . ','); + array_push($address, self::getChurchCity().','); } if (!empty(self::getChurchState())) { @@ -81,6 +81,7 @@ public static function getChurchLatitude() if (empty(SystemConfig::getValue('iChurchLatitude'))) { self::updateLatLng(); } + return SystemConfig::getValue('iChurchLatitude'); } @@ -89,6 +90,7 @@ public static function getChurchLongitude() if (empty(SystemConfig::getValue('iChurchLongitude'))) { self::updateLatLng(); } + return SystemConfig::getValue('iChurchLongitude'); } diff --git a/src/ChurchCRM/dto/Classification.php b/src/ChurchCRM/dto/Classification.php index 4f8a4ecce4..92981922dd 100644 --- a/src/ChurchCRM/dto/Classification.php +++ b/src/ChurchCRM/dto/Classification.php @@ -17,6 +17,7 @@ public static function getName($clsId) if (!empty($classification)) { return $classification->getOptionName(); } - return ""; + + return ''; } } diff --git a/src/ChurchCRM/dto/ConfigItem.php b/src/ChurchCRM/dto/ConfigItem.php index 81a96141ab..f1e0a72942 100644 --- a/src/ChurchCRM/dto/ConfigItem.php +++ b/src/ChurchCRM/dto/ConfigItem.php @@ -42,7 +42,6 @@ public function getUrl() return $this->url; } - public function setDBConfigObject($dbConfigItem) { $this->dbConfigItem = $dbConfigItem; @@ -51,7 +50,7 @@ public function setDBConfigObject($dbConfigItem) public function getDBConfigObject() { - return $this->dbConfigItem ; + return $this->dbConfigItem; } public function getValue() @@ -77,14 +76,14 @@ public function setValue($value) $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 + //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 + //set the values, and save it $this->dbConfigItem->setValue($value); $this->dbConfigItem->save(); $this->value = $value; @@ -96,7 +95,6 @@ public function getDefault() return $this->default; } - public function getType() { return $this->type; diff --git a/src/ChurchCRM/dto/FullCalendarEvent.php b/src/ChurchCRM/dto/FullCalendarEvent.php index f5dd361f8e..9339b20b65 100644 --- a/src/ChurchCRM/dto/FullCalendarEvent.php +++ b/src/ChurchCRM/dto/FullCalendarEvent.php @@ -25,14 +25,14 @@ public static function createFromEvent(Event $CRMEvent, Calendar $CRMCalendar): $fce = new self(); $fce->title = $CRMEvent->getTitle(); - $fce->start = $CRMEvent->getStart("c"); - $fce->end = $CRMEvent->getEnd("c"); - $fce->allDay = ( $CRMEvent->getEnd() == null ? true : false); + $fce->start = $CRMEvent->getStart('c'); + $fce->end = $CRMEvent->getEnd('c'); + $fce->allDay = ($CRMEvent->getEnd() == null ? true : false); $fce->id = $CRMEvent->getId(); - $fce->backgroundColor = "#" . $CRMCalendar->getBackgroundColor(); - $fce->textColor = "#" . $CRMCalendar->getForegroundColor(); + $fce->backgroundColor = '#'.$CRMCalendar->getBackgroundColor(); + $fce->textColor = '#'.$CRMCalendar->getForegroundColor(); $fce->editable = $CRMEvent->isEditable(); - + $url = $CRMEvent->getURL(); if ($url) { $fce->url = $url; diff --git a/src/ChurchCRM/dto/LocaleInfo.php b/src/ChurchCRM/dto/LocaleInfo.php index 7ee91bc702..2568dc83f2 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, 512, JSON_THROW_ON_ERROR); 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/Notification.php b/src/ChurchCRM/dto/Notification.php index 6775bf6cd2..77c7884676 100644 --- a/src/ChurchCRM/dto/Notification.php +++ b/src/ChurchCRM/dto/Notification.php @@ -31,7 +31,7 @@ public function setEmailText($text) public function setPerson(\ChurchCRM\Person $Person) { - $this->person = $Person; + $this->person = $Person; } public function setProjectorText($text) @@ -45,9 +45,11 @@ private function sendEmail() foreach ($this->recipients as $recipient) { array_push($emailaddresses, $recipient->getEmail()); } + try { $email = new NotificationEmail($emailaddresses, $this->person->getFullName()); $emailStatus = $email->send(); + return $emailStatus; } catch (\Exception $ex) { return false; @@ -57,15 +59,16 @@ private function sendEmail() private function sendSMS() { try { - $client = new Client(new Basic(SystemConfig::getValue("sNexmoAPIKey"), SystemConfig::getValue("sNexmoAPISecret"))); + $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() + 'to' => $recipient->getNumericCellPhone(), + 'from' => SystemConfig::getValue('sNexmoFromNumber'), + 'text' => gettext('Notification for').' '.$this->person->getFullName(), ]); } + return $message; } catch (\Exception $ex) { return false; @@ -76,11 +79,12 @@ private function sendProjector() { try { $OLPAlert = new OpenLPNotification( - SystemConfig::getValue("sOLPURL"), - SystemConfig::getValue("sOLPUserName"), - SystemConfig::getValue("sOLPPassword") + SystemConfig::getValue('sOLPURL'), + SystemConfig::getValue('sOLPUserName'), + SystemConfig::getValue('sOLPPassword') ); $OLPAlert->setAlertText($this->projectorText); + return $OLPAlert->send(); } catch (\Exception $ex) { return false; @@ -89,23 +93,22 @@ private function sendProjector() public function send() { - $methods = []; if (SystemConfig::hasValidMailServerSettings()) { $send = $this->sendEmail(); - array_push($methods, "email: " . $send); + array_push($methods, 'email: '.$send); } if (SystemConfig::hasValidSMSServerSettings()) { - $send = (bool)$this->sendSMS(); - array_push($methods, "sms: " . $send); + $send = (bool) $this->sendSMS(); + array_push($methods, 'sms: '.$send); } if (SystemConfig::hasValidOpenLPSettings()) { - $send = (bool)($this->sendProjector()); - array_push($methods, "projector: " . $send); + $send = (bool) $this->sendProjector(); + array_push($methods, 'projector: '.$send); } $sendStatus = [ - "status" => "", - "methods" => $methods + 'status' => '', + 'methods' => $methods, ]; return json_encode($sendStatus, JSON_THROW_ON_ERROR); diff --git a/src/ChurchCRM/dto/Notification/UiNotification.php b/src/ChurchCRM/dto/Notification/UiNotification.php index 8e1e86ad05..d99e555ee8 100644 --- a/src/ChurchCRM/dto/Notification/UiNotification.php +++ b/src/ChurchCRM/dto/Notification/UiNotification.php @@ -17,6 +17,7 @@ class UiNotification implements JsonSerializable /** * UiNotification constructor. + * * @param $title * @param $message * @param $url @@ -26,7 +27,7 @@ class UiNotification implements JsonSerializable * @param $placement * @param $align */ - public function __construct($title, $icon, $url = "", $message = "", $type = "info", $delay = 4000, $placement = "top", $align = "right") + public function __construct($title, $icon, $url = '', $message = '', $type = 'info', $delay = 4000, $placement = 'top', $align = 'right') { $this->title = $title; $this->message = $message; @@ -102,7 +103,6 @@ public function getAlign() return $this->align; } - public function jsonSerialize(): array { return get_object_vars($this); diff --git a/src/ChurchCRM/dto/OpenLPNotification.php b/src/ChurchCRM/dto/OpenLPNotification.php index d8eb7cc26f..f41751133b 100644 --- a/src/ChurchCRM/dto/OpenLPNotification.php +++ b/src/ChurchCRM/dto/OpenLPNotification.php @@ -18,35 +18,36 @@ public function __construct($OLPAddress, $OLPUsername, $OLPPassword) public function setAlertText($text) { - $this->AlertText = (string)$text; + $this->AlertText = (string) $text; } private function getAuthorizationHeader() { - return base64_encode(SystemConfig::getValue("sOLPUserName") . ":" . SystemConfig::getValue("sOLPPassword")); + return base64_encode(SystemConfig::getValue('sOLPUserName').':'.SystemConfig::getValue('sOLPPassword')); } public function send() { $headers = [ - 'http' => [ - 'method' => "GET", - 'timeout' => 5 - ], - "ssl" => [ - "verify_peer" => false, - "verify_peer_name" => false, - "allow_self_signed" => true, - ] + '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"; + 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)); + //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; } } diff --git a/src/ChurchCRM/dto/PeopleCustomField.php b/src/ChurchCRM/dto/PeopleCustomField.php index 9031e6750e..5b0a45706c 100644 --- a/src/ChurchCRM/dto/PeopleCustomField.php +++ b/src/ChurchCRM/dto/PeopleCustomField.php @@ -2,8 +2,8 @@ namespace ChurchCRM\dto; -use ChurchCRM\PersonQuery; use ChurchCRM\ListOptionQuery; +use ChurchCRM\PersonQuery; class PeopleCustomField { @@ -11,11 +11,12 @@ class PeopleCustomField private string $value; private $formattedValue; private ?string $link = null; - private string $icon = "fa fa-tag"; + private string $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').' )'; } } } diff --git a/src/ChurchCRM/dto/Photo.php b/src/ChurchCRM/dto/Photo.php index e4e928bd21..f5a6831cba 100644 --- a/src/ChurchCRM/dto/Photo.php +++ b/src/ChurchCRM/dto/Photo.php @@ -17,7 +17,7 @@ class Photo private $thumbnailContentType; private bool $remotesEnabled; - public static $validExtensions = ["png", "jpeg", "jpg"]; + public static $validExtensions = ['png', 'jpeg', 'jpg']; public function __construct($photoType, $id) { @@ -35,19 +35,19 @@ public static function getValidExtensions() private function setURIs($photoPath) { $this->photoURI = $photoPath; - $this->thubmnailPath = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/thumbnails/"; - $this->photoThumbURI = $this->thubmnailPath . $this->id . ".jpg"; + $this->thubmnailPath = SystemURLs::getImagesRoot().'/'.$this->photoType.'/thumbnails/'; + $this->photoThumbURI = $this->thubmnailPath.$this->id.'.jpg'; } private function shouldRefreshPhotoFile($photoFile): bool { if (!$this->remotesEnabled) { // if remotes are disabled, and the image contains remote, then we should re-gen - return strpos($photoFile, "remote") !== false; + return strpos($photoFile, 'remote') !== false; } - + // if the system has remotes enabled, calculate the cutoff timestamp for refreshing remote photos. - $remotePhotoCacheDuration = SystemConfig::getValue("iRemotePhotoCacheDuration"); + $remotePhotoCacheDuration = SystemConfig::getValue('iRemotePhotoCacheDuration'); if (!$remotePhotoCacheDuration) { LoggerUtils::getAppLogger()->error( 'config iRemotePhotoCacheDuration somehow not set, please investigate', @@ -57,12 +57,12 @@ private function shouldRefreshPhotoFile($photoFile): bool // default defined in SystemConfig.php $interval = \DateInterval::createFromDateString('72 hours'); } else { - $interval = \DateInterval::createFromDateString($remotePhotoCacheDuration); + $interval = \DateInterval::createFromDateString($remotePhotoCacheDuration); } $remoteCacheThreshold = new \DateTimeImmutable(); $remoteCacheThreshold = $remoteCacheThreshold->sub($interval); - if (strpos($photoFile, "remote") !== false || strpos($photoFile, "initials") !== false) { + if (strpos($photoFile, 'remote') !== false || strpos($photoFile, 'initials') !== false) { return filemtime($photoFile) < $remoteCacheThreshold->getTimestamp(); } @@ -71,15 +71,15 @@ private function shouldRefreshPhotoFile($photoFile): bool private function photoHunt() { - $baseName = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/" . $this->id; + $baseName = SystemURLs::getImagesRoot().'/'.$this->photoType.'/'.$this->id; $extensions = Photo::$validExtensions; foreach ($extensions as $ext) { - $photoFiles = [$baseName . "." . $ext, $baseName . "-remote." . $ext, $baseName . "-initials." . $ext]; + $photoFiles = [$baseName.'.'.$ext, $baseName.'-remote.'.$ext, $baseName.'-initials.'.$ext]; foreach ($photoFiles as $photoFile) { if (is_file($photoFile)) { $this->setURIs($photoFile); - if ($ext !== "png") { + if ($ext !== 'png') { $this->convertToPNG(); } if ($this->shouldRefreshPhotoFile($photoFile)) { @@ -87,20 +87,22 @@ private function photoHunt() $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) { + // 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); + $photoPath = $this->loadFromGoogle($personEmail, $baseName); if ($photoPath) { $this->setURIs($photoPath); + return; } } @@ -109,13 +111,14 @@ private function photoHunt() $photoPath = $this->loadFromGravatar($personEmail, $baseName); if ($photoPath) { $this->setURIs($photoPath); + return; } } } } - # still no image - generate it from initials + // still no image - generate it from initials $this->renderInitials(); } @@ -123,7 +126,7 @@ private function convertToPNG() { $image = $this->getGDImage($this->getPhotoURI()); $this->delete(); - $targetPath = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/" . $this->id . ".png"; + $targetPath = SystemURLs::getImagesRoot().'/'.$this->photoType.'/'.$this->id.'.png'; imagepng($image, $targetPath); $this->setURIs($targetPath); } @@ -142,6 +145,7 @@ private function getGDImage($sourceImagePath) $sourceGDImage = imagecreatefrompng($sourceImagePath); break; } + return $sourceGDImage; } @@ -155,12 +159,12 @@ private function ensureThumbnailsPath() 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. + $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 )); + $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); @@ -171,6 +175,7 @@ public function getThumbnailBytes() if (!file_exists($this->photoThumbURI)) { $this->createThumbnail(); } + return file_get_contents($this->photoThumbURI); } @@ -183,6 +188,7 @@ public function getPhotoContentType() { $finfo = new \finfo(FILEINFO_MIME); $this->photoContentType = $finfo->file($this->photoURI); + return $this->photoContentType; } @@ -190,6 +196,7 @@ public function getThumbnailContentType() { $finfo = new \finfo(FILEINFO_MIME); $this->thumbnailContentType = $finfo->file($this->photoThumbURI); + return $this->thumbnailContentType; } @@ -198,6 +205,7 @@ public function getThumbnailURI() if (!is_file($this->photoThumbURI)) { $this->createThumbnail(); } + return $this->photoThumbURI; } @@ -219,10 +227,12 @@ private function loadFromGravatar($email, $baseName) $photo = imagecreatefromstring(file_get_contents($url)); if ($photo) { - $photoPath = $baseName . "-remote.png"; + $photoPath = $baseName.'-remote.png'; imagepng($photo, $photoPath); + return $photoPath; } + return false; } @@ -230,7 +240,7 @@ private function loadFromGoogle($email, $baseName) { $url = 'http://picasaweb.google.com/data/entry/api/user/'; $url .= strtolower(trim($email)); - $url .= "?alt=json"; + $url .= '?alt=json'; $headers = @get_headers($url); if (strpos($headers[0], '404') === false) { $json = file_get_contents($url); @@ -240,12 +250,14 @@ private function loadFromGoogle($email, $baseName) $photoURL = $photoEntry->{'gphoto$thumbnail'}->{'$t'}; $photo = imagecreatefromstring(file_get_contents($photoURL)); if ($photo) { - $photoPath = $baseName . "-remote.png"; + $photoPath = $baseName.'-remote.png'; imagepng($photo, $photoPath); + return $photoPath; } } } + return false; } @@ -254,32 +266,34 @@ private function getRandomColor($image) $red = random_int(0, 150); $green = random_int(0, 150); $blue = random_int(0, 150); + return imagecolorallocate($image, $red, $green, $blue); } private function getInitialsString() { - $retstr = ""; - if ($this->photoType == "Person") { + $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") { + } elseif ($this->photoType == 'Family') { $fullNameArr = FamilyQuery::create()->findOneById($this->id)->getName(); $retstr .= mb_strtoupper(mb_substr($fullNameArr, 0, 1)); } + 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"; + $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); @@ -295,12 +309,12 @@ private function renderInitials() public function setImageFromBase64($base64) { $this->delete(); - $fileName = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/" . $this->id . ".png"; + $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") { + if ($finfo->buffer($fileData) == 'image/png; charset=binary') { file_put_contents($fileName, $fileData); } } @@ -314,30 +328,32 @@ public function delete(): bool if ($this->photoThumbURI && is_file($this->photoThumbURI)) { $deleted[$this->photoThumbURI] = unlink($this->photoThumbURI); } + return !in_array(false, $deleted); } public function refresh() { - if (strpos($this->photoURI, "initials") || strpos($this->photoURI, "remote")) { + if (strpos($this->photoURI, 'initials') || strpos($this->photoURI, 'remote')) { $this->delete(); } $this->photoURI = $this->photoHunt(); - $this->photoThumbURI = SystemURLs::getImagesRoot() . "/" . $this->photoType . "/thumbnails/" . $this->id . ".jpg"; + $this->photoThumbURI = SystemURLs::getImagesRoot().'/'.$this->photoType.'/thumbnails/'.$this->id.'.jpg'; } public function isInitials(): bool { - if ($this->photoType == "Person" && $this->id == 2) { + if ($this->photoType == 'Person' && $this->id == 2) { echo $this->photoURI; - echo strpos($this->photoURI, "initials") !== false; - die(); + echo strpos($this->photoURI, 'initials') !== false; + exit; } - return strpos($this->photoURI, "initials") !== false; + + return strpos($this->photoURI, 'initials') !== false; } public function isRemote(): bool { - return strpos($this->photoURI, "remote") !== false; + return strpos($this->photoURI, 'remote') !== false; } } diff --git a/src/ChurchCRM/dto/Prerequisite.php b/src/ChurchCRM/dto/Prerequisite.php index 97e7750618..0da08264fc 100644 --- a/src/ChurchCRM/dto/Prerequisite.php +++ b/src/ChurchCRM/dto/Prerequisite.php @@ -20,8 +20,9 @@ public function isPrerequisiteMet() { $callable = $this->testFunction; if ($this->savedTestResult === null) { - $this->savedTestResult = (bool)$callable(); + $this->savedTestResult = (bool) $callable(); } + return $this->savedTestResult; } @@ -32,22 +33,24 @@ public function getName() public function getWikiLink() { - return 'https://github.com/ChurchCRM/CRM/wiki/ChurchCRM-Application-Platform-Prerequisites#' . MiscUtils::getGitHubWikiAnchorLink($this->name); + 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('Passed'); } - return gettext("Failed"); + + return gettext('Failed'); } public function jsonSerialize(): array { - return [ - 'Name' => $this->getName(), - 'WikiLink' => $this->getWikiLink(), - 'Satisfied' => $this->isPrerequisiteMet() - ]; + 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 23ecd1351b..8fbb94b103 100644 --- a/src/ChurchCRM/dto/SystemCalendars.php +++ b/src/ChurchCRM/dto/SystemCalendars.php @@ -11,14 +11,15 @@ class SystemCalendars private static function getCalendars() { $systemCalendarNamespace = "ChurchCRM\SystemCalendars\\"; - $systemCalendarNames = ["BirthdaysCalendar", "AnniversariesCalendar", "HolidayCalendar","UnpinnedEvents"]; + $systemCalendarNames = ['BirthdaysCalendar', 'AnniversariesCalendar', 'HolidayCalendar', 'UnpinnedEvents']; $calendars = []; foreach ($systemCalendarNames as $systemCalendarName) { - $className = $systemCalendarNamespace . $systemCalendarName; + $className = $systemCalendarNamespace.$systemCalendarName; if ($className::isAvailable()) { array_push($calendars, new $className()); } } + return $calendars; } @@ -29,6 +30,7 @@ public static function getCalendarList() foreach (self::getCalendars() as $calendar) { $calendars->push(self::toPropelCalendar($calendar)); } + return $calendars; } @@ -41,17 +43,19 @@ public static function getCalendarById($id) break; } } + return $requestedCalendar; } public static function toPropelCalendar(SystemCalendar $calendar) { - $procalendar = new 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 fbc0da52a6..7de98196ca 100644 --- a/src/ChurchCRM/dto/SystemConfig.php +++ b/src/ChurchCRM/dto/SystemConfig.php @@ -22,269 +22,270 @@ class SystemConfig private static function getSupportedLocales() { - $localesFile = file_get_contents(SystemURLs::getDocumentRoot() . "/locale/locales.json"); + $localesFile = file_get_contents(SystemURLs::getDocumentRoot().'/locale/locales.json'); $locales = json_decode($localesFile, true, 512, JSON_THROW_ON_ERROR); $languagesChoices = []; foreach ($locales as $key => $value) { - array_push($languagesChoices, gettext($key) . ":" . $value["locale"]); + 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(); foreach ($familyRoles as $familyRole) { - array_push($roles, $familyRole->getOptionName() . ":" . $familyRole->getOptionId()); + array_push($roles, $familyRole->getOptionName().':'.$familyRole->getOptionId()); } } catch (Exception $e) { } - return ["Choices" => $roles]; - } + return ['Choices' => $roles]; + } private static function buildConfigs() { return [ - "sLogLevel" => new ConfigItem(4, "sLogLevel", "choice", "200", gettext("Event Log severity to write, used by ORM and App Logs"), "", json_encode(SystemConfig::getMonoLogLevels(), JSON_THROW_ON_ERROR)), - "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(), JSON_THROW_ON_ERROR)), - "sDirRoleSpouse" => new ConfigItem(7, "sDirRoleSpouse", "choice", "2", gettext("These are the family role numbers designated as spouse"), "", json_encode(SystemConfig::getFamilyRoleChoices(), JSON_THROW_ON_ERROR)), - "sDirRoleChild" => new ConfigItem(8, "sDirRoleChild", "choice", "3", gettext("These are the family role numbers designated as child"), "", json_encode(SystemConfig::getFamilyRoleChoices(), JSON_THROW_ON_ERROR)), - "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()], JSON_THROW_ON_ERROR)), - "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(), JSON_THROW_ON_ERROR)), - "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.")), - "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()], JSON_THROW_ON_ERROR)), - "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()], JSON_THROW_ON_ERROR)), - "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(), JSON_THROW_ON_ERROR)), - "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", "text", "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") + 'sLogLevel' => new ConfigItem(4, 'sLogLevel', 'choice', '200', gettext('Event Log severity to write, used by ORM and App Logs'), '', json_encode(SystemConfig::getMonoLogLevels(), JSON_THROW_ON_ERROR)), + '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(), JSON_THROW_ON_ERROR)), + 'sDirRoleSpouse' => new ConfigItem(7, 'sDirRoleSpouse', 'choice', '2', gettext('These are the family role numbers designated as spouse'), '', json_encode(SystemConfig::getFamilyRoleChoices(), JSON_THROW_ON_ERROR)), + 'sDirRoleChild' => new ConfigItem(8, 'sDirRoleChild', 'choice', '3', gettext('These are the family role numbers designated as child'), '', json_encode(SystemConfig::getFamilyRoleChoices(), JSON_THROW_ON_ERROR)), + '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()], JSON_THROW_ON_ERROR)), + '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(), JSON_THROW_ON_ERROR)), + '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.')), + '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()], JSON_THROW_ON_ERROR)), + '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()], JSON_THROW_ON_ERROR)), + '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(), JSON_THROW_ON_ERROR)), + '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', 'text', '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 [ - 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"], - 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"] + 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'], + 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'], ]; } @@ -308,7 +309,7 @@ public static function isInitialized(): bool /** * @return array */ - public static function getCategories(): array + public static function getCategories(): array { return self::$categories; } @@ -338,7 +339,7 @@ public static function getConfigItem(string $name) public static function getValue(string $name) { if (!isset(self::$configs[$name])) { - throw new \Exception(gettext("An invalid configuration name has been requested") . ": " . $name); + throw new \Exception(gettext('An invalid configuration name has been requested').': '.$name); } return self::$configs[$name]->getValue(); @@ -347,7 +348,7 @@ public static function getValue(string $name) public static function getBooleanValue(string $name): bool { if (!isset(self::$configs[$name])) { - throw new \Exception(gettext("An invalid configuration name has been requested") . ": " . $name); + throw new \Exception(gettext('An invalid configuration name has been requested').': '.$name); } return self::$configs[$name]->getBooleanValue(); @@ -356,7 +357,7 @@ public static function getBooleanValue(string $name): bool public static function setValue(string $name, $value) { if (!isset(self::$configs[$name])) { - throw new \Exception(gettext("An invalid configuration name has been requested") . ": " . $name); + throw new \Exception(gettext('An invalid configuration name has been requested').': '.$name); } self::$configs[$name]->setValue($value); @@ -372,18 +373,18 @@ public static function setValueById($Id, $value) } } if (!$success) { - throw new \Exception(gettext("An invalid configuration id has been requested") . ": " . $Id); + throw new \Exception(gettext('An invalid configuration id has been requested').': '.$Id); } } public static function hasValidMailServerSettings(): bool { $hasValidSettings = true; - if (empty(self::getValue("sSMTPHost"))) { + if (empty(self::getValue('sSMTPHost'))) { $hasValidSettings = false; } - if (SystemConfig::getBooleanValue("bSMTPAuth") && (empty(self::getValue("sSMTPUser")) || empty(self::getValue("sSMTPPass")))) { + if (SystemConfig::getBooleanValue('bSMTPAuth') && (empty(self::getValue('sSMTPUser')) || empty(self::getValue('sSMTPPass')))) { $hasValidSettings = false; } @@ -392,20 +393,20 @@ public static function hasValidMailServerSettings(): bool public static function hasValidSMSServerSettings(): bool { - return (!empty(self::getValue("sNexmoAPIKey"))) && (!empty(self::getValue("sNexmoAPISecret"))) && (!empty(self::getValue("sNexmoFromNumber"))); + return (!empty(self::getValue('sNexmoAPIKey'))) && (!empty(self::getValue('sNexmoAPISecret'))) && (!empty(self::getValue('sNexmoFromNumber'))); } public static function hasValidOpenLPSettings(): bool { - return !empty(self::getValue("sOLPURL")); + return !empty(self::getValue('sOLPURL')); } - public static function debugEnabled(): bool { - if (self::getValue("sLogLevel") == Logger::DEBUG) { + 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 bcda5174ee..c0d7162e3b 100644 --- a/src/ChurchCRM/dto/SystemURLs.php +++ b/src/ChurchCRM/dto/SystemURLs.php @@ -33,7 +33,8 @@ 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 . ']'); + + throw new \Exception("Please check the value for '\$sRootPath' in `Include\\Config.php`, the following is not valid [".self::$rootPath.']'); } public static function getDocumentRoot() @@ -43,7 +44,7 @@ public static function getDocumentRoot() public static function getImagesRoot() { - return self::$documentRoot . "/Images"; + return self::$documentRoot.'/Images'; } public static function getURLs() @@ -51,15 +52,15 @@ public static function getURLs() return self::$urls; } - public static function getSupportURL($topic = "") + public static function getSupportURL($topic = '') { $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" + '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)) { @@ -74,9 +75,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) == "/") { + if (substr($URL, -1, 1) == '/') { return substr($URL, 0, -1); } + return $URL; } @@ -95,7 +97,7 @@ public static function checkAllowedURL($bLockURL, $URL) { if (isset($bLockURL) && ($bLockURL === true)) { // get the URL of this page - $currentURL = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; + $currentURL = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // chop off the query string $currentURL = explode('?', $currentURL)[0]; @@ -112,7 +114,7 @@ public static function checkAllowedURL($bLockURL, $URL) // jump to the first whitelisted url (TODO: maybe pick a ranodm URL?) if (!$validURL) { - header('Location: ' . $URL[0]); + header('Location: '.$URL[0]); exit; } } diff --git a/src/ChurchCRM/dto/iCal.php b/src/ChurchCRM/dto/iCal.php index 6d97aafdf0..36b9fbcc50 100644 --- a/src/ChurchCRM/dto/iCal.php +++ b/src/ChurchCRM/dto/iCal.php @@ -6,7 +6,7 @@ * and open the template in the editor. */ - namespace ChurchCRM\dto; +namespace ChurchCRM\dto; use ChurchCRM\Event; use ChurchCRM\Service\SystemService; @@ -21,26 +21,26 @@ class iCal 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" . + $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" . + $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"; } @@ -50,7 +50,8 @@ public function toString() foreach ($this->eventsArray as $event) { $iCal .= $this->eventToVEVENT($event); } - $iCal .= "END:VCALENDAR"; + $iCal .= 'END:VCALENDAR'; + return $iCal; } } diff --git a/src/ChurchCRM/model/ChurchCRM/Calendar.php b/src/ChurchCRM/model/ChurchCRM/Calendar.php index f923bf57f1..03e5ace4ab 100644 --- a/src/ChurchCRM/model/ChurchCRM/Calendar.php +++ b/src/ChurchCRM/model/ChurchCRM/Calendar.php @@ -12,7 +12,6 @@ * 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 Calendar extends BaseCalendar { diff --git a/src/ChurchCRM/model/ChurchCRM/CalendarEvent.php b/src/ChurchCRM/model/ChurchCRM/CalendarEvent.php index f1f4697d08..7c33dc07ec 100644 --- a/src/ChurchCRM/model/ChurchCRM/CalendarEvent.php +++ b/src/ChurchCRM/model/ChurchCRM/CalendarEvent.php @@ -12,7 +12,6 @@ * 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 CalendarEvent extends BaseCalendarEvent { diff --git a/src/ChurchCRM/model/ChurchCRM/CalendarEventQuery.php b/src/ChurchCRM/model/ChurchCRM/CalendarEventQuery.php index 10d4c76c7b..0306ae559e 100644 --- a/src/ChurchCRM/model/ChurchCRM/CalendarEventQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/CalendarEventQuery.php @@ -12,7 +12,6 @@ * 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 CalendarEventQuery extends BaseCalendarEventQuery { diff --git a/src/ChurchCRM/model/ChurchCRM/CalendarQuery.php b/src/ChurchCRM/model/ChurchCRM/CalendarQuery.php index 638099b1ce..acef3afeca 100644 --- a/src/ChurchCRM/model/ChurchCRM/CalendarQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/CalendarQuery.php @@ -12,7 +12,6 @@ * 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 CalendarQuery extends BaseCalendarQuery { diff --git a/src/ChurchCRM/model/ChurchCRM/Config.php b/src/ChurchCRM/model/ChurchCRM/Config.php index ef510f0d5b..754fdc3b3d 100644 --- a/src/ChurchCRM/model/ChurchCRM/Config.php +++ b/src/ChurchCRM/model/ChurchCRM/Config.php @@ -12,7 +12,6 @@ * 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 Config extends BaseConfig { diff --git a/src/ChurchCRM/model/ChurchCRM/Deposit.php b/src/ChurchCRM/model/ChurchCRM/Deposit.php index 7bd14fa3b8..45d178e183 100644 --- a/src/ChurchCRM/model/ChurchCRM/Deposit.php +++ b/src/ChurchCRM/model/ChurchCRM/Deposit.php @@ -36,47 +36,47 @@ public function getOFX() } $orgName = 'ChurchCRM Deposit Data'; - $OFXReturn->content = 'OFXHEADER:100' . PHP_EOL . - 'DATA:OFXSGML' . PHP_EOL . - 'VERSION:102' . PHP_EOL . - 'SECURITY:NONE' . PHP_EOL . - 'ENCODING:USASCII' . PHP_EOL . - 'CHARSET:1252' . PHP_EOL . - 'COMPRESSION:NONE' . PHP_EOL . - 'OLDFILEUID:NONE' . PHP_EOL . - 'NEWFILEUID:NONE' . PHP_EOL . PHP_EOL; + $OFXReturn->content = 'OFXHEADER:100'.PHP_EOL. + 'DATA:OFXSGML'.PHP_EOL. + 'VERSION:102'.PHP_EOL. + 'SECURITY:NONE'.PHP_EOL. + 'ENCODING:USASCII'.PHP_EOL. + 'CHARSET:1252'.PHP_EOL. + 'COMPRESSION:NONE'.PHP_EOL. + 'OLDFILEUID:NONE'.PHP_EOL. + 'NEWFILEUID:NONE'.PHP_EOL.PHP_EOL; $OFXReturn->content .= ''; - $OFXReturn->content .= '0INFO' . date('YmdHis.u[O:T]') . 'ENG' . $orgName . '12345'; - $OFXReturn->content .= '' . - '' . - '' . - '' . - '0' . - 'INFO' . + $OFXReturn->content .= '0INFO'.date('YmdHis.u[O:T]').'ENG'.$orgName.'12345'; + $OFXReturn->content .= ''. + ''. + ''. + ''. + '0'. + 'INFO'. ''; foreach ($this->getFundTotals() as $fund) { - $OFXReturn->content .= '' . - 'USD' . - '' . - '' . $orgName . - '' . $fund['Name'] . - 'SAVINGS' . + $OFXReturn->content .= ''. + 'USD'. + ''. + ''.$orgName. + ''.$fund['Name']. + 'SAVINGS'. ''; $OFXReturn->content .= - '' . - 'CREDIT' . - '' . $this->getDate('Ymd') . - '' . $fund['Total'] . - '' . - '' . $this->getComment() . - '' . $fund['Name'] . + ''. + 'CREDIT'. + ''.$this->getDate('Ymd'). + ''.$fund['Total']. + ''. + ''.$this->getComment(). + ''.$fund['Name']. ''; } $OFXReturn->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; } @@ -123,7 +123,7 @@ private function generateTotalsByCurrencyType($thisReport) $thisReport->curY += 4; $thisReport->pdf->SetXY($thisReport->curX, $thisReport->curY); $thisReport->pdf->Write(8, 'Checks: '); - $thisReport->pdf->write(8, '(' . $this->getCountChecks() . ')'); + $thisReport->pdf->write(8, '('.$this->getCountChecks().')'); $thisReport->pdf->printRightJustified($thisReport->curX + 55, $thisReport->curY, sprintf('%.2f', $this->getTotalChecks())); $thisReport->curY += 4; $thisReport->pdf->SetXY($thisReport->curX, $thisReport->curY); @@ -196,7 +196,7 @@ private function generateQBDepositSlip($thisReport) $thisReport->curY = $thisReport->QBDepositTicketParameters->perforationY; $thisReport->pdf->SetXY($thisReport->QBDepositTicketParameters->titleX, $thisReport->curY); $thisReport->pdf->SetFont('Courier', 'B', 20); - $thisReport->pdf->Write(8, 'Deposit Summary ' . $this->getId()); + $thisReport->pdf->Write(8, 'Deposit Summary '.$this->getId()); $thisReport->pdf->SetFont('Times', '', 10); $thisReport->pdf->SetXY($thisReport->QBDepositTicketParameters->date2X, $thisReport->curY); $thisReport->pdf->Write(8, $this->getDate()->format('Y-m-d')); @@ -246,7 +246,7 @@ private function generateDepositSummary($thisReport) $thisReport->pdf->SetXY($thisReport->depositSummaryParameters->title->x, $thisReport->depositSummaryParameters->title->y); $thisReport->pdf->SetFont('Courier', 'B', 20); - $thisReport->pdf->Write(8, 'Deposit Summary ' . $this->getId()); + $thisReport->pdf->Write(8, 'Deposit Summary '.$this->getId()); $thisReport->pdf->SetFont('Times', 'B', 10); $thisReport->curX = $thisReport->depositSummaryParameters->summary->x; @@ -291,16 +291,16 @@ private function generateDepositSummary($thisReport) } if (strlen($checkNo) > 8) { - $checkNo = '...' . mb_substr($checkNo, -8, 8); + $checkNo = '...'.mb_substr($checkNo, -8, 8); } if (strlen($fundName) > 20) { - $fundName = mb_substr($fundName, 0, 20) . '...'; + $fundName = mb_substr($fundName, 0, 20).'...'; } if (strlen($comment) > 40) { - $comment = mb_substr($comment, 0, 38) . '...'; + $comment = mb_substr($comment, 0, 38).'...'; } if (strlen($familyName) > 25) { - $familyName = mb_substr($familyName, 0, 24) . '...'; + $familyName = mb_substr($familyName, 0, 24).'...'; } $thisReport->pdf->printRightJustified($thisReport->curX + 2, $thisReport->curY, $checkNo); @@ -354,7 +354,7 @@ private function generateDepositSummary($thisReport) 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->pdf->MultiCell(0, $thisReport->depositSummaryParameters->summary->intervalY, gettext('Deposit Comment').': '.$this->getComment(), 0, 'L'); } $thisReport->curY += 130; $thisReport->curX = $thisReport->depositSummaryParameters->summary->x; @@ -365,7 +365,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); @@ -408,7 +408,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() @@ -469,7 +469,7 @@ public function getFundTotals() $funds = PledgeQuery::create() ->filterByDepId($this->getId()) ->groupByFundId() - ->withColumn('SUM(' . PledgeTableMap::COL_PLG_AMOUNT . ')', 'Total') + ->withColumn('SUM('.PledgeTableMap::COL_PLG_AMOUNT.')', 'Total') ->joinDonationFund() ->withColumn(DonationFundTableMap::COL_FUN_NAME, 'Name') ->orderBy(DonationFundTableMap::COL_FUN_NAME) diff --git a/src/ChurchCRM/model/ChurchCRM/Event.php b/src/ChurchCRM/model/ChurchCRM/Event.php index b748cfe441..b7935a5937 100644 --- a/src/ChurchCRM/model/ChurchCRM/Event.php +++ b/src/ChurchCRM/model/ChurchCRM/Event.php @@ -27,12 +27,12 @@ public function __construct() 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; } @@ -59,7 +59,7 @@ public function checkInPerson($PersonId) ->setCheckoutDate(null) ->save(); - return ["status" => "success"]; + return ['status' => 'success']; } public function checkOutPerson($PersonId) @@ -75,11 +75,11 @@ public function checkOutPerson($PersonId) ->setCheckoutDate(date('Y-m-d H:i:s')) ->save(); - return ["status" => "success"]; + return ['status' => 'success']; } public function getViewURI() { - return SystemURLs::getRootPath() . "/EventEditor.php?calendarAction=" . $this->getID(); + 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 69de5f0a42..35b375024c 100644 --- a/src/ChurchCRM/model/ChurchCRM/EventAudience.php +++ b/src/ChurchCRM/model/ChurchCRM/EventAudience.php @@ -12,7 +12,6 @@ * 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 e8653c2e00..064766f09f 100644 --- a/src/ChurchCRM/model/ChurchCRM/EventAudienceQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/EventAudienceQuery.php @@ -12,7 +12,6 @@ * 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 92b2ad6b1a..a0142b04e0 100644 --- a/src/ChurchCRM/model/ChurchCRM/EventType.php +++ b/src/ChurchCRM/model/ChurchCRM/EventType.php @@ -12,7 +12,6 @@ * 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 32168bcc1a..31853aa918 100644 --- a/src/ChurchCRM/model/ChurchCRM/EventTypeQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/EventTypeQuery.php @@ -12,7 +12,6 @@ * 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 a14b851fcf..9594c2c104 100644 --- a/src/ChurchCRM/model/ChurchCRM/Family.php +++ b/src/ChurchCRM/model/ChurchCRM/Family.php @@ -34,13 +34,13 @@ public function getAddress() if (!empty($this->getAddress1())) { $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())) { @@ -59,7 +59,7 @@ public function getAddress() public function getViewURI() { - return SystemURLs::getRootPath() . '/v2/family/' . $this->getId(); + return SystemURLs::getRootPath().'/v2/family/'.$this->getId(); } public function getWeddingDay() @@ -87,10 +87,10 @@ public function getWeddingMonth() public function postInsert(ConnectionInterface $con = null) { $this->createTimeLineNote('create'); - if (!empty(SystemConfig::getValue("sNewPersonNotificationRecipientIDs"))) { + if (!empty(SystemConfig::getValue('sNewPersonNotificationRecipientIDs'))) { $NotificationEmail = new NewPersonOrFamilyEmail($this); if (!$NotificationEmail->send()) { - LoggerUtils::getAppLogger()->warning(gettext("New Family Notification Email Error") . " :" . $NotificationEmail->getError()); + LoggerUtils::getAppLogger()->warning(gettext('New Family Notification Email Error').' :'.$NotificationEmail->getError()); } } } @@ -102,23 +102,23 @@ 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"); + return $this->getPeopleByRole('sDirRoleHead'); } public function getSpousePeople() { - return $this->getPeopleByRole("sDirRoleSpouse"); + return $this->getPeopleByRole('sDirRoleSpouse'); } public function getAdults() @@ -128,18 +128,18 @@ public function getAdults() public function getChildPeople() { - return $this->getPeopleByRole("sDirRoleChild"); + return $this->getPeopleByRole('sDirRoleChild'); } public function getOtherPeople() { $roleIds = array_merge( - explode(",", SystemConfig::getValue("sDirRoleHead")), + explode(',', SystemConfig::getValue('sDirRoleHead')), explode( - ",", - SystemConfig::getValue("sDirRoleSpouse") + ',', + SystemConfig::getValue('sDirRoleSpouse') ), - explode(",", SystemConfig::getValue("sDirRoleChild")) + explode(',', SystemConfig::getValue('sDirRoleChild')) ); $foundPeople = []; foreach ($this->getPeople() as $person) { @@ -147,24 +147,27 @@ public function getOtherPeople() array_push($foundPeople, $person); } } + return $foundPeople; } private function getPeopleByRole($roleConfigName) { - $roleIds = explode(",", SystemConfig::getValue($roleConfigName)); + $roleIds = explode(',', SystemConfig::getValue($roleConfigName)); $foundPeople = []; foreach ($this->getPeople() as $person) { if (in_array($person->getFmrId(), $roleIds)) { array_push($foundPeople, $person); } } + return $foundPeople; } /** - * @return array * @throws \Propel\Runtime\Exception\PropelException + * + * @return array */ public function getEmails() { @@ -182,6 +185,7 @@ public function getEmails() array_push($emails, $email); } } + return $emails; } @@ -193,25 +197,25 @@ public function createTimeLineNote($type) $note->setDateEntered(new DateTime()); switch ($type) { - case "create": + case 'create': $note->setText(gettext('Created')); $note->setEnteredBy($this->getEnteredBy()); $note->setDateEntered($this->getDateEntered()); break; - case "edit": + 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": + case 'verify-link': $note->setText(gettext('Verification email sent')); $note->setEnteredBy(AuthenticationManager::getCurrentUser()->getId()); break; - case "verify-URL": + case 'verify-URL': $note->setText(gettext('Verification URL created')); $note->setEnteredBy(AuthenticationManager::getCurrentUser()->getId()); break; @@ -226,8 +230,9 @@ public function createTimeLineNote($type) public function getPhoto() { if (!$this->photo) { - $this->photo = new Photo("Family", $this->getId()); + $this->photo = new Photo('Family', $this->getId()); } + return $this->photo; } @@ -236,28 +241,33 @@ 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 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->setFamId($this->getId()); $note->save(); + return true; } + return false; } @@ -273,16 +283,16 @@ public function getFamilyString($booleanIncludeHOH = true) $HoH = $this->getHeadPeople(); } if (count($HoH) == 1) { - return $this->getName() . ": " . $HoH[0]->getFirstName() . " - " . $this->getAddress(); + 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(); + return $this->getName().': '.join(',', $HoHs).' - '.$this->getAddress(); } else { - return $this->getName() . " " . $this->getAddress(); + return $this->getName().' '.$this->getAddress(); } } @@ -293,6 +303,7 @@ public function hasLatitudeAndLongitude() /** * 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() @@ -312,16 +323,18 @@ public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColum $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() + 'Id' => $this->getId(), + 'displayName' => $this->getFamilyString(SystemConfig::getBooleanValue('bSearchIncludeFamilyHOH')), + 'uri' => SystemURLs::getRootPath().'/v2/family/'.$this->getId(), ]; + return $searchArray; } @@ -333,7 +346,7 @@ public function isActive() public function getProperties() { return PropertyQuery::create() - ->filterByProClass("f") + ->filterByProClass('f') ->useRecordPropertyQuery() ->filterByRecordId($this->getId()) ->find(); @@ -344,22 +357,24 @@ 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; } @@ -379,12 +394,12 @@ public function getSalutation() $firstLastName = $adults[0]->getLastName(); $secondLastName = $adults[1]->getLastName(); if ($firstLastName == $secondLastName) { - return $adults[0]->getFirstName() . ' & ' . $adults[1]->getFirstName() . ' ' . $firstLastName; + return $adults[0]->getFirstName().' & '.$adults[1]->getFirstName().' '.$firstLastName; } else { - return $adults[0]->getFullName() . ' & ' . $adults[1]->getFullName(); + return $adults[0]->getFullName().' & '.$adults[1]->getFullName(); } } else { - return $this->getName() . ' Family'; + return $this->getName().' Family'; } } @@ -394,6 +409,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 163229481f..13177a32e1 100644 --- a/src/ChurchCRM/model/ChurchCRM/Group.php +++ b/src/ChurchCRM/model/ChurchCRM/Group.php @@ -95,7 +95,7 @@ public function checkAgainstCart() $groupMemberships = $this->getPerson2group2roleP2g2rsJoinPerson(); $bNoneInCart = true; $bAllInCart = true; - //Loop through the recordset + //Loop through the recordset foreach ($groupMemberships as $groupMembership) { if (!isset($_SESSION['aPeopleCart'])) { $bAllInCart = 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 5f502df21e..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 b228bacfc1..88474f3a31 100644 --- a/src/ChurchCRM/model/ChurchCRM/KioskAssignment.php +++ b/src/ChurchCRM/model/ChurchCRM/KioskAssignment.php @@ -16,7 +16,6 @@ * 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 { @@ -28,9 +27,10 @@ private function getActiveEvent() ->filterByEnd('now', Criteria::GREATER_EQUAL) ->filterById($this->getEventId()) ->findOne(); + return $Event; } else { - throw new \Exception("This kiosk does not support group attendance"); + throw new \Exception('This kiosk does not support group attendance'); } } @@ -38,8 +38,8 @@ public function getActiveGroupMembers() { 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->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() @@ -48,15 +48,16 @@ public function getActiveGroupMembers() ->filterByGroupId($this->getEvent()->getGroupId()) ->joinGroup() ->addJoinObject($groupTypeJoin) - ->withColumn(ListOptionTableMap::COL_LST_OPTIONNAME, "RoleName") + ->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"]) + ->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"); + 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 d3de314c61..9e9570aceb 100644 --- a/src/ChurchCRM/model/ChurchCRM/KioskAssignmentQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/KioskAssignmentQuery.php @@ -12,7 +12,6 @@ * 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 b597c75756..ac5ec671ac 100644 --- a/src/ChurchCRM/model/ChurchCRM/KioskDevice.php +++ b/src/ChurchCRM/model/ChurchCRM/KioskDevice.php @@ -3,7 +3,6 @@ namespace ChurchCRM; use ChurchCRM\Base\KioskDevice as BaseKioskDevice; -use ChurchCRM\Map\ListOptionTableMap; class KioskDevice extends BaseKioskDevice { @@ -37,12 +36,11 @@ public function heartbeat() $assignmentJSON = $assignment->toJSON(); } - return [ - "Accepted" => $this->getAccepted(), - "Name" => $this->getName(), - "Assignment" => $assignmentJSON, - "Commands" => $this->getPendingCommands() + 'Accepted' => $this->getAccepted(), + 'Name' => $this->getName(), + 'Assignment' => $assignmentJSON, + 'Commands' => $this->getPendingCommands(), ]; } @@ -51,20 +49,23 @@ public function getPendingCommands() $commands = parent::getPendingCommands(); $this->setPendingCommands(null); $this->save(); + return $commands; } public function reloadKiosk() { - $this->setPendingCommands("Reload"); + $this->setPendingCommands('Reload'); $this->save(); + return true; } public function identifyKiosk() { - $this->setPendingCommands("Identify"); + $this->setPendingCommands('Identify'); $this->save(); + return true; } @@ -73,6 +74,7 @@ public function preInsert(\Propel\Runtime\Connection\ConnectionInterface $con = if (!isset($this->Name)) { $this->setName(Utils\MiscUtils::randomWord()); } + return true; } } diff --git a/src/ChurchCRM/model/ChurchCRM/KioskDeviceQuery.php b/src/ChurchCRM/model/ChurchCRM/KioskDeviceQuery.php index d303361b04..8d958ba72f 100644 --- a/src/ChurchCRM/model/ChurchCRM/KioskDeviceQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/KioskDeviceQuery.php @@ -12,7 +12,6 @@ * 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 db0f627e43..37f0952462 100644 --- a/src/ChurchCRM/model/ChurchCRM/ListOptionQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/ListOptionQuery.php @@ -15,9 +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 d1d9aafae1..7026149431 100644 --- a/src/ChurchCRM/model/ChurchCRM/Location.php +++ b/src/ChurchCRM/model/ChurchCRM/Location.php @@ -12,7 +12,6 @@ * 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 8aedf267dd..e443a93a51 100644 --- a/src/ChurchCRM/model/ChurchCRM/LocationQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/LocationQuery.php @@ -12,7 +12,6 @@ * 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 936f97e927..5594de26f1 100644 --- a/src/ChurchCRM/model/ChurchCRM/MenuLink.php +++ b/src/ChurchCRM/model/ChurchCRM/MenuLink.php @@ -12,7 +12,6 @@ * 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 ed4713d391..4aa45216f8 100644 --- a/src/ChurchCRM/model/ChurchCRM/MenuLinkQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/MenuLinkQuery.php @@ -12,7 +12,6 @@ * 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/Note.php b/src/ChurchCRM/model/ChurchCRM/Note.php index 2746199f9b..1275da1594 100644 --- a/src/ChurchCRM/model/ChurchCRM/Note.php +++ b/src/ChurchCRM/model/ChurchCRM/Note.php @@ -24,12 +24,12 @@ public function setEntered($enteredBy) public function getEditLink() { - $url = SystemURLs::getRootPath() . '/NoteEditor.php?NoteID=' . $this->getId() . '&'; + $url = SystemURLs::getRootPath().'/NoteEditor.php?NoteID='.$this->getId().'&'; if ($this->getPerId() != '') { - $url = $url . 'PersonID=' . $this->getPerId(); + $url = $url.'PersonID='.$this->getPerId(); } else { - $url = $url . 'FamilyID=' . $this->getFamId(); + $url = $url.'FamilyID='.$this->getFamId(); } return $url; @@ -37,7 +37,7 @@ public function getEditLink() public function getDeleteLink() { - return SystemURLs::getRootPath() . '/NoteDelete.php?NoteID=' . $this->getId(); + return SystemURLs::getRootPath().'/NoteDelete.php?NoteID='.$this->getId(); } public function getDisplayEditedDate($format = 'Y-m-d h:i:s') diff --git a/src/ChurchCRM/model/ChurchCRM/Person.php b/src/ChurchCRM/model/ChurchCRM/Person.php index ba06aa365d..eb00447137 100644 --- a/src/ChurchCRM/model/ChurchCRM/Person.php +++ b/src/ChurchCRM/model/ChurchCRM/Person.php @@ -70,8 +70,10 @@ public function getBirthDate() if ($birthYear === '') { $birthYear = 1900; } - return date_create($birthYear . '-' . $this->getBirthMonth() . '-' . $this->getBirthDay()); + + return date_create($birthYear.'-'.$this->getBirthMonth().'-'.$this->getBirthDay()); } + return false; } @@ -82,15 +84,15 @@ public function getFormattedBirthDate() return false; } if ($this->hideAge()) { - return $birthDate->format(SystemConfig::getValue("sDateFormatNoYear")); + return $birthDate->format(SystemConfig::getValue('sDateFormatNoYear')); } else { - return $birthDate->format(SystemConfig::getValue("sDateFormatLong")); + 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,6 +124,7 @@ public function getClassification() if (!empty($clsId)) { $classification = ListOptionQuery::create()->filterById(1)->filterByOptionId($clsId)->findOne(); } + return $classification; } @@ -132,16 +135,17 @@ public function getClassificationName() if ($classification !== null) { $classificationName = $classification->getOptionName(); } + return $classificationName; } public function postInsert(ConnectionInterface $con = null) { $this->createTimeLineNote('create'); - if (!empty(SystemConfig::getValue("sNewPersonNotificationRecipientIDs"))) { + if (!empty(SystemConfig::getValue('sNewPersonNotificationRecipientIDs'))) { $NotificationEmail = new NewPersonOrFamilyEmail($this); if (!$NotificationEmail->send()) { - LoggerUtils::getAppLogger()->warning(gettext("New Person Notification Email Error") . " :" . $NotificationEmail->getError()); + LoggerUtils::getAppLogger()->warning(gettext('New Person Notification Email Error').' :'.$NotificationEmail->getError()); } } } @@ -161,12 +165,12 @@ private function createTimeLineNote($type) $note->setDateEntered(new DateTime()); switch ($type) { - case "create": + case 'create': $note->setText(gettext('Created')); $note->setEnteredBy($this->getEnteredBy()); $note->setDateEntered($this->getDateEntered()); break; - case "edit": + case 'edit': $note->setText(gettext('Updated')); $note->setEnteredBy($this->getEditedBy()); $note->setDateEntered($this->getDateLastEdited()); @@ -185,6 +189,7 @@ public function isUser() /** * Get address of a person. If empty, return family address. + * * @return string */ public function getAddress() @@ -193,11 +198,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()); @@ -208,6 +213,7 @@ public function getAddress() if (!empty($this->getCountry())) { array_push($address, $this->getCountry()); } + return implode(' ', $address); } else { if ($this->getFamily()) { @@ -216,11 +222,12 @@ public function getAddress() } } //if it reaches here, no address found. return empty $address - return ""; + return ''; } /** * Get name of a person family. + * * @return string */ public function getFamilyName() @@ -229,12 +236,13 @@ public function getFamilyName() return $this->getFamily() ->getName(); } - //if it reaches here, no family name found. return empty family name - return ""; + //if it reaches here, no family name found. return empty family name + return ''; } /** * Get name of a person family. + * * @return string */ public function getFamilyCountry() @@ -243,15 +251,16 @@ public function getFamilyCountry() return $this->getFamily() ->getCountry(); } - //if it reaches here, no country found. return empty country - return ""; + //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) @@ -265,23 +274,25 @@ public function getFamilyPhone($type) break; case 1: if ($this->getFamily()) { - return $this->getFamily() - ->getWorkPhone(); + return $this->getFamily() + ->getWorkPhone(); } break; case 2: if ($this->getFamily()) { - return $this->getFamily() - ->getCellPhone(); + return $this->getFamily() + ->getCellPhone(); } break; } - //if it reaches here, no phone found. return empty phone - return ""; + //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() @@ -296,18 +307,19 @@ public function getLatLng() $lng = $latLng['Longitude']; } } else { - // Philippe Logel : this is usefull when a person don't have a family : ie not an address + // 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(); + $this->getFamily()->updateLanLng(); } $lat = $this->getFamily()->getLatitude(); $lng = $this->getFamily()->getLongitude(); } } + return [ - 'Latitude' => $lat, - 'Longitude' => $lng + 'Latitude' => $lat, + 'Longitude' => $lng, ]; } @@ -316,22 +328,25 @@ 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()); + $this->photo = new Photo('Person', $this->getId()); } + return $this->photo; } @@ -339,14 +354,16 @@ 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; } @@ -360,9 +377,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) @@ -371,101 +389,101 @@ 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()) { $nameString .= $this->getFirstName(); @@ -482,16 +500,17 @@ public function getFormattedName($Style) if (!$nameString) { // no first name $nameString = $this->getFirstName(); } else { - $nameString .= ', ' . $this->getFirstName(); + $nameString .= ', '.$this->getFirstName(); } } if ($this->getMiddleName()) { - $nameString .= ' ' . $this->getMiddleName(); + $nameString .= ' '.$this->getMiddleName(); } break; default: $nameString = trim($this->getFullName()); } + return $nameString; } @@ -520,7 +539,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); @@ -533,10 +552,11 @@ public function preDelete(ConnectionInterface $con = null) public function getProperties() { $personProperties = PropertyQuery::create() - ->filterByProClass("p") + ->filterByProClass('p') ->useRecordPropertyQuery() ->filterByRecordId($this->getId()) ->find(); + return $personProperties; } @@ -545,15 +565,16 @@ public function getProperties() public function getPropertiesString() { $personProperties = PropertyQuery::create() - ->filterByProClass("p") + ->filterByProClass('p') ->leftJoinRecordProperty() - ->where('r2p_record_ID=' . $this->getId()) + ->where('r2p_record_ID='.$this->getId()) ->find(); $PropertiesList = []; foreach ($personProperties as $element) { $PropertiesList[] = $element->getProName(); } + return $PropertiesList; } @@ -561,11 +582,11 @@ public function getPropertiesString() // created for the person-list.php datatable public function getCustomFields() { - // get list of custom field column names + // 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(); + // 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()); @@ -573,7 +594,7 @@ public function getCustomFields() } $thisPersonCustomFields = $rawQry->findOneByPerId($this->getId()); - // get custom column names and values + // get custom column names and values $personCustom = []; if ($rawQry->count() > 0) { foreach ($allPersonCustomFields as $customfield) { @@ -585,32 +606,36 @@ public function getCustomFields() } } } + 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()) + ->where('p2g2r_per_ID='.$this->getId()) ->find(); $group = []; foreach ($GroupList as $element) { $group[] = $element->getName(); } + 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); } @@ -648,25 +673,27 @@ public function getNumericAge() } 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 = [], $includeForeignObjects = false) { $array = parent::toArray(); $array['Address'] = $this->getAddress(); + return $array; } public function getThumbnailURL() { - return SystemURLs::getRootPath() . '/api/person/' . $this->getId() . '/thumbnail'; + return SystemURLs::getRootPath().'/api/person/'.$this->getId().'/thumbnail'; } public function getEmail() @@ -677,6 +704,7 @@ public function getEmail() return $family->getEmail(); } } + return parent::getEmail(); } } diff --git a/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunity.php b/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunity.php index c9f09aad92..766b18527a 100644 --- a/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunity.php +++ b/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunity.php @@ -12,7 +12,6 @@ * 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 e6e8804cf5..36f8d90869 100644 --- a/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunityQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/PersonVolunteerOpportunityQuery.php @@ -12,7 +12,6 @@ * 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 8305124a73..f82acd6b5b 100644 --- a/src/ChurchCRM/model/ChurchCRM/Pledge.php +++ b/src/ChurchCRM/model/ChurchCRM/Pledge.php @@ -23,10 +23,12 @@ 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) { @@ -44,10 +46,10 @@ public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColum $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. + // 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(); } diff --git a/src/ChurchCRM/model/ChurchCRM/Property.php b/src/ChurchCRM/model/ChurchCRM/Property.php index bbf979f647..8208299eeb 100644 --- a/src/ChurchCRM/model/ChurchCRM/Property.php +++ b/src/ChurchCRM/model/ChurchCRM/Property.php @@ -12,7 +12,6 @@ * 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 839ea14469..f00c0d04a4 100644 --- a/src/ChurchCRM/model/ChurchCRM/PropertyQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/PropertyQuery.php @@ -12,7 +12,6 @@ * 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 37ad740fca..16e0f06bb0 100644 --- a/src/ChurchCRM/model/ChurchCRM/PropertyType.php +++ b/src/ChurchCRM/model/ChurchCRM/PropertyType.php @@ -12,7 +12,6 @@ * 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 9ce7831b1a..4320620c46 100644 --- a/src/ChurchCRM/model/ChurchCRM/PropertyTypeQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/PropertyTypeQuery.php @@ -12,7 +12,6 @@ * 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/RecordProperty.php b/src/ChurchCRM/model/ChurchCRM/RecordProperty.php index 4f6e5acadd..2612be8f1b 100644 --- a/src/ChurchCRM/model/ChurchCRM/RecordProperty.php +++ b/src/ChurchCRM/model/ChurchCRM/RecordProperty.php @@ -12,7 +12,6 @@ * 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 87fed96820..38fdda99de 100644 --- a/src/ChurchCRM/model/ChurchCRM/RecordPropertyQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/RecordPropertyQuery.php @@ -12,7 +12,6 @@ * 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 78c659c02e..7fd7dbce35 100644 --- a/src/ChurchCRM/model/ChurchCRM/Token.php +++ b/src/ChurchCRM/model/ChurchCRM/Token.php @@ -12,31 +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 { - public const TYPE_FAMILY_VERIFY = "verifyFamily"; - private const TYPE_PASSWORD = "password"; + public const TYPE_FAMILY_VERIFY = 'verifyFamily'; + private const TYPE_PASSWORD = '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::TYPE_FAMILY_VERIFY === $this->getType(); @@ -59,6 +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 af6036ac05..4d6723729f 100644 --- a/src/ChurchCRM/model/ChurchCRM/TokenQuery.php +++ b/src/ChurchCRM/model/ChurchCRM/TokenQuery.php @@ -12,7 +12,6 @@ * 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 d47a8d6a0e..c2cec4a910 100644 --- a/src/ChurchCRM/model/ChurchCRM/User.php +++ b/src/ChurchCRM/model/ChurchCRM/User.php @@ -71,9 +71,10 @@ public function isManageGroupsEnabled() public function isFinanceEnabled() { - if (SystemConfig::getBooleanValue("bEnabledFinance")) { + if (SystemConfig::getBooleanValue('bEnabledFinance')) { return $this->isAdmin() || $this->isFinance(); } + return false; } @@ -104,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 @@ -148,6 +149,7 @@ public function resetPasswordToRandom() $this->updatePassword($password); $this->setNeedPasswordChange(true); $this->setFailedLogins(0); + return $password; } @@ -160,6 +162,7 @@ public static function randomPassword() $n = random_int(0, $alphaLength); $pass[] = $alphabet[$n]; } + return implode($pass); //turn the array into a string } @@ -170,12 +173,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) @@ -186,25 +189,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; } @@ -216,48 +219,48 @@ 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; } @@ -279,7 +282,6 @@ public function setUserConfigString($userConfigName, $value) } } - public function setSetting($name, $value) { $setting = $this->getSetting($name); @@ -295,7 +297,8 @@ public function setSetting($name, $value) public function getSettingValue($name) { $userSetting = $this->getSetting($name); - return $userSetting === null ? "" : $userSetting->getValue(); + + return $userSetting === null ? '' : $userSetting->getValue(); } public function getSetting($name) @@ -305,6 +308,7 @@ public function getSetting($name) return $userSetting; } } + return null; } @@ -315,17 +319,18 @@ public function getStyle() array_push($cssClasses, $skin); array_push($cssClasses, $this->getSetting(UserSetting::UI_BOXED)); array_push($cssClasses, $this->getSetting(UserSetting::UI_SIDEBAR)); + return implode(' ', $cssClasses); } public function isShowPledges() { - return $this->getSettingValue(UserSetting::FINANCE_SHOW_PLEDGES) == "true"; + return $this->getSettingValue(UserSetting::FINANCE_SHOW_PLEDGES) == 'true'; } public function isShowPayments() { - return $this->getSettingValue(UserSetting::FINANCE_SHOW_PAYMENTS) == "true"; + return $this->getSettingValue(UserSetting::FINANCE_SHOW_PAYMENTS) == 'true'; } public function getShowSince() @@ -343,6 +348,7 @@ 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; } @@ -355,8 +361,10 @@ public function confirmProvisional2FACode($twoFACode) if ($isKeyValid) { $this->setTwoFactorAuthSecret($this->provisional2FAKey); $this->save(); + return true; } + return $isKeyValid; } @@ -373,7 +381,7 @@ public function getDecryptedTwoFactorAuthSecret() private function getDecryptedTwoFactorAuthRecoveryCodes() { - return explode(",", Crypto::decryptWithPassword($this->getTwoFactorAuthRecoveryCodes(), KeyManager::getTwoFASecretKey())); + return explode(',', Crypto::decryptWithPassword($this->getTwoFactorAuthRecoveryCodes(), KeyManager::getTwoFASecretKey())); } public function disableTwoFactorAuthentication() @@ -395,9 +403,10 @@ public function getNewTwoFARecoveryCodes() 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; } @@ -409,6 +418,7 @@ public function isTwoFACodeValid($twoFACode) if ($timestamp !== false) { $this->setTwoFactorAuthLastKeyTimestamp($timestamp); $this->save(); + return true; } else { return false; @@ -422,10 +432,12 @@ public function isTwoFaRecoveryCodeValid($twoFaRecoveryCode) $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; } @@ -434,44 +446,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) { $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/UserSetting.php b/src/ChurchCRM/model/ChurchCRM/UserSetting.php index 2b7eb151cf..1cebd7e82a 100644 --- a/src/ChurchCRM/model/ChurchCRM/UserSetting.php +++ b/src/ChurchCRM/model/ChurchCRM/UserSetting.php @@ -15,13 +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/Version.php b/src/ChurchCRM/model/ChurchCRM/Version.php index 5ae3250395..0f84225615 100644 --- a/src/ChurchCRM/model/ChurchCRM/Version.php +++ b/src/ChurchCRM/model/ChurchCRM/Version.php @@ -18,7 +18,7 @@ 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'; $statement = $con->prepare($query); @@ -36,7 +36,7 @@ public function preSave(\Propel\Runtime\Connection\ConnectionInterface $con = nu $statement = $con->prepare($query); $resultset = $statement->execute(); } - //then save this version + //then save this version return true; } diff --git a/src/ChurchCRM/tasks/CheckExecutionTimeTask.php b/src/ChurchCRM/tasks/CheckExecutionTimeTask.php index 16b397d3b7..e7c62aed7a 100644 --- a/src/ChurchCRM/tasks/CheckExecutionTimeTask.php +++ b/src/ChurchCRM/tasks/CheckExecutionTimeTask.php @@ -30,11 +30,11 @@ public function getLink(): string public function getTitle(): string { - return gettext('PHP Max Execution Time is too Short') . " (" . $this->executionTime . ")"; + return gettext('PHP Max Execution Time is too Short').' ('.$this->executionTime.')'; } public function getDesc(): string { - 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 397edb58a0..97ec5102cf 100644 --- a/src/ChurchCRM/tasks/CheckUploadSizeTask.php +++ b/src/ChurchCRM/tasks/CheckUploadSizeTask.php @@ -32,12 +32,12 @@ public function getLink(): string public function getTitle(): string { - return gettext('PHP Max File size too small') . " (" . $this->sizeString . ")"; + return gettext('PHP Max File size too small').' ('.$this->sizeString.')'; } public function getDesc(): string { - 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.'); } private static function returnBytes(string $val): int diff --git a/src/ChurchCRM/tasks/ChurchAddress.php b/src/ChurchCRM/tasks/ChurchAddress.php index 4c9e705e51..0027221a0b 100644 --- a/src/ChurchCRM/tasks/ChurchAddress.php +++ b/src/ChurchCRM/tasks/ChurchAddress.php @@ -2,9 +2,9 @@ namespace ChurchCRM\Tasks; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; -use ChurchCRM\Authentication\AuthenticationManager; class ChurchAddress implements TaskInterface { @@ -20,7 +20,7 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/SystemSettings.php'; + return SystemURLs::getRootPath().'/SystemSettings.php'; } public function getTitle(): string @@ -30,6 +30,6 @@ public function getTitle(): string public function getDesc(): string { - return gettext("Church Address is not Set."); + return gettext('Church Address is not Set.'); } } diff --git a/src/ChurchCRM/tasks/ChurchNameTask.php b/src/ChurchCRM/tasks/ChurchNameTask.php index 8a77c0855f..7097f20870 100644 --- a/src/ChurchCRM/tasks/ChurchNameTask.php +++ b/src/ChurchCRM/tasks/ChurchNameTask.php @@ -2,9 +2,9 @@ namespace ChurchCRM\Tasks; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; -use ChurchCRM\Authentication\AuthenticationManager; class ChurchNameTask implements TaskInterface { @@ -20,7 +20,7 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/SystemSettings.php'; + return SystemURLs::getRootPath().'/SystemSettings.php'; } public function getTitle(): string @@ -30,6 +30,6 @@ public function getTitle(): string public function getDesc(): string { - return gettext("Church Name is set to default value"); + return gettext('Church Name is set to default value'); } } diff --git a/src/ChurchCRM/tasks/EmailTask.php b/src/ChurchCRM/tasks/EmailTask.php index b7061cb565..fd846e545b 100644 --- a/src/ChurchCRM/tasks/EmailTask.php +++ b/src/ChurchCRM/tasks/EmailTask.php @@ -2,9 +2,9 @@ namespace ChurchCRM\Tasks; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; -use ChurchCRM\Authentication\AuthenticationManager; class EmailTask implements TaskInterface { @@ -20,7 +20,7 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/SystemSettings.php'; + return SystemURLs::getRootPath().'/SystemSettings.php'; } public function getTitle(): string @@ -30,6 +30,6 @@ public function getTitle(): string public function getDesc(): string { - return gettext("SMTP Server info are blank"); + return gettext('SMTP Server info are blank'); } } diff --git a/src/ChurchCRM/tasks/HttpsTask.php b/src/ChurchCRM/tasks/HttpsTask.php index 82947c33f4..1c3d040e37 100644 --- a/src/ChurchCRM/tasks/HttpsTask.php +++ b/src/ChurchCRM/tasks/HttpsTask.php @@ -2,8 +2,8 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\dto\SystemURLs; use ChurchCRM\Authentication\AuthenticationManager; +use ChurchCRM\dto\SystemURLs; class HttpsTask implements TaskInterface { diff --git a/src/ChurchCRM/tasks/IntegrityCheckTask.php b/src/ChurchCRM/tasks/IntegrityCheckTask.php index 0305bc0623..bf108eb5ee 100644 --- a/src/ChurchCRM/tasks/IntegrityCheckTask.php +++ b/src/ChurchCRM/tasks/IntegrityCheckTask.php @@ -2,8 +2,8 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\dto\SystemURLs; use ChurchCRM\Authentication\AuthenticationManager; +use ChurchCRM\dto\SystemURLs; use ChurchCRM\Utils\MiscUtils; class IntegrityCheckTask implements TaskInterface @@ -12,7 +12,7 @@ class IntegrityCheckTask implements TaskInterface public function __construct() { - $integrityCheckPath = SystemURLs::getDocumentRoot() . '/integrityCheck.json'; + $integrityCheckPath = SystemURLs::getDocumentRoot().'/integrityCheck.json'; if (is_file($integrityCheckPath)) { $integrityCheckContents = file_get_contents($integrityCheckPath); MiscUtils::throwIfFailed($integrityCheckContents); @@ -33,7 +33,7 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/v2/admin/debug'; + return SystemURLs::getRootPath().'/v2/admin/debug'; } public function getTitle(): string diff --git a/src/ChurchCRM/tasks/LatestReleaseTask.php b/src/ChurchCRM/tasks/LatestReleaseTask.php index 561305c229..c28d556968 100644 --- a/src/ChurchCRM/tasks/LatestReleaseTask.php +++ b/src/ChurchCRM/tasks/LatestReleaseTask.php @@ -2,11 +2,10 @@ namespace ChurchCRM\Tasks; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\dto\SystemURLs; use ChurchCRM\Utils\ChurchCRMReleaseManager; use ChurchCRM\Utils\LoggerUtils; -use ChurchCRM\dto\ChurchCRMRelease; -use ChurchCRM\Authentication\AuthenticationManager; class LatestReleaseTask implements TaskInterface { @@ -21,7 +20,7 @@ public function __construct() public function isActive(): bool { $isCurrent = ChurchCRMReleaseManager::isReleaseCurrent($this->installedVersion); - if (! $isCurrent) { + if (!$isCurrent) { try { // This can fail with an exception if the currently running software is "not current" // but there are no more available releases. @@ -30,10 +29,13 @@ public function isActive(): bool $this->latestVersion = ChurchCRMReleaseManager::getNextReleaseStep($this->installedVersion); } catch (\Exception $e) { LoggerUtils::getAppLogger()->debug($e); + return false; } + return true; } + return false; } @@ -45,7 +47,7 @@ public function isAdmin(): bool public function getLink(): string { if (AuthenticationManager::getCurrentUser()->isAdmin()) { - return SystemURLs::getRootPath() . '/UpgradeCRM.php'; + return SystemURLs::getRootPath().'/UpgradeCRM.php'; } else { return 'https://github.com/ChurchCRM/CRM/releases/latest'; } @@ -53,7 +55,7 @@ public function getLink(): string public function getTitle(): string { - return gettext('New Release') . ' ' . $this->latestVersion; + return gettext('New Release').' '.$this->latestVersion; } public function getDesc(): string diff --git a/src/ChurchCRM/tasks/PHPPendingDeprecationVersionCheckTask.php b/src/ChurchCRM/tasks/PHPPendingDeprecationVersionCheckTask.php index d0a07f888d..2005de8081 100644 --- a/src/ChurchCRM/tasks/PHPPendingDeprecationVersionCheckTask.php +++ b/src/ChurchCRM/tasks/PHPPendingDeprecationVersionCheckTask.php @@ -2,7 +2,6 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; class PHPPendingDeprecationVersionCheckTask implements TaskInterface, PreUpgradeTaskInterface @@ -21,7 +20,7 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/v2/admin/debug'; + return SystemURLs::getRootPath().'/v2/admin/debug'; } public function getTitle(): string @@ -31,6 +30,6 @@ public function getTitle(): string public function getDesc(): string { - return gettext('Support for this PHP version will soon be removed. Current PHP Version: ' . PHP_VERSION . ". Minimum Required PHP Version: " . $this::REQUIRED_PHP_VERSION); + return gettext('Support for this PHP version will soon be removed. Current PHP Version: '.PHP_VERSION.'. Minimum Required PHP Version: '.$this::REQUIRED_PHP_VERSION); } } diff --git a/src/ChurchCRM/tasks/PHPZipArchiveCheckTask.php b/src/ChurchCRM/tasks/PHPZipArchiveCheckTask.php index a048660ecb..f40e16f566 100644 --- a/src/ChurchCRM/tasks/PHPZipArchiveCheckTask.php +++ b/src/ChurchCRM/tasks/PHPZipArchiveCheckTask.php @@ -2,15 +2,14 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; class PHPZipArchiveCheckTask implements TaskInterface, PreUpgradeTaskInterface { - // todo: make these const variables private after deprecating PHP7.0 #4948 + // todo: make these const variables private after deprecating PHP7.0 #4948 public function isActive(): bool { - return !class_exists("ZipArchive"); + return !class_exists('ZipArchive'); } public function isAdmin(): bool @@ -20,7 +19,7 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/v2/admin/debug'; + return SystemURLs::getRootPath().'/v2/admin/debug'; } public function getTitle(): string @@ -30,6 +29,6 @@ public function getTitle(): string public function getDesc(): string { - return gettext("PHP ZipArchive required to support upgrade"); + return gettext('PHP ZipArchive required to support upgrade'); } } diff --git a/src/ChurchCRM/tasks/PersonClassificationDataCheck.php b/src/ChurchCRM/tasks/PersonClassificationDataCheck.php index 7272532098..846410d702 100644 --- a/src/ChurchCRM/tasks/PersonClassificationDataCheck.php +++ b/src/ChurchCRM/tasks/PersonClassificationDataCheck.php @@ -31,16 +31,16 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/v2/people?Classification=0'; + return SystemURLs::getRootPath().'/v2/people?Classification=0'; } public function getTitle(): string { - return gettext('Missing Classification Data') . " (" . $this->count . ")"; + return gettext('Missing Classification Data').' ('.$this->count.')'; } public function getDesc(): string { - 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 bf3b4f56cb..33b4673a87 100644 --- a/src/ChurchCRM/tasks/PersonGenderDataCheck.php +++ b/src/ChurchCRM/tasks/PersonGenderDataCheck.php @@ -31,16 +31,16 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/v2/people?Gender=0'; + return SystemURLs::getRootPath().'/v2/people?Gender=0'; } public function getTitle(): string { - return gettext('Missing Gender Data') . " (" . $this->count . ")"; + return gettext('Missing Gender Data').' ('.$this->count.')'; } public function getDesc(): string { - 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 8038669110..4d793758e3 100644 --- a/src/ChurchCRM/tasks/PersonRoleDataCheck.php +++ b/src/ChurchCRM/tasks/PersonRoleDataCheck.php @@ -14,7 +14,7 @@ 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(); } @@ -31,16 +31,16 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/v2/people?FamilyRole=0'; + return SystemURLs::getRootPath().'/v2/people?FamilyRole=0'; } public function getTitle(): string { - return gettext('Missing Role Data') . " (" . $this->count . ")"; + return gettext('Missing Role Data').' ('.$this->count.')'; } public function getDesc(): string { - 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 9e16852914..a477ac7ab6 100644 --- a/src/ChurchCRM/tasks/PrerequisiteCheckTask.php +++ b/src/ChurchCRM/tasks/PrerequisiteCheckTask.php @@ -9,7 +9,7 @@ class PrerequisiteCheckTask implements TaskInterface { public function isActive(): bool { - return ! AppIntegrityService::arePrerequisitesMet(); + return !AppIntegrityService::arePrerequisitesMet(); } public function isAdmin(): bool @@ -19,7 +19,7 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/v2/admin/debug'; + return SystemURLs::getRootPath().'/v2/admin/debug'; } public function getTitle(): string diff --git a/src/ChurchCRM/tasks/SecretsConfigurationCheckTask.php b/src/ChurchCRM/tasks/SecretsConfigurationCheckTask.php index 4a11d637bb..41c7622382 100644 --- a/src/ChurchCRM/tasks/SecretsConfigurationCheckTask.php +++ b/src/ChurchCRM/tasks/SecretsConfigurationCheckTask.php @@ -9,7 +9,7 @@ class SecretsConfigurationCheckTask implements TaskInterface { public function isActive(): bool { - return ! KeyManager::getAreAllSecretsDefined(); + return !KeyManager::getAreAllSecretsDefined(); } public function isAdmin(): bool diff --git a/src/ChurchCRM/tasks/TaskInterface.php b/src/ChurchCRM/tasks/TaskInterface.php index 86d3ef39c2..a2177f2eda 100644 --- a/src/ChurchCRM/tasks/TaskInterface.php +++ b/src/ChurchCRM/tasks/TaskInterface.php @@ -5,8 +5,12 @@ interface TaskInterface { public function isActive(): bool; + public function isAdmin(): bool; + public function getLink(): string; + public function getTitle(): string; + public function getDesc(): string; } diff --git a/src/ChurchCRM/tasks/UnsupportedDepositCheck.php b/src/ChurchCRM/tasks/UnsupportedDepositCheck.php index 3c08887cb5..4aaa44a673 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 TaskInterface { @@ -13,7 +13,7 @@ class UnsupportedDepositCheck implements TaskInterface public function __construct() { $UnsupportedQuery = DepositQuery::create() - ->filterByType("Bank", Criteria::NOT_EQUAL) + ->filterByType('Bank', Criteria::NOT_EQUAL) ->find(); $this->count = $UnsupportedQuery->count(); } @@ -35,11 +35,11 @@ public function getLink(): string public function getTitle(): string { - return gettext('Unsupported Deposit Types Detected') . " (" . $this->count . ")"; + return gettext('Unsupported Deposit Types Detected').' ('.$this->count.')'; } public function getDesc(): string { - 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 0d7117b90f..7b1c00056d 100644 --- a/src/ChurchCRM/tasks/UpdateFamilyCoordinatesTask.php +++ b/src/ChurchCRM/tasks/UpdateFamilyCoordinatesTask.php @@ -2,8 +2,8 @@ namespace ChurchCRM\Tasks; -use ChurchCRM\FamilyQuery; use ChurchCRM\dto\SystemURLs; +use ChurchCRM\FamilyQuery; class UpdateFamilyCoordinatesTask { @@ -11,7 +11,7 @@ class UpdateFamilyCoordinatesTask public function __construct() { - $query = FamilyQuery::create()->filterByLatitude("")->find(); + $query = FamilyQuery::create()->filterByLatitude('')->find(); $this->count = $query->count(); } @@ -27,16 +27,16 @@ public function isAdmin(): bool public function getLink(): string { - return SystemURLs::getRootPath() . '/UpdateAllLatLon.php'; + return SystemURLs::getRootPath().'/UpdateAllLatLon.php'; } public function getTitle(): string { - return gettext('Missing Coordinates') . " (" . $this->count . ")"; + return gettext('Missing Coordinates').' ('.$this->count.')'; } public function getDesc(): string { - return gettext("Family Coordinates Data for Some Families"); + return gettext('Family Coordinates Data for Some Families'); } } diff --git a/src/ChurchCRM/utils/ExecutionTime.php b/src/ChurchCRM/utils/ExecutionTime.php index 11ba0539bf..e47e535543 100644 --- a/src/ChurchCRM/utils/ExecutionTime.php +++ b/src/ChurchCRM/utils/ExecutionTime.php @@ -4,11 +4,12 @@ class ExecutionTime { - // inspired from https://stackoverflow.com/a/22885011 + // inspired from https://stackoverflow.com/a/22885011 private $startTime; private $endTime; private $startR; private $endR; + public function __construct() { $this->startTime = microtime(true); @@ -23,26 +24,27 @@ public function end() 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 End() has not yet been called, this returns the current number of running seconds. + // Otherwise, returns the ending number of seconds if ($this->endTime === null) { $value = (microtime(true) - $this->startTime) * 1000; } else { $value = ($this->endTime - $this->startTime) * 1000; } + 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)); + - ($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") . + 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"; } } diff --git a/src/ChurchCRM/utils/GeoUtils.php b/src/ChurchCRM/utils/GeoUtils.php index d7e049e191..c88933858b 100644 --- a/src/ChurchCRM/utils/GeoUtils.php +++ b/src/ChurchCRM/utils/GeoUtils.php @@ -2,21 +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(); @@ -25,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(); @@ -45,12 +43,12 @@ 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 [ - 'Latitude' => $lat, - 'Longitude' => $long + 'Latitude' => $lat, + 'Longitude' => $long, ]; } @@ -58,17 +56,18 @@ 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, 512, JSON_THROW_ON_ERROR); $matrixElements = $details['rows'][0]['elements'][0]; + return [ 'distance' => $matrixElements['distance']['text'], - 'duration' => $matrixElements['duration']['text'] + 'duration' => $matrixElements['duration']['text'], ]; } @@ -77,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 32e146c251..7e2a4774f8 100644 --- a/src/ChurchCRM/utils/InputUtils.php +++ b/src/ChurchCRM/utils/InputUtils.php @@ -20,10 +20,10 @@ public static function legacyFilterInputArr($arr, $key, $type = 'string', $size public static function translateSpecialCharset($string) { if (empty($string)) { - return ""; + return ''; } - return (SystemConfig::getValue("sCSVExportCharset") == "UTF-8") ? gettext($string) : iconv('UTF-8', SystemConfig::getValue("sCSVExportCharset"), gettext($string)); + return (SystemConfig::getValue('sCSVExportCharset') == 'UTF-8') ? gettext($string) : iconv('UTF-8', SystemConfig::getValue('sCSVExportCharset'), gettext($string)); } public static function filterString($sInput) @@ -54,18 +54,18 @@ public static function filterFloat($sInput) public static function filterDate($sInput) { - // Attempts to take a date in any format and convert it to YYYY-MM-DD format - // Logel Philippe + // Attempts to take a date in any format and convert it to YYYY-MM-DD format + // Logel Philippe if (empty($sInput)) { - return ""; + return ''; } else { - return date('Y-m-d', strtotime(str_replace("/", "-", $sInput))); + return date('Y-m-d', strtotime(str_replace('/', '-', $sInput))); } } - // Sanitizes user input as a security measure - // Optionally, a filtering type and size may be specified. By default, strip any tags from a string. - // Note that a database connection must already be established for the mysqli_real_escape_string function to work. + // Sanitizes user input as a security measure + // Optionally, a filtering type and size may be specified. By default, strip any tags from a string. + // Note that a database connection must already be established for the mysqli_real_escape_string function to work. public static function legacyFilterInput($sInput, $type = 'string', $size = 1) { global $cnInfoCentral; diff --git a/src/ChurchCRM/utils/LoggerUtils.php b/src/ChurchCRM/utils/LoggerUtils.php index 15d7d4c482..7b5fbe6bf5 100644 --- a/src/ChurchCRM/utils/LoggerUtils.php +++ b/src/ChurchCRM/utils/LoggerUtils.php @@ -2,12 +2,10 @@ namespace ChurchCRM\Utils; -use Monolog\Handler\StreamHandler; -use Monolog\Logger; use ChurchCRM\dto\SystemConfig; use ChurchCRM\dto\SystemURLs; -use ChurchCRM\Utils\RemoteAddress; -use ChurchCRM\Authentication\AuthenticationManager; +use Monolog\Handler\StreamHandler; +use Monolog\Logger; class LoggerUtils { @@ -23,17 +21,18 @@ public static function getCorrelationId() if (empty(self::$correlationId)) { self::$correlationId = uniqid(); } + return self::$correlationId; } public static function getLogLevel() { - return intval(SystemConfig::getValue("sLogLevel")); + return intval(SystemConfig::getValue('sLogLevel')); } public static function buildLogFilePath($type) { - return $logFilePrefix = SystemURLs::getDocumentRoot() . '/logs/' . date("Y-m-d") . '-' . $type . '.log'; + return $logFilePrefix = SystemURLs::getDocumentRoot().'/logs/'.date('Y-m-d').'-'.$type.'.log'; } /** @@ -42,23 +41,25 @@ public static function buildLogFilePath($type) public static function getAppLogger($level = null) { if (self::$appLogger === null) { - // if $level is null - // (meaning this function was invoked without explicitly setting the level), - // then get the level from the database + // if $level is null + // (meaning this function was invoked without explicitly setting the level), + // then get the level from the database if ($level === null) { $level = self::getLogLevel(); } self::$appLogger = new Logger('defaultLogger'); - //hold a reference to the handler object so that resetAppLoggerLevel can be called later on - self::$appLogHandler = new StreamHandler(self::buildLogFilePath("app"), $level); + //hold a reference to the handler object so that resetAppLoggerLevel can be called later on + self::$appLogHandler = new StreamHandler(self::buildLogFilePath('app'), $level); self::$appLogger->pushHandler(self::$appLogHandler); self::$appLogger->pushProcessor(function ($entry) { $entry['extra']['url'] = $_SERVER['REQUEST_URI']; $entry['extra']['remote_ip'] = $_SERVER['REMOTE_ADDR']; $entry['extra']['correlation_id'] = self::getCorrelationId(); + return $entry; }); } + return self::$appLogger; } @@ -69,9 +70,10 @@ private static function getCaller() if ($callers[5]) { $call = $callers[5]; } + return [ - "ContextClass" => array_key_exists("class", $call) ? $call['class'] : "", - "ContextMethod" => $call['function'] + 'ContextClass' => array_key_exists('class', $call) ? $call['class'] : '', + 'ContextMethod' => $call['function'], ]; } @@ -81,15 +83,15 @@ private static function getCaller() public static function getAuthLogger($level = null) { if (self::$authLogger === null) { - // if $level is null - // (meaning this function was invoked without explicitly setting the level), - // then get the level from the database + // if $level is null + // (meaning this function was invoked without explicitly setting the level), + // then get the level from the database if ($level === null) { $level = self::getLogLevel(); } self::$authLogger = new Logger('authLogger'); - //hold a reference to the handler object so that resetAppLoggerLevel can be called later on - self::$authLogHandler = new StreamHandler(self::buildLogFilePath("auth"), $level); + //hold a reference to the handler object so that resetAppLoggerLevel can be called later on + self::$authLogHandler = new StreamHandler(self::buildLogFilePath('auth'), $level); self::$authLogger->pushHandler(self::$authLogHandler); self::$authLogger->pushProcessor(function ($entry) { $entry['extra']['url'] = $_SERVER['REQUEST_URI']; @@ -100,14 +102,15 @@ public static function getAuthLogger($level = null) return $entry; }); } + return self::$authLogger; } public static function resetAppLoggerLevel() { - // if the app log handler was initialized (in the boostrapper) to a specific level - // before the database initialization occurred - // we provide a function to reset the app logger to what's defined in the database. + // if the app log handler was initialized (in the boostrapper) to a specific level + // before the database initialization occurred + // we provide a function to reset the app logger to what's defined in the database. self::$appLogHandler->setLevel(self::getLogLevel()); } @@ -115,8 +118,9 @@ public static function getCSPLogger() { if (self::$cspLogger === null) { self::$cspLogger = new Logger('cspLogger'); - self::$cspLogger->pushHandler(new StreamHandler(self::buildLogFilePath("csp"), self::getLogLevel())); + self::$cspLogger->pushHandler(new StreamHandler(self::buildLogFilePath('csp'), self::getLogLevel())); } + return self::$cspLogger; } } diff --git a/src/ChurchCRM/utils/MiscUtils.php b/src/ChurchCRM/utils/MiscUtils.php index c994ab1faf..4edfb168df 100644 --- a/src/ChurchCRM/utils/MiscUtils.php +++ b/src/ChurchCRM/utils/MiscUtils.php @@ -6,9 +6,9 @@ class MiscUtils { - /** - * @param bool|mixed $isSuccessful - */ + /** + * @param bool|mixed $isSuccessful + */ public static function throwIfFailed($isSuccessful): void { if ($isSuccessful === false) { @@ -25,6 +25,7 @@ public static function randomToken() $n = random_int(0, $alphaLength); $apiKey[] = $alphabet[$n]; } + return implode($apiKey); //turn the array into a string } @@ -33,18 +34,19 @@ public static function randomWord($length = 6) $cons = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'z', 'pt', 'gl', 'gr', 'ch', 'ph', 'ps', 'sh', 'st', 'th', 'wh']; $cons_cant_start = ['ck', 'cm', 'dr', 'ds', 'ft', 'gh', 'gn', 'kr', 'ks', 'ls', 'lt', 'lr', 'mp', 'mt', 'ms', 'ng', 'ns', 'rd', 'rg', 'rs', 'rt', 'ss', 'ts', 'tch']; $vows = ['a', 'e', 'i', 'o', 'u', 'y', 'ee', 'oa', 'oo']; - $current = ( random_int(0, 1) == '0' ? 'cons' : 'vows' ); + $current = (random_int(0, 1) == '0' ? 'cons' : 'vows'); $word = ''; while (strlen($word) < $length) { if (strlen($word) == 2) { $cons = array_merge($cons, $cons_cant_start); } - $rnd = ${$current}[ random_int(0, count(${$current}) - 1) ]; - if (strlen($word . $rnd) <= $length) { + $rnd = ${$current}[random_int(0, count(${$current}) - 1)]; + if (strlen($word.$rnd) <= $length) { $word .= $rnd; - $current = ( $current == 'cons' ? 'vows' : 'cons' ); + $current = ($current == 'cons' ? 'vows' : 'cons'); } } + return $word; } @@ -61,9 +63,10 @@ public static function getRandomCache($baseCacheTime, $variability) public static function getPhotoCacheExpirationTimestamp() { - $cacheLength = SystemConfig::getValue("iPhotoClientCacheDuration"); + $cacheLength = SystemConfig::getValue('iPhotoClientCacheDuration'); $cacheLength = MiscUtils::getRandomCache($cacheLength, 0.5 * $cacheLength); - return time() + $cacheLength ; + + return time() + $cacheLength; } public static function formatAge(int $Month, int $Day, int $Year) @@ -84,8 +87,8 @@ public static function formatAge(int $Month, int $Day, int $Year) return sprintf(ngettext('%d year old', '%d years old', $age->y), $age->y); } - // Format a BirthDate - // Optionally, the separator may be specified. Default is YEAR-MN-DY + // Format a BirthDate + // Optionally, the separator may be specified. Default is YEAR-MN-DY public static function formatBirthDate($per_BirthYear, $per_BirthMonth, $per_BirthDay, $sSeparator, $bFlags) { $birthDate = MiscUtils::birthDate($per_BirthYear, $per_BirthMonth, $per_BirthDay); @@ -93,20 +96,20 @@ public static function formatBirthDate($per_BirthYear, $per_BirthMonth, $per_Bir return false; } if ($bFlags || $per_BirthYear === null || $per_BirthYear === '') { - return $birthDate->format(SystemConfig::getValue("sDateFormatNoYear")); + return $birthDate->format(SystemConfig::getValue('sDateFormatNoYear')); } - return $birthDate->format(SystemConfig::getValue("sDateFormatLong")); + return $birthDate->format(SystemConfig::getValue('sDateFormatLong')); } public static function birthDate($year, $month, $day) { if (!$day !== null && $day !== '' && $month !== null && $month !== '') { if ($year === null || $year === '') { - $year = 1900; + $year = 1900; } - return date_create($year . '-' . $month . '-' . $day); + return date_create($year.'-'.$month.'-'.$day); } return false; @@ -114,12 +117,12 @@ public static function birthDate($year, $month, $day) public static function getGitHubWikiAnchorLink($text) { - // roughly adapted from https://gist.github.com/asabaylus/3071099#gistcomment-1593627 + // roughly adapted from https://gist.github.com/asabaylus/3071099#gistcomment-1593627 $anchor = strtolower($text); $anchor = preg_replace('/[^\w\d\- ]+/', '', $anchor); $anchor = preg_replace('/\s/', '-', $anchor); $anchor = preg_replace('/\-+$/', '', $anchor); - $anchor = str_replace(" ", "-", $anchor); + $anchor = str_replace(' ', '-', $anchor); return $anchor; } diff --git a/src/ChurchCRM/utils/ORMUtils.php b/src/ChurchCRM/utils/ORMUtils.php index 15f28d0845..d23c0b2ce6 100644 --- a/src/ChurchCRM/utils/ORMUtils.php +++ b/src/ChurchCRM/utils/ORMUtils.php @@ -8,8 +8,9 @@ public static function getValidationErrors($failures) { $validationErrors = []; foreach ($failures as $failure) { - array_push($validationErrors, "Property " . $failure->getPropertyPath() . ": " . $failure->getMessage()); + array_push($validationErrors, 'Property '.$failure->getPropertyPath().': '.$failure->getMessage()); } + return $validationErrors; } } diff --git a/src/ChurchCRM/utils/PHPToMomentJSConverter.php b/src/ChurchCRM/utils/PHPToMomentJSConverter.php index c60cd9d422..8f669cf173 100644 --- a/src/ChurchCRM/utils/PHPToMomentJSConverter.php +++ b/src/ChurchCRM/utils/PHPToMomentJSConverter.php @@ -49,10 +49,12 @@ class PHPToMomentJSConverter 'r' => '', // no equivalent 'U' => 'X', ]; + public static function convertFormatString($string) { - //borrowed from https://stackoverflow.com/questions/30186611/php-dateformat-to-moment-js-format + //borrowed from https://stackoverflow.com/questions/30186611/php-dateformat-to-moment-js-format $momentFormat = strtr($string, self::$replacements); + return $momentFormat; } } diff --git a/src/ChurchCRM/utils/RedirectUtils.php b/src/ChurchCRM/utils/RedirectUtils.php index 5e6c065e17..3dc0766d26 100644 --- a/src/ChurchCRM/utils/RedirectUtils.php +++ b/src/ChurchCRM/utils/RedirectUtils.php @@ -8,33 +8,34 @@ class RedirectUtils { /** * Convert a relative URL into an absolute URL and redirect the browser there. + * * @param string $sRelativeURL + * * @throws \Exception */ public static function redirect($sRelativeURL) { - if (substr($sRelativeURL, 0, 1) != "/") { - $sRelativeURL = "/" . $sRelativeURL; + if (substr($sRelativeURL, 0, 1) != '/') { + $sRelativeURL = '/'.$sRelativeURL; } if (substr($sRelativeURL, 0, strlen(SystemURLs::getRootPath())) != SystemURLs::getRootPath()) { - $finalLocation = SystemURLs::getRootPath() . $sRelativeURL; + $finalLocation = SystemURLs::getRootPath().$sRelativeURL; } else { $finalLocation = $sRelativeURL; } - header('Location: ' . $finalLocation); + header('Location: '.$finalLocation); exit; } public static function absoluteRedirect($sTargetURL) { - header('Location: ' . $sTargetURL); + header('Location: '.$sTargetURL); exit; } - public static function securityRedirect($missingRole) { - LoggerUtils::getAppLogger()->info("Security Redirect Request due to Role: " . $missingRole); - self::Redirect("Menu.php"); + LoggerUtils::getAppLogger()->info('Security Redirect Request due to Role: '.$missingRole); + self::Redirect('Menu.php'); } } diff --git a/src/ConvertIndividualToFamily.php b/src/ConvertIndividualToFamily.php index e000de1a07..d452274304 100644 --- a/src/ConvertIndividualToFamily.php +++ b/src/ConvertIndividualToFamily.php @@ -24,8 +24,8 @@ require 'Include/Config.php'; require 'Include/Functions.php'; -use ChurchCRM\Utils\RedirectUtils; use ChurchCRM\Authentication\AuthenticationManager; +use ChurchCRM\Utils\RedirectUtils; // Security if (!AuthenticationManager::getCurrentUser()->isAdmin()) { @@ -78,19 +78,19 @@ fam_HomePhone, fam_DateEntered, fam_EnteredBy) - VALUES ('" . - $per_LastName . "','" . - $per_Address1 . "','" . - $per_Address2 . "','" . - $per_City . "','" . - $per_State . "','" . - $per_Zip . "','" . - $per_Country . "','" . - $per_HomePhone . "'," . - 'NOW()' . ",'" . - $curUserId . "')"; - - echo '
' . $sSQL; + VALUES ('". + $per_LastName."','". + $per_Address1."','". + $per_Address2."','". + $per_City."','". + $per_State."','". + $per_Zip."','". + $per_Country."','". + $per_HomePhone."',". + 'NOW()'.",'". + $curUserId."')"; + + echo '
'.$sSQL; // RunQuery to add family record RunQuery($sSQL); $iFamilyID++; // increment family ID @@ -109,20 +109,20 @@ echo '

'; // Now update person record - $sSQL = 'UPDATE person_per ' . - "SET per_fam_ID='$iFamilyID'," . - ' per_Address1=NULL,' . - ' per_Address2=NULL,' . - ' per_City=NULL,' . - ' per_State=NULL,' . - ' per_Zip=NULL,' . - ' per_Country=NULL,' . - ' per_HomePhone=NULL,' . - ' per_DateLastEdited=NOW(),' . - " per_EditedBy='$curUserId' " . + $sSQL = 'UPDATE person_per '. + "SET per_fam_ID='$iFamilyID',". + ' per_Address1=NULL,'. + ' per_Address2=NULL,'. + ' per_City=NULL,'. + ' per_State=NULL,'. + ' per_Zip=NULL,'. + ' per_Country=NULL,'. + ' per_HomePhone=NULL,'. + ' per_DateLastEdited=NOW(),'. + " per_EditedBy='$curUserId' ". "WHERE per_ID='$per_ID'"; - echo '
' . $sSQL; + echo '
'.$sSQL; RunQuery($sSQL); echo '


'; @@ -136,7 +136,7 @@ } echo '

'; -echo '' . gettext('Convert Next') . '

'; -echo '' . gettext('Convert All') . '
'; +echo ''.gettext('Convert Next').'

'; +echo ''.gettext('Convert All').'
'; require 'Include/Footer.php'; diff --git a/src/DonatedItemReplicate.php b/src/DonatedItemReplicate.php index f77fe70dc9..bd91e2d402 100644 --- a/src/DonatedItemReplicate.php +++ b/src/DonatedItemReplicate.php @@ -13,9 +13,9 @@ require 'Include/Config.php'; require 'Include/Functions.php'; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\Utils\InputUtils; use ChurchCRM\Utils\RedirectUtils; -use ChurchCRM\Authentication\AuthenticationManager; $iFundRaiserID = $_SESSION['iCurrentFundraiser']; $iDonatedItemID = InputUtils::legacyFilterInputArr($_GET, 'DonatedItemID', 'int'); @@ -31,15 +31,15 @@ if (strlen($startItem) == 2) { // replicated items will sort better if they have a two-digit number $letter = mb_substr($startItem, 0, 1); $number = mb_substr($startItem, 1, 1); - $startItem = $letter . '0' . $number; + $startItem = $letter.'0'.$number; } $letterNum = ord('a'); for ($i = 0; $i < $iCount; $i++) { $sSQL = 'INSERT INTO donateditem_di (di_item,di_FR_ID,di_donor_ID,di_multibuy,di_title,di_description,di_sellprice,di_estprice,di_minimum,di_materialvalue,di_EnteredBy,di_EnteredDate,di_picture)'; - $sSQL .= "SELECT '" . $startItem . chr($letterNum) . "',di_FR_ID,di_donor_ID,di_multibuy,di_title,di_description,di_sellprice,di_estprice,di_minimum,di_materialvalue,"; - $sSQL .= AuthenticationManager::getCurrentUser()->getId() . ",'" . date('YmdHis') . "',"; + $sSQL .= "SELECT '".$startItem.chr($letterNum)."',di_FR_ID,di_donor_ID,di_multibuy,di_title,di_description,di_sellprice,di_estprice,di_minimum,di_materialvalue,"; + $sSQL .= AuthenticationManager::getCurrentUser()->getId().",'".date('YmdHis')."',"; $sSQL .= 'di_picture'; $sSQL .= " FROM donateditem_di WHERE di_ID=$iDonatedItemID"; $ret = RunQuery($sSQL); diff --git a/src/FamilyCustomFieldsRowOps.php b/src/FamilyCustomFieldsRowOps.php index b25c58eeae..3bece6b5c3 100644 --- a/src/FamilyCustomFieldsRowOps.php +++ b/src/FamilyCustomFieldsRowOps.php @@ -14,9 +14,9 @@ require 'Include/Config.php'; require 'Include/Functions.php'; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\Utils\InputUtils; use ChurchCRM\Utils\RedirectUtils; -use ChurchCRM\Authentication\AuthenticationManager; // Security: user must be administrator to use this page. if (!AuthenticationManager::getCurrentUser()->isAdmin()) { @@ -32,24 +32,24 @@ switch ($sAction) { // Move a field up: Swap the fam_custom_Order (ordering) of the selected row and the one above it case 'up': - $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '" . $iOrderID . "' WHERE fam_custom_Order = '" . ($iOrderID - 1) . "'"; + $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '".$iOrderID."' WHERE fam_custom_Order = '".($iOrderID - 1)."'"; RunQuery($sSQL); - $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '" . ($iOrderID - 1) . "' WHERE fam_custom_Field = '" . $sField . "'"; + $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '".($iOrderID - 1)."' WHERE fam_custom_Field = '".$sField."'"; RunQuery($sSQL); break; // Move a field down: Swap the fam_custom_Order (ordering) of the selected row and the one below it case 'down': - $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '" . $iOrderID . "' WHERE fam_custom_Order = '" . ($iOrderID + 1) . "'"; + $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '".$iOrderID."' WHERE fam_custom_Order = '".($iOrderID + 1)."'"; RunQuery($sSQL); - $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '" . ($iOrderID + 1) . "' WHERE fam_custom_Field = '" . $sField . "'"; + $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '".($iOrderID + 1)."' WHERE fam_custom_Field = '".$sField."'"; RunQuery($sSQL); break; // Delete a field from the form case 'delete': // Check if this field is a custom list type. If so, the list needs to be deleted from list_lst. - $sSQL = "SELECT type_ID,fam_custom_Special FROM family_custom_master WHERE fam_custom_Field = '" . $sField . "'"; + $sSQL = "SELECT type_ID,fam_custom_Special FROM family_custom_master WHERE fam_custom_Field = '".$sField."'"; $rsTemp = RunQuery($sSQL); $aTemp = mysqli_fetch_array($rsTemp); if ($aTemp[0] == 12) { @@ -57,10 +57,10 @@ RunQuery($sSQL); } - $sSQL = 'ALTER TABLE `family_custom` DROP `' . $sField . '` ;'; + $sSQL = 'ALTER TABLE `family_custom` DROP `'.$sField.'` ;'; RunQuery($sSQL); - $sSQL = "DELETE FROM family_custom_master WHERE fam_custom_Field = '" . $sField . "'"; + $sSQL = "DELETE FROM family_custom_master WHERE fam_custom_Field = '".$sField."'"; RunQuery($sSQL); $sSQL = 'SELECT * FROM family_custom_master'; @@ -70,7 +70,7 @@ // Shift the remaining rows up by one, unless we've just deleted the only row if ($numRows > 0) { for ($reorderRow = $iOrderID + 1; $reorderRow <= $numRows + 1; $reorderRow++) { - $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '" . ($reorderRow - 1) . "' WHERE fam_custom_Order = '" . $reorderRow . "'"; + $sSQL = "UPDATE family_custom_master SET fam_custom_Order = '".($reorderRow - 1)."' WHERE fam_custom_Order = '".$reorderRow."'"; RunQuery($sSQL); } } diff --git a/src/FamilyVerify.php b/src/FamilyVerify.php index 5f859fc894..2eef709f51 100644 --- a/src/FamilyVerify.php +++ b/src/FamilyVerify.php @@ -9,10 +9,10 @@ //Get the FamilyID out of the querystring $iFamilyID = InputUtils::legacyFilterInput($_GET['FamilyID'], 'int'); -$family = FamilyQuery::create() +$family = FamilyQuery::create() ->findOneById($iFamilyID); $family->verify(); -header('Location: ' . $family->getViewURI()); +header('Location: '.$family->getViewURI()); exit; diff --git a/src/GroupPropsFormRowOps.php b/src/GroupPropsFormRowOps.php index fe3b4968c3..b5acab05a5 100644 --- a/src/GroupPropsFormRowOps.php +++ b/src/GroupPropsFormRowOps.php @@ -13,9 +13,9 @@ require 'Include/Config.php'; require 'Include/Functions.php'; +use ChurchCRM\Authentication\AuthenticationManager; use ChurchCRM\Utils\InputUtils; use ChurchCRM\Utils\RedirectUtils; -use ChurchCRM\Authentication\AuthenticationManager; // Security: user must be allowed to edit records to use this page. if (!AuthenticationManager::getCurrentUser()->isManageGroupsEnabled()) { @@ -30,36 +30,36 @@ $sAction = $_GET['Action']; // Get the group information -$sSQL = 'SELECT * FROM group_grp WHERE grp_ID = ' . $iGroupID; +$sSQL = 'SELECT * FROM group_grp WHERE grp_ID = '.$iGroupID; $rsGroupInfo = RunQuery($sSQL); extract(mysqli_fetch_array($rsGroupInfo)); // Abort if user tries to load with group having no special properties. if ($grp_hasSpecialProps == false) { - RedirectUtils::redirect('GroupView.php?GroupID=' . $iGroupID); + RedirectUtils::redirect('GroupView.php?GroupID='.$iGroupID); } switch ($sAction) { // Move a field up: Swap the prop_ID (ordering) of the selected row and the one above it case 'up': - $sSQL = "UPDATE groupprop_master SET prop_ID = '" . $iPropID . "' WHERE grp_ID = '" . $iGroupID . "' AND prop_ID = '" . ($iPropID - 1) . "'"; + $sSQL = "UPDATE groupprop_master SET prop_ID = '".$iPropID."' WHERE grp_ID = '".$iGroupID."' AND prop_ID = '".($iPropID - 1)."'"; RunQuery($sSQL); - $sSQL = "UPDATE groupprop_master SET prop_ID = '" . ($iPropID - 1) . "' WHERE grp_ID = '" . $iGroupID . "' AND prop_Field = '" . $sField . "'"; + $sSQL = "UPDATE groupprop_master SET prop_ID = '".($iPropID - 1)."' WHERE grp_ID = '".$iGroupID."' AND prop_Field = '".$sField."'"; RunQuery($sSQL); break; // Move a field down: Swap the prop_ID (ordering) of the selected row and the one below it case 'down': - $sSQL = "UPDATE groupprop_master SET prop_ID = '" . $iPropID . "' WHERE grp_ID = '" . $iGroupID . "' AND prop_ID = '" . ($iPropID + 1) . "'"; + $sSQL = "UPDATE groupprop_master SET prop_ID = '".$iPropID."' WHERE grp_ID = '".$iGroupID."' AND prop_ID = '".($iPropID + 1)."'"; RunQuery($sSQL); - $sSQL = "UPDATE groupprop_master SET prop_ID = '" . ($iPropID + 1) . "' WHERE grp_ID = '" . $iGroupID . "' AND prop_Field = '" . $sField . "'"; + $sSQL = "UPDATE groupprop_master SET prop_ID = '".($iPropID + 1)."' WHERE grp_ID = '".$iGroupID."' AND prop_Field = '".$sField."'"; RunQuery($sSQL); break; // Delete a field from the form case 'delete': // Check if this field is a custom list type. If so, the list needs to be deleted from list_lst. - $sSQL = "SELECT type_ID,prop_Special FROM groupprop_master WHERE grp_ID = '" . $iGroupID . "' AND prop_Field = '" . $sField . "'"; + $sSQL = "SELECT type_ID,prop_Special FROM groupprop_master WHERE grp_ID = '".$iGroupID."' AND prop_Field = '".$sField."'"; $rsTemp = RunQuery($sSQL); $aTemp = mysqli_fetch_array($rsTemp); if ($aTemp[0] == 12) { @@ -67,20 +67,20 @@ RunQuery($sSQL); } - $sSQL = 'ALTER TABLE `groupprop_' . $iGroupID . '` DROP `' . $sField . '` ;'; + $sSQL = 'ALTER TABLE `groupprop_'.$iGroupID.'` DROP `'.$sField.'` ;'; RunQuery($sSQL); - $sSQL = "DELETE FROM groupprop_master WHERE grp_ID = '" . $iGroupID . "' AND prop_ID = '" . $iPropID . "'"; + $sSQL = "DELETE FROM groupprop_master WHERE grp_ID = '".$iGroupID."' AND prop_ID = '".$iPropID."'"; RunQuery($sSQL); - $sSQL = 'SELECT * FROM groupprop_master WHERE grp_ID = ' . $iGroupID; + $sSQL = 'SELECT * FROM groupprop_master WHERE grp_ID = '.$iGroupID; $rsPropList = RunQuery($sSQL); $numRows = mysqli_num_rows($rsPropList); // Shift the remaining rows up by one, unless we've just deleted the only row if ($numRows != 0) { for ($reorderRow = $iPropID + 1; $reorderRow <= $numRows + 1; $reorderRow++) { - $sSQL = "UPDATE groupprop_master SET prop_ID = '" . ($reorderRow - 1) . "' WHERE grp_ID = '" . $iGroupID . "' AND prop_ID = '" . $reorderRow . "'"; + $sSQL = "UPDATE groupprop_master SET prop_ID = '".($reorderRow - 1)."' WHERE grp_ID = '".$iGroupID."' AND prop_ID = '".$reorderRow."'"; RunQuery($sSQL); } } @@ -88,10 +88,10 @@ // If no valid action was specified, abort and return to the GroupView default: - RedirectUtils::redirect('GroupView.php?GroupID=' . $iGroupID); + RedirectUtils::redirect('GroupView.php?GroupID='.$iGroupID); break; } // Reload the Form Editor page -RedirectUtils::redirect('GroupPropsFormEditor.php?GroupID=' . $iGroupID); +RedirectUtils::redirect('GroupPropsFormEditor.php?GroupID='.$iGroupID); exit; diff --git a/src/Include/CanvassUtilities.php b/src/Include/CanvassUtilities.php index c23602d950..800941b2b1 100644 --- a/src/Include/CanvassUtilities.php +++ b/src/Include/CanvassUtilities.php @@ -11,7 +11,7 @@ function CanvassSetDefaultFY($iFYID) { - $sSQL = "UPDATE user_usr SET usr_defaultFY='" . $iFYID . "';"; + $sSQL = "UPDATE user_usr SET usr_defaultFY='".$iFYID."';"; RunQuery($sSQL); } @@ -36,7 +36,7 @@ function CanvassClearCanvasserAssignments() function CanvassGetCanvassers($groupName) { // Find the canvassers group - $sSQL = 'SELECT grp_ID AS iCanvassGroup FROM group_grp WHERE grp_Name="' . $groupName . '";'; + $sSQL = 'SELECT grp_ID AS iCanvassGroup FROM group_grp WHERE grp_Name="'.$groupName.'";'; $rsGroupData = RunQuery($sSQL); $aGroupData = mysqli_fetch_array($rsGroupData); if (mysqli_num_rows($rsGroupData) == 0) { @@ -45,7 +45,7 @@ function CanvassGetCanvassers($groupName) extract($aGroupData); // Get the canvassers from the Canvassers group - $sSQL = 'SELECT per_ID, per_FirstName, per_LastName FROM person_per, person2group2role_p2g2r WHERE per_ID = p2g2r_per_ID AND p2g2r_grp_ID = ' . $iCanvassGroup . ' ORDER BY per_LastName,per_FirstName;'; + $sSQL = 'SELECT per_ID, per_FirstName, per_LastName FROM person_per, person2group2role_p2g2r WHERE per_ID = p2g2r_per_ID AND p2g2r_grp_ID = '.$iCanvassGroup.' ORDER BY per_LastName,per_FirstName;'; $rsCanvassers = RunQuery($sSQL); $numCanvassers = mysqli_num_rows($rsCanvassers); if ($numCanvassers == 0) { @@ -72,7 +72,7 @@ function CanvassAssignCanvassers($groupName) mysqli_data_seek($rsCanvassers, 0); $aCanvasser = mysqli_fetch_array($rsCanvassers); } - $sSQL = 'UPDATE family_fam SET fam_Canvasser=' . $aCanvasser['per_ID'] . ' WHERE fam_ID= ' . $aFamily['fam_ID']; + $sSQL = 'UPDATE family_fam SET fam_Canvasser='.$aCanvasser['per_ID'].' WHERE fam_ID= '.$aFamily['fam_ID']; RunQuery($sSQL); } @@ -96,17 +96,17 @@ function CanvassAssignNonPledging($groupName, $iFYID) while ($aFamily = mysqli_fetch_array($rsFamilies)) { // Get pledges for this fiscal year, this family $sSQL = 'SELECT plg_Amount FROM pledge_plg - WHERE plg_FYID = ' . $iFYID . ' AND plg_PledgeOrPayment="Pledge" AND plg_FamID = ' . $aFamily['fam_ID'] . ' ORDER BY plg_Amount DESC'; + WHERE plg_FYID = '.$iFYID.' AND plg_PledgeOrPayment="Pledge" AND plg_FamID = '.$aFamily['fam_ID'].' ORDER BY plg_Amount DESC'; $rsPledges = RunQuery($sSQL); $pledgeCount = mysqli_num_rows($rsPledges); if ($pledgeCount == 0) { - ++$numFamilies; + $numFamilies++; if (!($aCanvasser = mysqli_fetch_array($rsCanvassers))) { mysqli_data_seek($rsCanvassers, 0); $aCanvasser = mysqli_fetch_array($rsCanvassers); } - $sSQL = 'UPDATE family_fam SET fam_Canvasser=' . $aCanvasser['per_ID'] . ' WHERE fam_ID= ' . $aFamily['fam_ID']; + $sSQL = 'UPDATE family_fam SET fam_Canvasser='.$aCanvasser['per_ID'].' WHERE fam_ID= '.$aFamily['fam_ID']; RunQuery($sSQL); } } diff --git a/src/Include/GetGroupArray.php b/src/Include/GetGroupArray.php index becbece9bd..173705ebf5 100644 --- a/src/Include/GetGroupArray.php +++ b/src/Include/GetGroupArray.php @@ -15,18 +15,18 @@ function GetGroupArray($iGroupID) FROM record2property_r2p LEFT JOIN property_pro ON pro_ID = r2p_pro_ID LEFT JOIN propertytype_prt ON propertytype_prt.prt_ID = property_pro.pro_prt_ID - WHERE pro_Class = 'g' AND r2p_record_ID = " . $iGroupID . + WHERE pro_Class = 'g' AND r2p_record_ID = ".$iGroupID. ' ORDER BY prt_Name, pro_Name'; $rsAssignedProperties = RunQuery($sSQL); // Get the group's role list ID - $sSQL = 'SELECT grp_RoleListID,grp_hasSpecialProps FROM group_grp WHERE grp_ID =' . $iGroupID; + $sSQL = 'SELECT grp_RoleListID,grp_hasSpecialProps FROM group_grp WHERE grp_ID ='.$iGroupID; $aTemp = mysqli_fetch_array(RunQuery($sSQL)); $iRoleListID = $aTemp[0]; $bHasSpecialProps = ($aTemp[1] == 'true'); // Get the roles - $sSQL = 'SELECT * FROM list_lst WHERE lst_ID = ' . $iRoleListID . ' ORDER BY lst_OptionSequence'; + $sSQL = 'SELECT * FROM list_lst WHERE lst_ID = '.$iRoleListID.' ORDER BY lst_OptionSequence'; $rsRoles = RunQuery($sSQL); $numRoles = mysqli_num_rows($rsRoles); @@ -41,7 +41,7 @@ function GetGroupArray($iGroupID) LEFT JOIN list_lst ON p2g2r_rle_ID = lst_OptionID AND lst_ID = $iRoleListID LEFT JOIN group_grp ON grp_ID = p2g2r_grp_ID LEFT JOIN family_fam ON per_fam_ID = family_fam.fam_ID - WHERE p2g2r_grp_ID = " . $iGroupID . ' ORDER BY per_LastName, per_FirstName'; + WHERE p2g2r_grp_ID = ".$iGroupID.' ORDER BY per_LastName, per_FirstName'; $rsGroupMembers = RunQuery($sSQL); $row = 0; while ($aGroupMember = mysqli_fetch_array($rsGroupMembers)) { diff --git a/src/Include/Header-Security.php b/src/Include/Header-Security.php index 7c1faaf2ae..2ab26d6826 100644 --- a/src/Include/Header-Security.php +++ b/src/Include/Header-Security.php @@ -6,12 +6,12 @@ * and open the template in the editor. */ -use ChurchCRM\dto\SystemURLs; use ChurchCRM\dto\SystemConfig; +use ChurchCRM\dto\SystemURLs; $csp = [ "default-src 'self'", - "script-src 'unsafe-eval' 'self' 'nonce-" . SystemURLs::getCSPNonce() . "' browser-update.org", + "script-src 'unsafe-eval' 'self' 'nonce-".SystemURLs::getCSPNonce()."' browser-update.org", "object-src 'none'", "style-src 'self' 'unsafe-inline' fonts.googleapis.com", "img-src 'self' data:", @@ -19,10 +19,10 @@ "frame-src 'self'", "font-src 'self' fonts.gstatic.com", "connect-src 'self'", - "report-uri " . SystemURLs::getRootPath() . "/api/system/background/csp-report" + 'report-uri '.SystemURLs::getRootPath().'/api/system/background/csp-report', ]; -if (SystemConfig::getBooleanValue("bHSTSEnable")) { +if (SystemConfig::getBooleanValue('bHSTSEnable')) { header('Strict-Transport-Security: max-age=31536000; includeSubDomains'); } header('X-Frame-Options: SAMEORIGIN'); -header("Content-Security-Policy-Report-Only:" . join(";", $csp)); +header('Content-Security-Policy-Report-Only:'.join(';', $csp)); diff --git a/src/Include/LabelFunctions.php b/src/Include/LabelFunctions.php index 4ba5a17568..c0c1116c58 100644 --- a/src/Include/LabelFunctions.php +++ b/src/Include/LabelFunctions.php @@ -21,7 +21,7 @@ function FontSelect($fieldname) { $sFPDF_PATH = 'vendor/setasign/fpdf'; - $d = scandir($sFPDF_PATH . '/font/', SCANDIR_SORT_DESCENDING); + $d = scandir($sFPDF_PATH.'/font/', SCANDIR_SORT_DESCENDING); $fontnames = []; $family = ' '; foreach ($d as $entry) { @@ -40,7 +40,7 @@ function FontSelect($fieldname) sort($fontnames); echo ''; - echo '' . gettext('Font') . ':'; + echo ''.gettext('Font').':'; echo ''; echo "'; echo ''; @@ -59,7 +59,7 @@ function FontSizeSelect($fieldname) { $sizes = ['default', 6, 7, 8, 9, 10, 11, 12, 14, 16, 18]; echo ''; - echo ' ' . gettext('Font Size') . ':'; + echo ' '.gettext('Font Size').':'; echo ''; echo "'; echo ''; @@ -78,7 +78,7 @@ function LabelSelect($fieldname) { $labels = ['Tractor', '5160', '5161', '5162', '5163', '5164', '8600', 'L7163']; echo ''; - echo '' . gettext('Label Type') . ':'; + echo ''.gettext('Label Type').':'; echo ''; echo "'; echo ''; @@ -95,7 +95,7 @@ function LabelSelect($fieldname) function LabelGroupSelect($fieldname) { - echo '' . gettext('Label Grouping') . ''; + echo ''.gettext('Label Grouping').''; echo ''; echo "' . gettext('All Individuals') . '
'; + echo '>'.gettext('All Individuals').'
'; echo "' . gettext('Grouped by Family') . '
'; + echo '>'.gettext('Grouped by Family').'
'; } function ToParentsOfCheckBox($fieldname) { - echo '' . gettext('To the parents of') . ':'; + echo ''.gettext('To the parents of').':'; echo ''; echo " - ' . gettext('Start Row') . ': + '.gettext('Start Row').': - ' . gettext('Start Column') . ': + '.gettext('Start Column').': @@ -150,7 +150,7 @@ function IgnoreIncompleteAddresses() { echo ' - ' . gettext('Ignore Incomplete
Addresses') . ': + '.gettext('Ignore Incomplete
Addresses').': @@ -162,7 +162,7 @@ function LabelFileType() { echo ' - ' . gettext('File Type') . ': + '.gettext('File Type').':
'; -echo ' ' . gettext('Quiet Presort') . ''; +echo ' '.gettext('Quiet Presort').''; echo ' '; echo '