Skip to content

Instantly share code, notes, and snippets.

@thesandybridge
Last active December 9, 2022 21:45
Show Gist options
  • Save thesandybridge/64ec2abac70907d4cea71f2a1f5f5ef4 to your computer and use it in GitHub Desktop.
Save thesandybridge/64ec2abac70907d4cea71f2a1f5f5ef4 to your computer and use it in GitHub Desktop.
Code Examples
import { useBlockProps, InnerBlocks, RichText, useInnerBlocksProps } from '@wordpress/block-editor'
import { useState, useEffect } from 'react'
import { select, useDispatch, useSelect } from '@wordpress/data'
import { usePrevious } from '@wordpress/compose'
import {
createBlock,
} from '@wordpress/blocks';
import { Tooltip, Icon } from '@wordpress/components'
import { __ } from '@wordpress/i18n'
import './editor.scss'
const ALLOWED_BLOCKS = ['nrtc-blocks/tab']
export default function Edit(
{
attributes,
setAttributes,
isSelected,
clientId,
}) {
const { tabNavigation, tabPanel } = attributes
const { insertBlocks, removeBlock } = useDispatch('core/block-editor')
const { getBlocksByClientId } = useSelect('core/block-editor')
const [selectedTab, setSelectedTab] = useState(0)
const addTabs = () => {
setAttributes({
tabNavigation: [...tabNavigation, { title: `Tab ${tabNavigation.length + 1}` }]
})
setSelectedTab(tabNavigation.length)
insertBlocks(
createBlock(
'nrtc-blocks/tab',
{
tabId: tabNavigation.length,
active: true
}
), undefined, clientId
)
setAttributes({ activeTab: tabNavigation.length })
}
const removeTabs = () => {
setAttributes({
tabNavigation: [
...tabNavigation.slice(0, selectedTab),
...tabNavigation.slice(selectedTab + 1)
]
})
removeBlock(getBlocksByClientId(clientId)[0].innerBlocks[selectedTab].clientId)
}
const updateAttributes = (type, value) => {
const newTabNavigation = [...tabNavigation]
newTabNavigation[selectedTab][type] = value
setAttributes({ tabNavigation: newTabNavigation })
}
return (
<div {...useBlockProps()}>
<div className='tabNavigation'>
<ul>
{tabNavigation.map((tab, index) =>
<li
data-id={index} className={`tab ${selectedTab === index ? 'active' : ''}`}
onClick={() => {
setSelectedTab(index)
setAttributes({ activeTab: index })
}}
aria-label={__('Edit Tab')}>
<button data-id={index} role="Tab Button" className={`tabButton ${selectedTab === index ? 'active' : ''}`} aria-label={__(`${tab.title} tab`)}>
<RichText
key={index}
tagName="span"
value={tab.title}
onChange={(title) => updateAttributes('title', title)}
placeholder={tab.title} />
{selectedTab === index && isSelected && (
<Tooltip text={__('Remove tab')}>
<button
aria-label={__('Remove Tabs')}
className="removeTabBtn"
onClick={removeTabs}><Icon icon="no-alt" /></button>
</Tooltip>
)}
{selectedTab === index ? (
<Icon icon={
<svg width="15" height="7" viewBox="0 0 15 7" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.50007 7L0.5 0H14.5L7.50007 7Z" fill="#D42518" />
</svg>
} />
) : (
<Icon icon={
<svg width="14" height="3" viewBox="0 0 14 3" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7 2.75012L0 2.75V0.25H14V2.75012H7Z" fill="#A6AEAF" />
</svg>
} />
)}
</button>
</li>
)}
{isSelected && (
<li className='addTabs'>
<Tooltip text={__('Add tab')}>
<button className="tabAppender" aria-label={__('Add Tabs')} onClick={addTabs}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false"><path d="M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"></path></svg>
</button>
</Tooltip>
</li>
)}
</ul>
</div>
<div className="tabPanel">
<InnerBlocks
templateLock={false}
renderAppender={false}
allowedBlocks={ALLOWED_BLOCKS}
clientId={clientId}
template={tabPanel}
/>
</div>
</div>
);
}
import { micromark } from "micromark";
import { gfm, gfmHtml } from "micromark-extension-gfm";
type Post = {
name: string;
path: string;
sha: string;
size: number;
url: string;
html_url: string;
git_url: string;
download_url: string;
type: string;
_links: object;
}
/**
* Fetch all posts from the Github API.
* @returns
*/
const getPosts = async () => {
const res = await fetch(process.env.GITHUB_ENDPOINT, {
headers: {
Authorization: `bearer ${process.env.GITHUB_TOKEN}`,
},
});
return res.json();
};
/**
* Get a post by slug from the Github API.
* @param slug string containing the slug of the post.
* @returns
*/
const getPost = async (slug: string) => {
const res = await fetch(`${process.env.GITHUB_ENDPOINT}/${slug}.md`, {
headers: {
Authorization: `bearer ${process.env.GITHUB_TOKEN}`,
},
});
return res.json();
}
/**
* Parse mardown to HTML and return the html.
* @param markdown
* @returns
*/
const markdownToHtml = async(markdown: string) => {
const result = micromark(markdown, {
extensions: [gfm()],
htmlExtensions: [gfmHtml()],
});
return result;
}
/**
* Fetch post by slug from the Github API and then convert it to html. Returns the html payload.
* @param slug string containing the slug of the post.
* @returns
*/
const getMarkdownByPost = async (slug: string) => {
const payload = await getPost(slug)
.then(async (post: Post) => {
const res = await fetch(post.download_url)
const markdown = await markdownToHtml(await res.text())
return markdown
})
return payload;
}
/**
* Fetch all posts from the Github API and then convert it to html. Returns the html payload for each post.
* @returns
*/
const getMarkdown = async () => {
const posts = await getPosts();
const payload = await Promise.all(posts.map(async (post: Post) => {
const res = await fetch(post.download_url);
const markdown = await markdownToHtml(await res.text())
return markdown;
}));
return payload;
}
export {getPosts, getMarkdownByPost, getMarkdown}
#!/usr/bin/env bash
#
# Deploy to wpengine git remote
#
# Required globals:
# WPE_REPO_URL
# GIT_EMAIL
# GIT_NAME
# ARTIFACT
# WPE_INSTALL_ID
# WPE_API_USER
# WPE_API_PASSWORD
source "$(dirname "$0")/common.sh"
# mandatory parameters
WPE_REPO_URL=${WPE_REPO_URL:?'WPE_REPO_URL variable missing.'}
WPE_INSTALL_ID=${WPE_INSTALL_ID:?'WPE_INSTALL_ID variable missing.'}
WPE_API_USER=${WPE_API_USER:?'WPE_API_USER variable missing.'}
WPE_API_PASSWORD=${WPE_API_PASSWORD:?'WPE_API_PASSWORD variable missing.'}
GIT_EMAIL=${GIT_EMAIL:?'GIT_EMAIL variable missing.'}
GIT_NAME=${GIT_NAME:?'GIT_NAME variable missing.'}
ARTIFACT=${ARTIFACT:?'ARTIFACT variable missing.'}
info "Running wpengine pipe..."
# copies repo ssh keys into pipe image
configure_ssh() {
info "configuring ssh keys..."
mkdir -p ~/.ssh
cp /opt/atlassian/pipelines/agent/ssh/id_rsa_tmp ~/.ssh/id_rsa
cp /opt/atlassian/pipelines/agent/ssh/known_hosts ~/.ssh/known_hosts
chmod -R go-rwx ~/.ssh/
}
configure_ssh
# pushes artifact into target remote
push_to_wpe() {
info "Deploying to to ${WPE_REPO_URL}..."
info "Configuring git..."
git config --global user.email "${GIT_EMAIL}"
git config --global user.email "${GIT_NAME}"
mkdir deploy
mv ${ARTIFACT} deploy
cd deploy
success "Artifact has been moved to deploy"
info "Unzipping artifact..."
unzip -o ${ARTIFACT}
rm -rf ${ARTIFACT}
success "Successfuly unzipped artifact!"
ls
git init
git remote add origin ${WPE_REPO_URL}
git add .
git branch -M master
git commit -m "$BITBUCKET_COMMIT"
git push -uf ${WPE_REPO_URL}
}
# takes a backup of target install
backup_wpe_install() {
printf -v data -- '{"description": "Before Bitbucket deploy", "notification_emails": ["%s"]}' \
"${GIT_EMAIL}"
info "Backing up site before git push..."
STATUS=$(curl --write-out "%{http_code}\n" -X POST "https://api.wpengineapi.com/v1/installs/${WPE_INSTALL_ID}/backups" \
-H "Content-Type: application/json" \
-d "$data" \
-u ${WPE_API_USER}:${WPE_API_PASSWORD} \
--output output.txt --silent)
if [ "$STATUS" == 202 ]
then
success "$STATUS: Successfuly created a backup!"
push_to_wpe
else
fail "$STATUS: failed to created a backup!"
fi
}
backup_wpe_install
success "Successfuly synced files with wpengine!"
<?php
/**
* @package GrafikBasePlugin
*/
namespace Lib\Services\Components;
use Exception;
use Lib\Services\ServicesBase;
use Lib\Services\Service;
use Timber;
/**
* Jira class used to register settings to the jira page
* @package Lib\Services\Components
*/
class Jira extends ServicesBase implements Service {
public function register()
{
$this->create_table();
add_action('template_redirect', [$this, '_custom_redirect']);
add_filter( 'timber/twig', [$this, 'jira_twig_extensions'] );
}
/**
* Registers functions to be used in twig templates
* @param mixed $timber
* @return mixed
*/
public function jira_twig_extensions($timber) {
$timber->addFunction(
new Timber\Twig_Function( 'fetch_bad_links', [$this, 'fetch_bad_links'] ),
);
return $timber;
}
/**
* Create table if it doesn't exist.
* @return void
*/
public function create_table() {
global $wpdb;
$tablename = $wpdb->prefix . "bad_link_lookup";
$this->notified_lookup($tablename);
}
/**
* function to handle sending 404 reports to jira
* @return void
*/
public function _custom_redirect() {
global $wp;
global $wp_query;
global $wpdb;
if ( $wp_query->is_404() )
{
$tablename = $wpdb->prefix . "bad_link_lookup";
// Query args
$url = home_url( add_query_arg( array(), $wp->request ) );
$referer = add_query_arg(array(), wp_get_referer());
// TODO: Need to make error log
$error = add_query_arg(array(), '');
// Fields for API method
$api_key = get_option('jira_api')['jira_api_field'] ?? '';
$account_email = get_option('jira_api')['jira_account_email'] ?? '';
$project_id = get_option('jira_api')['jira_project_id'] ?? '';
$summary = get_option('jira_api')['jira_summary'] ?? '';
$message = get_option('jira_api')['jira_custom_message_field'] ?? '';
$disable_api = isset(get_option('jira_api')['jira_disable_api']);
$body = str_replace(array("%url%", "%referer%"), array($url, $referer), $message);
if ( ! $url ) return;
if (! $this->notified_lookup( $tablename ) ) return;
// check to see if this has been added
$count = $wpdb->get_var("SELECT count(*) FROM $tablename WHERE url = '$url'");
if ( ! intval($count) < 1 ) return;
$this->new_link($url, $referer, $tablename, $wpdb);
if ( ! $disable_api ) {
if ( isset( $api_key ) ) {
$message = empty($body) ? "404 Error Caught for : $url\nReferer: $referer" : $body;
$this->createIssue(
$account_email,
$api_key,
json_encode($project_id),
json_encode($summary),
json_encode($message)
);
}
}
}
}
/**
* Creates a table in the database
* @param mixed $tablename
* @return bool
*/
public function notified_lookup($tablename) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$main_sql_create = "CREATE TABLE $tablename(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
url VARCHAR(255) NOT NULL,
refer VARCHAR(255) NOT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE = InnoDB";
return maybe_create_table( $tablename, $main_sql_create );
}
/**
* Insert data into database
* @param mixed $url
* @param mixed $referer
* @param mixed $tablename
* @param mixed $wpdb
* @return mixed
*/
public function new_link($url, $referer, $tablename, $wpdb) {
return $wpdb->query(
$wpdb->prepare("INSERT INTO $tablename( url, refer ) VALUES ( %s, %s )", $url, $referer)
);
}
/**
* Used to return a list of entries
* @return mixed
* @throws Exception
*/
public function fetch_bad_links() {
global $wpdb;
$tablename = $wpdb->prefix . "bad_link_lookup";
$query = $wpdb->prepare( "SHOW TABLES LIKE %s", $tablename );
if ( $wpdb->get_var( $query ) == $tablename ) {
$count = $wpdb->get_var("SELECT count(*) FROM $tablename");
if ( !$count < 1 ) {
$results = $wpdb->get_results(
"SELECT *
FROM $tablename
ORDER BY id desc
LIMIT 25" ) or die();
return $results;
} else {
echo "<span class='window-error'>There are no results to display.</span>";
}
} else {
Throw new Exception("Table $tablename does not exist");
}
}
/**
* Sends JSON payload to Jira to create an issue.
* @param mixed $email
* @param mixed $key
* @param mixed $project
* @param mixed $summary
* @param mixed $message
* @return void
*/
public function createIssue($email, $key, $project, $summary, $message) {
$url = "https://2120.atlassian.net/rest/api/2/issue/";
$apiKey = base64_encode("{$email}:{$key}");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Accept: application/json",
"Authorization: Basic {$apiKey}",
"Content-Type: application/json",
"X-Atlassian-Token: nocheck"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = <<<DATA
{
"fields": {
"project":
{
"key": $project
},
"summary": $summary,
"description": $message,
"issuetype": {
"name": "Bug"
}
}
}
DATA;
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_exec($curl);
curl_close($curl);
// var_dump($resp);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\State;
use App\StudentDetail;
use App\AddressDetail;
use App\FormerSchool;
use App\GuardianDetail;
use App\GuardianInformation;
use App\GuardianStatement;
use App\PIMS_verification;
use App\ContactSheet;
use App\UsersStudents;
use App\UsersOtherIncome;
use App\UsersAlimony;
use App\UsersSocialSecurity;
use App\UserEarningFromWork;
use App\Enrolldate;
use App\Grade;
use App\User;
use App\Race;
use App\EarningFromWork;
use App\Alimony;
use App\SocitySecurity;
use App\OtherIncome;
use App\LunchForm;
use App\AnnualIncome;
use App\FormList;
use App\SchoolDistrict;
use App\AnnualSalaryRange;
use App\County;
use App\Student;
use Validator;
use Illuminate\Support\Facades\Auth;
use Mail;
class EnrollmentController extends Controller
{
public $user_id;
public function __construct()
{
$this->middleware('auth');
$this->middleware('useraccess');
//$this->middleware('enrollform');
$this->middleware(function ($request, $next) {
$this->user_id = Auth::id();
$this->data['form_list'] = FormList::all();
return $next($request);
});
}
public function index($encode_id)
{
$this->data['states'] = State::where('id', '!=', 52)->orderBy('abbr')->get();
$this->data['county'] = County::all();
$this->data['previous_grade'] = Grade::where('id', '>', 6)->where('id', '<', 13)->get();
$this->data['step_no'] = 1;
$getMonth = [];
foreach (range(1, 12) as $m) {
$getMonth[] = date('F', mktime(0, 0, 0, $m, 1));
}
$this->data['monthlist'] = $getMonth;
$student_id = decodeStudentId($encode_id);
$data = StudentDetail::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
$this->data['detail'] = $data;
$this->data['edit'] = true;
return view('enrollments.studentInfo', $this->data);
} else {
$this->data['edit'] = false;
return view('enrollments.studentInfo', $this->data);
}
}
/*
* Store Student information
*/
public function store(Request $request, $id = null)
{
/**
* @todo this is is not catching all of the errors, need to make sure the logic here is matching what is happening on the front end
*/
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'address' => 'required',
'city' => 'required',
'state' => 'required',
'zip_code' => 'required',
]);
if ($validator->fails()) {
return redirect('studentInformation/' . $request->student_id)->withErrors($validator->errors());
}
$datadate = \App\Enrolldate::where('is_active_currently', '1')->first();
$dob = $request->year . '/' . $request->month . '/' . $request->date;
if( ( $datadate->start_date == null ) || ( $datadate->start_date == "" ) || ( $datadate->end_date == null ) || ( $datadate->end_date == "" ) ) {
if(date('m') < 06 ){
$enroll_startdate = (date('Y')-1) . '-07-01' ;
$enroll_enddate = date('Y') . '-06-30' ;
}else{
$enroll_startdate = date('Y') . '-07-01' ;
$enroll_enddate = (date('Y')+1) . '-06-30' ;
}
}
else {
$enroll_startdate = $datadate->start_date;
$enroll_enddate = $datadate->end_date;
}
$birth_date = date('Y-m-d', strtotime($dob));
$student_id = decodeStudentId($request->student_id);
$data = StudentDetail::where('user_id', $this->user_id)->where('archive_status', '=', '0')->where('student_id', $student_id)->first();
if ($data != null) {
// edit
$student = StudentDetail::where('archive_status', '=', '0')->find($id);
} else {
// add
$student = new StudentDetail();
}
$student->user_id = Auth::id();
$student->student_id = $student_id;
$student->first_name = $request->first_name;
$student->last_name = $request->last_name;
$student->middle_name = $request->middle_name;
$student->perferred_name = $request->perferred_name;
$student->gender = $request->gender;
$student->dob = $birth_date;
$student->address = $request->address;
$student->city = $request->city;
$student->state = $request->state;
$student->zip_code = $request->zip_code;
$student->county = $request->county;
$student->phone_no = $request->phone_no;
$student->archive_status = "0";
$student->email = $request->email;
$student->enrollment_startdate = $enroll_startdate;
$student->enrollment_enddate = $enroll_enddate;
$student->grade = $request->grade;
if (!empty($request->hasMailingAddress)) {
$student->maddress = $request->mailing_address;
$student->mcity = $request->mailing_city;
$student->mstate = $request->mailing_state;
$student->mzip_code = $request->mailing_zip_code;
$student->mcounty = $request->mailing_county;
} else {
// not checked or unchecked since last request clear out
$student->maddress = null;
$student->mcity = null;
$student->mstate = null;
$student->mzip_code = null;
$student->mcounty = null;
}
$student->save();
if ($id == null) {
$total_student = getStudentCount();
$user = new Student();
$user->user_id = Auth::id();
$user->student_id = $total_student + 1;
$user->current_step = 1;
$user->enroll_type = 1;
$user->save();
$user_id = Auth::id();
$count = User::find($user_id);
$student_count = $count->student_count + 1;
$count->student_count = $student_count;
$count->save();
// Email Send
$email_list = \App\EmailTemplate::find(2);
$email_text = $email_list->email_text;
$email_text = str_replace('{{student_firstname}}', $request->first_name, $email_text);
$email_text = str_replace('{{student_lastname}}', $request->last_name, $email_text);
$email_text = str_replace('{{student_grade}}', $request->grade, $email_text);
$list = explode(',', $email_list->email);
foreach ($list as $data) {
$email = trim($data);
$msg['text'] = $email_text;
$subject = "Student Registration";
$this->sendEmail($email, $msg, $subject);
}
}
if ($request->page_reset == 1) {
return redirect('studentInformation/' . $request->student_id)->with('message', 'Your progress has been saved successfully.');
} else {
return redirect('addressInformation/' . $request->student_id);
}
}
public function sendEmail($email, $detail, $subject)
{
if ($email) {
Mail::send('emails.email', $detail, function ($message) use ($email, $subject) {
$message->to($email)->subject($subject)
->replyTo('info@achievementcharter.com', 'AHCCS Online'); // Adding Reply-To Email Address As Per Task Created By Client : https://2120.atlassian.net/browse/AHCCS001-38
});
if (Mail::failures()) {
return false;
} else {
return true;
}
} else {
return true;
}
}
/*
* Address form
*/
public function addressinfo($encoded_id)
{
$student_id = decodeStudentId($encoded_id);
$this->data['states'] = State::where('id', '!=', 52)->orderBy('abbr')->get();
$this->data['former_school'] = FormerSchool::all();
$this->data['school_district'] = SchoolDistrict::orderBy('school_type')->get();
$this->data['grade'] = Grade::all();
$this->data['step_no'] = 2;
$data = AddressDetail::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
$this->data['detail'] = $data;
$this->data['edit'] = true;
return view('enrollments.addressInfo', $this->data);
} else {
$this->data['edit'] = false;
return view('enrollments.addressInfo', $this->data);
}
}
/*
* Store address information
*/
public function storeaddressinfo(Request $request, $id = null)
{
//dd($request->all());
$validator = Validator::make($request->all(), [
'district_residence' => 'required',
]);
if ($validator->fails()) {
return redirect('addressInformation')->withErrors($validator->errors());
}
$student_id = decodeStudentId($request->student_id);
$data = AddressDetail::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
// edit
$addressDetail = AddressDetail::find($id);
} else {
// add
$addressDetail = new AddressDetail();
}
$addressDetail->user_id = Auth::id();
$addressDetail->student_id = $student_id;
$addressDetail->district_residence = $request->district_residence;
$addressDetail->former_school_type = $request->former_school_type;
$addressDetail->former_school_name = $request->former_school_name;
$addressDetail->previous_grade = $request->previous_grade;
$addressDetail->IEP_service = (isset($request->IEP_service) ? $request->IEP_service : NULL);
$addressDetail->IEP_record = (isset($request->IEP_record) ? $request->IEP_record : NULL);
$addressDetail->save();
if ($id == null) {
$student = Student::where('user_id', Auth::id())->where('student_id', $student_id)->first();
$student->current_step = 2;
$student->save();
}
if ($request->page_reset == 1) {
return redirect('addressInformation/' . $request->student_id)->with('message', 'Your progress has been saved successfully.');;
} else {
return redirect('guardianInformation/' . $request->student_id);
}
}
/*
* Guardian Detail Form
*/
public function guardianinfo($encoded_id)
{
$this->data['states'] = State::where('id', '!=', 52)->orderBy('abbr')->get();
$this->data['guardianInfo'] = GuardianInformation::all();
$this->data['step_no'] = 3;
$student_id = decodeStudentId($encoded_id);
$data = GuardianDetail::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
$this->data['detail'] = $data;
$this->data['edit'] = true;
return view('enrollments.guardianInfo', $this->data);
} else {
$this->data['edit'] = false;
return view('enrollments.guardianInfo', $this->data);
}
}
/*
* Store Guardian information
*/
public function storeguardianinfo(Request $request, $id = null)
{
$validator = Validator::make($request->all(), [
'live_with' => 'required'
]);
if ($validator->fails()) {
return redirect('guardianInformation')->withErrors($validator->errors());
}
$this->data['states'] = State::where('id', '!=', 52)->orderBy('abbr')->get();
$this->data['guardianInfo'] = GuardianInformation::all();
$student_id = decodeStudentId($request->student_id);
$data = GuardianDetail::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
//edit section
$detail = GuardianDetail::find($id);
} else {
//add section
$detail = new GuardianDetail();
}
$detail->user_id = Auth::id();
$detail->student_id = $student_id;
$detail->live_with = $request->live_with;
$detail->court_instruction = (isset($request->court_instruction) ? $request->court_instruction : NULL);
$detail->father_name = (isset($request->father_name) ? $request->father_name : NULL);
$detail->father_address = (isset($request->father_address) ? $request->father_address : NULL);
$detail->father_city = (isset($request->father_city) ? $request->father_city : NULL);
$detail->father_state = (isset($request->father_state) ? $request->father_state : NULL);
$detail->father_zip_code = (isset($request->father_zip_code) ? $request->father_zip_code : NULL);
$detail->father_phone_no = (isset($request->father_phone_no) ? $request->father_phone_no : NULL);
$detail->father_work_no = (isset($request->father_work_no) ? $request->father_work_no : NULL);
$detail->mother_name = (isset($request->mother_name) ? $request->mother_name : NULL);
$detail->mother_address = (isset($request->mother_address) ? $request->mother_address : NULL);
$detail->mother_city = (isset($request->mother_city) ? $request->mother_city : NULL);
$detail->mother_state = (isset($request->mother_state) ? $request->mother_state : NULL);
$detail->mother_zip_code = (isset($request->mother_zip_code) ? $request->mother_zip_code : NULL);
$detail->mohter_phone_no = (isset($request->mohter_phone_no) ? $request->mohter_phone_no : NULL);
$detail->mother_work_no = (isset($request->mother_work_no) ? $request->mother_work_no : NULL);
$detail->other_adult = ($request->other_adult == 'on' ? 1 : NULL);
$detail->adult_name = (isset($request->adult_name) ? $request->adult_name : NULL);
$detail->adult_address = (isset($request->adult_address) ? $request->adult_address : NULL);
$detail->adult_city = (isset($request->adult_city) ? $request->adult_city : NULL);
$detail->adult_state = (isset($request->adult_state) ? $request->adult_state : NULL);
$detail->adult_zip_code = (isset($request->adult_zip_code) ? $request->adult_zip_code : NULL);
$detail->save();
if ($id == null) {
$student = Student::where('user_id', Auth::id())->where('student_id', $student_id)->first();
$student->current_step = 3;
$student->save();
}
if ($request->page_reset == 1) {
return redirect('guardianInformation/' . $request->student_id)->with('message', 'Your progress has been saved successfully.');;
} else {
return redirect('guardianStatement/' . $request->student_id);
}
}
/* Guardian Statement
*
*/
public function guardianStatement($encoded_id)
{
$student_id = decodeStudentId($encoded_id);
$data = GuardianStatement::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
$getMonth = [];
foreach (range(1, 12) as $m) {
$getMonth[] = date('F', mktime(0, 0, 0, $m, 1));
}
$this->data['monthlist'] = $getMonth;
$this->data['step_no'] = 4;
if ($data != null) {
$this->data['detail'] = $data;
$this->data['edit'] = true;
return view('enrollments.guardianStatement', $this->data);
} else {
$this->data['edit'] = false;
return view('enrollments.guardianStatement', $this->data);
}
}
/*
* Store Guardian statement information
*/
public function storeGuardianStatement(Request $request, $id = null)
{
$student_id = decodeStudentId($request->student_id);
$data = GuardianStatement::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
//edit section
$statement = GuardianStatement::find($id);
} else {
//add section
$statement = new GuardianStatement();
}
if ($request->suspension == 1) {
$start_date = $request->start_year . '/' . $request->start_month . '/' . $request->start_day;
$start_suspension_date = date('Y-m-d', strtotime($start_date));
$end_date = $request->end_year . '/' . $request->end_month . '/' . $request->end_day;
$end_suspension_date = date('Y-m-d', strtotime($end_date));
} else {
$start_suspension_date = NULL;
$end_suspension_date = NULL;
}
$statement->user_id = Auth::id();
$statement->student_id = $student_id;
$statement->suspension = $request->suspension;
$statement->suspension_start_date = $start_suspension_date;
$statement->suspension_end_date = $end_suspension_date;
$statement->address_change = (isset($request->address_change) ? '1' : '0');
$statement->school_record = (isset($request->school_record) ? '1' : '0');
$statement->state_testing = (isset($request->state_testing) ? '1' : '0');
$statement->launchpad_course = $request->launchpad_course;
$statement->save();
if ($id == null) {
$student = Student::where('user_id', Auth::id())->where('student_id', $student_id)->first();
$student->current_step = 4;
$student->save();
}
if ($request->page_reset == 1) {
return redirect('guardianStatement/' . $request->student_id)->with('message', 'Your progress has been saved successfully.');;
} else {
return redirect('verification/' . $request->student_id);
}
}
/*
* PIMS verification
*/
public function verification($encoded_id)
{
$student_id = decodeStudentId($encoded_id);
$data = PIMS_verification::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
$yenroll = \App\Enrolldate::where('is_active_currently', '1')->first();
$this->data['race'] = Race::all();
$this->data['states'] = State::all();
$this->data['step_no'] = 5;
$this->data['start_date'] = $yenroll->start_date;
$this->data['end_date'] = $yenroll->end_date;
if ($data != null) {
$this->data['detail'] = $data;
$this->data['edit'] = true;
return view('enrollments.pimsVerification', $this->data);
} else {
$this->data['edit'] = false;
return view('enrollments.pimsVerification', $this->data);
}
}
/*
* Store and Update PIMS verification form
*/
public function storeVerification(Request $request, $id = null)
{
$validator = Validator::make($request->all(), [
'state' => 'required',
'ethnicity' => 'required',
'race' => 'required',
]);
if ($validator->fails()) {
return redirect('verification')->withErrors($validator->errors());
}
$student_id = decodeStudentId($request->student_id);
$data = PIMS_verification::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
//edit section
$verification = PIMS_verification::find($id);
} else {
//add section
$verification = new PIMS_verification();
}
$verification->user_id = Auth::id();
$verification->student_id = $student_id;
$verification->education_service = $request->education_service;
$verification->challenge_type = isset($request->challenge_type) ? $request->challenge_type : NULL;
$verification->medical_accommodations = $request->medical_accommodations;
$verification->medical_need = isset($request->medical_need) ? $request->medical_need : NULL;
$verification->learning_program = $request->learning_program;
$verification->foreign_exchange = $request->foreign_exchange;
$verification->meal_plan = $request->meal_plan;
$verification->grade_year = $request->grade_year;
$verification->current_grade = $request->current_grade;
$verification->national_guard = $request->national_guard;
$verification->ethnicity = $request->ethnicity;
$verification->race = $request->race;
$verification->state = $request->state;
$verification->pa_year = $request->pa_year;
$verification->save();
if ($id == null) {
$student = Student::where('user_id', Auth::id())->where('student_id', $student_id)->first();
$student->current_step = 5;
$student->save();
}
if ($request->page_reset == 1) {
return redirect('verification/' . $request->student_id)->with('message', 'Your progress has been saved successfully.');;
} else {
return redirect('contactSheet/' . $request->student_id);
}
}
/*
* Contact Sheet
*/
public function contactsheet($encoded_id)
{
$student_id = decodeStudentId($encoded_id);
$data = ContactSheet::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
$this->data['step_no'] = 6;
if ($data != null) {
$this->data['detail'] = $data;
$this->data['edit'] = true;
return view('enrollments.contactSheet', $this->data);
} else {
$this->data['edit'] = false;
return view('enrollments.contactSheet', $this->data);
}
}
/*
* Store and Update Contact Sheet
*/
public function storeContactSheet(Request $request, $id = null)
{
$student_id = decodeStudentId($request->student_id);
$data = ContactSheet::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
//edit section
$contact = ContactSheet::find($id);
} else {
//add section
$contact = new ContactSheet();
}
$contact->user_id = Auth::id();
$contact->student_id = $student_id;
$contact->classroom_name = $request->classroom_name;
$contact->enrolled = $request->enrolled;
$contact->enrolled_year = $request->enrolled_year;
$contact->siblings = $request->siblings;
$contact->siblings_guardian_email = $request->siblings_guardian_email;
$contact->guardian_email = $request->guardian_email;
$contact->guardian_phone_no = $request->guardian_phone_no;
$contact->guardian_employer = $request->guardian_employer;
$contact->guardian_work_no = $request->guardian_work_no;
$contact->guardian_work_email = $request->guardian_work_email;
$contact->contact_type = $request->contact_type;
$contact->contact_language = $request->contact_language;
$contact->contact1_name = $request->contact1_name;
$contact->contact1_email = $request->contact1_email;
$contact->contact1_relation = $request->contact1_relation;
$contact->contact1_phone_no = $request->contact1_phone_no;
$contact->contact2_name = $request->contact2_name;
$contact->contact2_email = $request->contact2_email;
$contact->contact2_relation = $request->contact2_relation;
$contact->contact2_phone_no = $request->contact2_phone_no;
$contact->save();
if ($id == null) {
$student = Student::where('user_id', Auth::id())->where('student_id', $student_id)->first();
$student->current_step = 6;
$student->save();
}
if ($request->page_reset == 1) {
return redirect('contactSheet/' . $request->student_id)->with('message', 'Your progress has been saved successfully.');;
} else {
return redirect('lunchForm/' . $request->student_id);
}
}
/*
* Lunch Form
* */
public function lunchForm($encoded_id)
{
$getMonth = [];
foreach (range(1, 12) as $m) {
$getMonth[] = date('F', mktime(0, 0, 0, $m, 1));
}
$student_id = decodeStudentId($encoded_id);
$data = LunchForm::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
$this->data['step_no'] = 7;
$this->data['monthlist'] = $getMonth;
$this->data['earning_work'] = EarningFromWork::all();
$this->data['other_income'] = OtherIncome::all();
$this->data['alimony'] = Alimony::all();
$this->data['SocitySecurity'] = SocitySecurity::all();
$this->data['previous_grade'] = Grade::where('id', '>', 6)->where('id', '<', 13)->get();
if ($data != null) {
$this->data['detail'] = $data;
$this->data['student_info'] = UsersStudents::where('user_id', Auth::id())->where('student_id', $student_id)->get();
$this->data['user_earning'] = UserEarningFromWork::where('user_id', Auth::id())->where('student_id', $student_id)->get();
$this->data['user_other_income'] = UsersOtherIncome::where('user_id', Auth::id())->where('student_id', $student_id)->get();
$this->data['user_alimony'] = UsersAlimony::where('user_id', Auth::id())->where('student_id', $student_id)->get();
$this->data['user_security'] = UsersSocialSecurity::where('user_id', Auth::id())->where('student_id', $student_id)->get();
$this->data['user_student'] = UsersStudents::where('user_id', Auth::id())->where('student_id', $student_id)->get();
$this->data['edit'] = true;
//dd($this->data);
return view('enrollments.lunchform', $this->data);
} else {
#dd($this->data);
$this->data['edit'] = false;
return view('enrollments.lunchform', $this->data);
}
}
/* Add and Update Lunch Form
*
*/
public function storeLunchForm(Request $request, $id = null)
{
// dd($request->all());
$resetpg = 1;
$student_id = decodeStudentId($request->student_id);
$data = LunchForm::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
//dd($data);
if ($data != null) {
//edit section LunchForm
$lunch_form = LunchForm::find($id);
$detch = User::find(Auth::id());
// Detech earning
$user_earning = UserEarningFromWork::where('user_id', Auth::id())->where('student_id', $student_id)->delete();
// Detech Other income
$user_income = UsersOtherIncome::where('user_id', Auth::id())->where('student_id', $student_id)->delete();
// Detech Alimony
$user_alimony = UsersAlimony::where('user_id', Auth::id())->where('student_id', $student_id)->delete();
// Detech Security
$user_security = UsersSocialSecurity::where('user_id', Auth::id())->where('student_id', $student_id)->delete();
// Detech Student
$user_student = UsersStudents::where('user_id', Auth::id())->where('student_id', $student_id)->delete();
} else {
//add section
$lunch_form = new LunchForm();
}
// Store user information
$student = User::find(Auth::id());
$student_info = $request->student_info;
$user_student = array();
foreach ($student_info as $key => $value) {
if(((0 == $value['year'] % 4) & (0 != $value['year'] % 100) | (0 == $value['year'] % 400)) && ($value['month'] == 2 && ($value['day'] == 30 || $value['day'] == 31))){
$student->user_student()->saveMany($user_student);
$resetpg = 2;
return redirect('lunchForm/' . $request->student_id)->with('dob', 'Please Enter Correct Date Of Birth For Additional Students.');;
}
else if ($value['month'] == 2 && ($value['day'] == 29 || $value['day'] == 30 || $value['day'] == 31)){
$resetpg = 2;
$student->user_student()->saveMany($user_student);
return redirect('lunchForm/' . $request->student_id)->with('dob', 'Please Enter Correct Date Of Birth For Additional Students.');;
}
else{
$dob = $value['year'] . '/' . $value['month'] . '/' . $value['day'];
$birth_date = date('Y-m-d', strtotime($dob));
$forest_child = (isset($value['forest_child']) == 'on') ? '1' : '0';
$user_student[] = new UsersStudents(['student_name' => $value['student_name'], 'student_id' => $student_id, 'grade' => $value['grade'], 'forest_child' => $forest_child, 'dob' => $birth_date]);
$student->user_student()->saveMany($user_student);
}
}
// $student->user_student()->saveMany($user_student);
// Store earning from work
$earning_work = User::find(Auth::id());
$earning = $request->earning_work;
$user_earning = array();
if (!empty($earning)) {
foreach ($earning as $key => $value) {
$uearning = new UserEarningFromWork();
$uearning->user_id = Auth::id();
$uearning->student_id = $student_id;
$uearning->work_id = $value;
$uearning->save();
}
}
$otherincome = User::find(Auth::id());
$other_data = $request->other_income;
$user_income = array();
if (!empty($other_data)) {
foreach ($other_data as $key => $value) {
$uincome = new UsersOtherIncome();
$uincome->user_id = Auth::id();
$uincome->student_id = $student_id;
$uincome->income_id = $value;
$uincome->save();
}
}
$alomny = User::find(Auth::id());
$alomny_data = $request->alomny;
$user_alimony = array();
if (!empty($alomny_data)) {
foreach ($alomny_data as $key => $value) {
$ualimony = new UsersAlimony();
$ualimony->user_id = Auth::id();
$ualimony->student_id = $student_id;
$ualimony->alimony_id = $value;
$ualimony->save();
}
}
$security = User::find(Auth::id());
$security_data = $request->security;
$user_security = array();
if (!empty($security_data)) {
foreach ($security_data as $key => $value) {
$usecurity = new UsersSocialSecurity();
$usecurity->user_id = Auth::id();
$usecurity->student_id = $student_id;
$usecurity->social_id = $value;
$usecurity->save();
}
}
if ($id == null) {
$student_data = Student::where('user_id', Auth::id())->where('student_id', $student_id)->first();
$student_data->current_step = 7;
$student_data->save();
$lunch_form->user_id = Auth::id();
$lunch_form->lunch_form = 1;
$lunch_form->student_id = $student_id;
$lunch_form->save();
}
if ($request->page_reset == 1) {
return redirect('lunchForm/' . $request->student_id)->with('message', 'Your progress has been saved successfully.');;
} else {
return redirect('annualIncome/' . $request->student_id);
}
}
/*
* Annual Income
*/
public function annualIncome($encoded_id)
{
$student_id = decodeStudentId($encoded_id);
$data = AnnualIncome::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
$salary_range = array();
$this->data['step_no'] = 8;
if ($data != null) {
$this->data['detail'] = $data;
$salary_range = AnnualSalaryRange::where('family_range', $data->people_count)->get();
$this->data['salary_ranges'] = $salary_range;
$this->data['edit'] = true;
return view('enrollments.annualIncome', $this->data);
} else {
$this->data['edit'] = false;
$this->data['salary_range'] = $salary_range;
return view('enrollments.annualIncome', $this->data);
}
}
/* * *
* Store Annual Income
*
*/
public function storeAnnualIncome(Request $request, $id = null)
{
$student_id = decodeStudentId($request->student_id);
$data = AnnualIncome::where('user_id', $this->user_id)->where('student_id', $student_id)->first();
if ($data != null) {
//edit section
$income = AnnualIncome::find($id);
} else {
//add section
$income = new AnnualIncome();
}
$income->user_id = Auth::id();
$income->student_id = $student_id;
$income->name = $request->name;
$income->case_no = $request->case_no;
$income->people_count = $request->people_count;
$income->salary_range = $request->salary_range;
$income->save();
if ($id == null) {
$student_data = Student::where('user_id', Auth::id())->where('student_id', $student_id)->first();
$student_data->current_step = 8;
$student_data->save();
}
if ($request->page_reset == 1) {
return redirect('annualIncome/' . $request->student_id)->with('message', 'Your progress has been saved successfully.');;
} else {
return redirect('languageServey/' . $request->student_id);
}
}
}
import { useRouter } from "next/router";
import ErrorPage from "next/error";
import Head from "next/head";
import Stripe from "../components/StripesComponent/Stripe";
import styles from "../styles/Mods.module.css";
import { getPostBySlug, getAllPosts } from "../utils/api";
import markdownToHtml from "../utils/markdownToHTML";
import Image from "next/image";
import SteamSVG from "../svgs/steam";
import { PostType } from "../types/posts";
import Layout from "../components/Layout";
import MapSVG from "../svgs/map";
type Props = {
post: PostType;
};
const Mod = ({ post }: Props) => {
const router = useRouter();
if (!router.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} />;
}
return (
<Layout fullWidth={false} breadcrumbs={true} stripes={true}>
{router.isFallback ? (
<h2>Loading…</h2>
) : (
<>
<article>
<Head>
<title>
The Kingdom | {post.category}: {post.title}
</title>
<meta name="description" content={post.excerpt} />
<meta property="og:image" content={post.ogImage?.url} />
<meta property="og:type" content="object"></meta>
<meta
property="og:title"
content={`The Kingdom | ${post.category}: ${post.title}`}
key="title"
/>
<meta property="og:image:alt" content={post.excerpt} />
<meta
property="og:url"
content={process.env.VERCEL_URL + router.asPath}
/>
<meta property="og:description" content={post.excerpt} />
<meta name="twitter:card" content="summary_large_image" />
<meta property="twitter:domain" content="kingdomgaming.gg" />
<meta property="twitter:url" content={process.env.VERCEL_URL} />
<meta
name="twitter:title"
content={`The Kingdom | Mod: ${post.title}`}
/>
<meta name="twitter:description" content={post.excerpt} />
<meta name="twitter:image" content={post.ogImage?.url} />
</Head>
<section className={styles.modBody}>
<div className="inner-content">
{post.trailer && (
<iframe
className={styles.trailer}
width="100%"
height="auto"
src={post.trailer}
title={`${post.title} trailer`}
frameBorder="0"
allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
></iframe>
)}
<div className={styles.modMeta}>
<h1>{post.title}</h1>
<div className={styles.modSocials}>
{post.roadmap && (
<a
className="linked-svg"
href={post.roadmap}
title={`${post.title} Roadmap`}
target="_blank"
aria-label={`${post.title} Roadmap`}
rel="noreferrer noopener"
>
<MapSVG />
</a>
)}
{post.steamLink && (
<a
className="linked-svg"
href={post.steamLink}
title={`${post.title} on Steam Workshop`}
target="_blank"
aria-label={`${post.title} on Steam Workshop`}
rel="noreferrer noopener"
>
<SteamSVG />
</a>
)}
</div>
</div>
<Stripe height={4} amount={2} />
<div dangerouslySetInnerHTML={{ __html: post.content }} />
{post.coverImage && (
<div className={styles.featuredImage}>
<Image
src={post.coverImage}
alt={post.title}
layout="fill"
objectFit="cover"
/>
</div>
)}
</div>
</section>
</article>
</>
)}
</Layout>
);
};
type Params = {
params: {
slug: string;
};
};
export async function getStaticProps({ params }: Params) {
const post = getPostBySlug(params.slug, [
"title",
"date",
"slug",
"author",
"excerpt",
"content",
"ogImage",
"coverImage",
"steamLink",
"trailer",
"category",
"roadmap",
]);
const content = await markdownToHtml(post.content || "");
return {
props: {
post: {
...post,
content,
},
},
};
}
export async function getStaticPaths() {
const posts = getAllPosts(["slug"]);
return {
paths: posts.map((post) => {
return {
params: {
slug: post.slug,
},
};
}),
fallback: false,
};
}
export default Mod;
use home_config::HomeConfig;
use std::str;
use regex::Regex;
use serde::{Deserialize, Serialize};
use dialoguer::Input;
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct Data {
pub wpengine_user_id: String,
pub wpengine_password: String,
pub wpengine_api: String
}
/// This function will prompt the user for their WPEngine API credentials
/**
- Stores wpengine API username and password in config file.
- $HOME/.config/wpe/wpeconfig.toml
*/
fn set_config(username: String, token: String) {
let config = HomeConfig::with_config_dir("wpe", "wpeconfig.toml");
let data: Data = Data {
wpengine_user_id: username,
wpengine_password: token,
wpengine_api: String::from("https://api.wpengineapi.com/v1")
};
config.save_toml(&data).unwrap();
}
/// Check if username and password are stored in config file.
fn authenticated() -> bool {
let config = HomeConfig::with_config_dir("wpe", "wpeconfig.toml");
let file = HomeConfig::path(&config);
// Check if config file exists.
if file.exists() {
let toml = config.toml::<Data>().unwrap();
let re = Regex::new(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$").unwrap();
// check if username matches UUID format
if re.is_match(&toml.wpengine_user_id) {
true
} else {
false
}
} else {
false
}
}
/// Get username and password from config file.
pub fn get_config() -> Data {
let config = HomeConfig::with_config_dir("wpe", "wpeconfig.toml");
let toml = config.toml::<Data>().unwrap();
toml
}
/// Reset the config file. This should be used if you change your API token or for debugging.
pub fn reset() {
let config = HomeConfig::with_config_dir("wpe", "wpeconfig.toml");
let file = HomeConfig::path(&config);
if file.exists() {
std::fs::remove_file(file).unwrap();
}
}
/// Handles the cli for the authentication.
pub fn set_auth() {
println!("Authenticate with wpengine.");
let username: String = Input::new()
.with_prompt("Enter API Username")
.interact()
.unwrap();
let token: String = Input::new()
.with_prompt("Enter API Password")
.interact()
.unwrap();
set_config(username, token);
}
/// Handles user authentication.
pub fn init() {
if !authenticated() {
set_auth();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment