middleware('auth'); } private function max_message_length($numbers) { $max_name_length = 0; foreach($numbers as $n) { if(strlen($n->name) > $max_name_length) { $max_name_length = strlen($n->name); } } return 160 - $max_name_length - 1; } public function index() { $this->authorize('admin'); $numbers = PhoneNumber::orderBy('name')->get(); $maxlen = $this->max_message_length($numbers); return view('sms', [ 'numbers' => $numbers, 'maxlen' => $maxlen ]); } public function save(Request $request) { $this->authorize('admin'); if(preg_match_all('/(.+)\s+([0-9\-]+)/', $request->input('input'), $matches)) { $contacts = []; $errors = []; foreach($matches[1] as $i=>$name) { if(preg_match('/^1?(\d{3})-?(\d{3})-?(\d{4})$/', $matches[2][$i], $pm)) { $contacts[] = [trim($name), $pm[1].'-'.$pm[2].'-'.$pm[3]]; } else { $errors[] = $matches[0][$i]; } } if(count($errors)) { $request->session()->flash('status', 'danger'); $request->session()->flash('status-message', 'There was a problem with some of your entries. No numbers were changed. The lines below had errors:
'.implode('
', array_map('htmlspecialchars', $errors))); } else { DB::table('phone_numbers')->delete(); foreach($contacts as $c) { $p = new PhoneNumber; $p->name = $c[0]; $p->phone = $c[1]; $p->save(); } $request->session()->flash('status', 'success'); $request->session()->flash('status-message', 'Phone numbers saved!'); } } else { $request->session()->flash('status', 'danger'); $request->session()->flash('status-message', 'Invalid input, phone numbers were not modified'); } return redirect('sms'); } public function send(Request $request) { $this->authorize('admin'); $numbers = PhoneNumber::orderBy('name')->get(); $maxlen = $this->max_message_length($numbers); if(strlen($request->input('text')) <= $maxlen) { $client = new \Twilio\Rest\Client(env('TWILIO_SID'), env('TWILIO_TOKEN')); foreach($numbers as $number) { $text = $request->input('text'); $text = str_replace('{name}', $number->name, $text); $message = $client->messages->create( '+1'.str_replace('-','',$number->phone), array( 'from' => env('TWILIO_NUMBER'), 'body' => $text ) ); } $request->session()->flash('status', 'success'); $request->session()->flash('status-message', 'Message was sent! It will take about 1 second per number to deliver all the messages!'); } else { $request->session()->flash('status', 'danger'); $request->session()->flash('status-message', 'Your message was too long!'); } return redirect('sms'); } }