/**
  * @Route("/", methods="POST")
  * @Route("/{id}", methods="POST", requirements={"id"="\d+"})
  * @Request({"submission": "array", "id": "int", "g-recaptcha-response": "string"}, csrf=true)
  */
 public function saveAction($data, $id = 0, $gRecaptchaResponse = '')
 {
     if (!($submission = Submission::find($id))) {
         $submission = Submission::create();
         unset($data['id']);
         $submission->form_id = $data['form_id'];
         $submission->created = new \DateTime();
         $submission->ip = App::request()->getClientIp();
     }
     unset($data['created']);
     if (!($form = Form::find($submission->form_id))) {
         App::abort(404, 'Form not found.');
     }
     $submission->form = $form;
     if ($form->get('recaptcha') && $id == 0) {
         $resp = (new ReCaptcha(App::module('formmaker')->config('recaptha_secret_key')))->verify($gRecaptchaResponse, App::request()->server->get('REMOTE_ADDR'));
         if (!$resp->isSuccess()) {
             $errors = $resp->getErrorCodes();
             App::abort(403, $errors[0]);
         }
     }
     $submission->save($data);
     $submission->email = $submission->getUserEmail();
     if ($id == 0 && $submission->email) {
         try {
             (new MailHelper($submission))->sendMail();
             $submission->save();
         } catch (Exception $e) {
             App::abort(400, $e->getMessage());
         }
     }
     return ['message' => 'Submission successfull', 'submission' => $submission];
 }
 /**
  * @Request({"user", "key"})
  */
 public function confirmAction($username = "", $activation = "")
 {
     if (empty($username) || empty($activation) || !($user = User::where(compact('username', 'activation'))->first())) {
         return $this->messageView(__('Invalid key.'), $success = false);
     }
     if ($user->isBlocked()) {
         return $this->messageView(__('Your account has not been activated or is blocked.'), $success = false);
     }
     $error = '';
     if ('POST' === App::request()->getMethod()) {
         try {
             if (!App::csrf()->validate()) {
                 throw new Exception(__('Invalid token. Please try again.'));
             }
             $password = App::request()->request->get('password');
             if (empty($password)) {
                 throw new Exception(__('Enter password.'));
             }
             if ($password != trim($password)) {
                 throw new Exception(__('Invalid password.'));
             }
             $user->password = App::get('auth.password')->hash($password);
             $user->activation = null;
             $user->save();
             App::message()->success(__('Your password has been reset.'));
             return App::redirect('@user/login');
         } catch (Exception $e) {
             $error = $e->getMessage();
         }
     }
     return ['$view' => ['title' => __('Reset Confirm'), 'name' => 'system/user/reset-confirm.php'], 'username' => $username, 'activation' => $activation, 'error' => $error];
 }
Example #3
0
 /**
  * @Route(methods="POST", defaults={"_maintenance" = true})
  * @Request({"credentials": "array", "remember_me": "boolean", "redirect": "string"})
  */
 public function authenticateAction($credentials, $remember = false, $redirect = '')
 {
     try {
         if (!App::csrf()->validate()) {
             throw new CsrfException(__('Invalid token. Please try again.'));
         }
         App::auth()->authorize($user = App::auth()->authenticate($credentials, false));
         if (($event = App::auth()->login($user, $remember)) && $event->hasResponse()) {
             return $event->getResponse();
         }
         if (App::request()->isXmlHttpRequest()) {
             return App::response()->json(['csrf' => App::csrf()->generate()]);
         } else {
             return App::redirect(preg_replace('#(https?:)?//[^/]+#', '', $redirect));
         }
     } catch (CsrfException $e) {
         if (App::request()->isXmlHttpRequest()) {
             return App::response()->json(['csrf' => App::csrf()->generate()], 401);
         }
         $error = $e->getMessage();
     } catch (BadCredentialsException $e) {
         $error = __('Invalid username or password.');
     } catch (AuthException $e) {
         $error = $e->getMessage();
     }
     if (App::request()->isXmlHttpRequest()) {
         App::abort(401, $error);
     } else {
         App::message()->error($error);
         return App::redirect(preg_replace('#(https?:)?//[^/]+#', '', App::url()->previous()));
     }
 }
Example #4
0
 /**
  * @Route(methods="POST", defaults={"_maintenance" = true})
  * @Request({"credentials": "array", "_remember_me": "boolean"})
  */
 public function authenticateAction($credentials, $remember = false)
 {
     $isXml = App::request()->isXmlHttpRequest();
     try {
         if (!App::csrf()->validate()) {
             throw new AuthException(__('Invalid token. Please try again.'));
         }
         App::auth()->authorize($user = App::auth()->authenticate($credentials, false));
         if (!$isXml) {
             return App::auth()->login($user, $remember);
         } else {
             App::auth()->setUser($user, $remember);
             return ['success' => true];
         }
     } catch (BadCredentialsException $e) {
         $error = __('Invalid username or password.');
     } catch (AuthException $e) {
         $error = $e->getMessage();
     }
     if (!$isXml) {
         App::message()->error($error);
         return App::redirect(App::url()->previous());
     } else {
         App::abort(400, $error);
     }
 }
 /**
  * @param FieldValueBase $fieldValue
  * @return array
  */
 public function uploadAction(FieldValueBase $fieldValue)
 {
     try {
         if (!($path = $this->getPath($fieldValue->field->get('path')))) {
             return $this->error(__('Invalid path.'));
         }
         if (!is_dir($path) || !App::user()->hasAccess('system: manage storage | bixframework: upload files')) {
             return $this->error(__('Permission denied.'));
         }
         $fileInfo = [];
         $files = App::request()->files->get('files');
         if (!$files) {
             return $this->error(__('No files uploaded.'));
         }
         /** @var UploadedFile $file */
         foreach ($files as $file) {
             if (!$file->isValid()) {
                 return $this->error(sprintf(__('Uploaded file invalid. (%s)'), $file->getErrorMessage()));
             }
             if (!($ext = $file->guessExtension()) or !in_array($ext, $fieldValue->field->get('allowed', []))) {
                 return $this->error(__('File extension not allowed.'));
             }
             if (!($size = $file->getClientSize()) or $size > $fieldValue->field->get('max_size', 0) * 1024 * 1024) {
                 return $this->error(__('File is too large.'));
             }
             //give file unique name
             $localFile = $file->move($path, sprintf('%d%d-%s', microtime(true) * 10000, rand(), preg_replace("/[^a-zA-Z0-9\\.]/", "-", $file->getClientOriginalName())));
             $fileInfo[] = ['name' => $file->getClientOriginalName(), 'size' => $localFile->getSize(), 'path' => str_replace(App::path(), '', $localFile->getPathname()), 'url' => ltrim(App::url()->getStatic($localFile->getPathname(), [], 'base'), '/')];
         }
         return ['message' => __('Upload complete.'), 'files' => $fileInfo];
     } catch (\Exception $e) {
         return $this->error(__('Unable to upload.'));
     }
 }
 /**
  * @Route("/admin/login", defaults={"_maintenance"=true})
  */
 public function loginAction()
 {
     if (App::user()->isAuthenticated()) {
         return App::redirect('@system');
     }
     return ['$view' => ['title' => __('Login'), 'name' => 'system/theme:views/login.php', 'layout' => false], 'last_username' => App::session()->get(Auth::LAST_USERNAME), 'redirect' => App::request()->get('redirect') ?: App::url('@system', [], true), 'remember_me_param' => Auth::REMEMBER_ME_PARAM];
 }
 /**
  * @Route("/", methods="POST")
  * @Route("/{id}", methods="POST", requirements={"id"="\d+"})
  * @Request({"submission": "array", "id": "int"}, csrf=true)
  */
 public function saveAction($data, $id = 0)
 {
     if (!($submission = Submission::find($id))) {
         $submission = Submission::create();
         unset($data['id']);
         $submission->form_id = $data['form_id'];
         $submission->created = new \DateTime();
         $submission->ip = App::request()->getClientIp();
     }
     unset($data['created']);
     if (!($form = Form::find($submission->form_id))) {
         App::abort(404, 'Form not found.');
     }
     $submission->form = $form;
     $submission->save($data);
     $submission->email = $submission->getUserEmail();
     if ($id == 0 && $submission->email) {
         try {
             (new MailHelper($submission))->sendMail();
             $submission->save();
         } catch (Exception $e) {
             App::abort(400, $e->getMessage());
         }
     }
     return ['message' => 'Submission successfull', 'submission' => $submission];
 }
Example #8
0
 /**
  * @Route("/{id}", name="view", requirements={"id"="\d+"})
  */
 public function viewAction($id)
 {
     $artist = Artist::query()->where('id = ?', [$id])->related('album')->first();
     $request = App::request();
     if (is_null($artist)) {
         $request->getSession()->getFlashBag()->add('error', __('Tried to view an non-existing Artist'));
         return App::response()->redirect('@shoutzor/artist/index');
     }
     $topTracks = $artist->getTopMedia();
     return ['$view' => ['title' => 'Artist: ' . $artist->name, 'name' => 'shoutzor:views/artist/view.php'], 'image' => is_null($artist->image) || empty($artist->image) ? App::url()->getStatic('shoutzor:assets/images/profile-placeholder.png') : App::url()->getStatic('shoutzor:' . App::module('shoutzor')->config('shoutzor')['imageDir'] . '/' . $artist->image), 'summary' => empty($artist->summary) ? __('No summary for this artist is available') : $artist->summary, 'artist' => $artist, 'topTracks' => $topTracks, 'albums' => $artist->getAlbums()];
 }
 /**
  * @param      $event
  * @param User $user
  */
 public function onUserChange($event, User $user)
 {
     $profilevalues = App::request()->request->get('profilevalues', []);
     if (count($profilevalues)) {
         $profileUser = ProfileUser::load($user);
         $profileUser->setProfileValues($profilevalues);
         $profileUser->saveProfile();
         //only save once
         App::request()->request->set('profilevalues', []);
     }
 }
Example #10
0
 /**
  * @Route("/search", name="search", methods="GET")
  * @Request({"q":"string", "page":"int"})
  */
 public function searchAction($q = "", $page = 1)
 {
     $query = Artist::query()->select('*');
     $request = App::request();
     if (empty($q)) {
         return ['$view' => ['title' => 'Search', 'name' => 'shoutzor:views/search_error.php']];
     }
     $query = Media::query()->select('m.*')->from('@shoutzor_media m')->leftJoin('@shoutzor_media_artist ma', 'ma.media_id = m.id')->leftJoin('@shoutzor_artist a', 'a.id = ma.artist_id')->where('m.status = :status AND (m.title LIKE :search OR a.name LIKE :search OR m.filename LIKE :search)', ['status' => Media::STATUS_FINISHED, 'search' => "%{$q}%"])->orderBy('m.title', 'DESC');
     $limit = 20;
     $count = $query->count();
     $total = ceil($count / $limit);
     $page = max(1, min($total, $page));
     $results = $query->offset(($page - 1) * $limit)->limit($limit)->orderBy('name', 'ASC')->related(['artist', 'album'])->get();
     return ['$view' => ['title' => 'Search', 'name' => 'shoutzor:views/search.php'], 'searchterm' => htmlspecialchars($q), 'page' => $page, 'totalPage' => $total, 'resultCount' => $count, 'results' => $results];
 }
 /**
  * @Route(methods="POST", defaults={"_maintenance" = true})
  * @Request({"credentials": "array"})
  */
 public function authenticateAction($credentials)
 {
     try {
         if (!App::csrf()->validate()) {
             throw new AuthException(__('Invalid token. Please try again.'));
         }
         App::auth()->authorize($user = App::auth()->authenticate($credentials, false));
         return App::auth()->login($user, App::request()->get(Auth::REMEMBER_ME_PARAM));
     } catch (BadCredentialsException $e) {
         App::message()->error(__('Invalid username or password.'));
     } catch (AuthException $e) {
         App::message()->error($e->getMessage());
     }
     return App::redirect(App::url()->previous());
 }
Example #12
0
 /**
  * TODO: Limit catalogue if maintenance mode is enabled?
  * @Route("/{locale}", requirements={"locale"="[a-zA-Z0-9_-]+"}, defaults={"_maintenance" = true})
  * @Request({"locale"})
  */
 public function indexAction($locale = null)
 {
     $intl = App::module('system/intl');
     $intl->loadLocale($locale);
     $messages = $intl->getFormats($locale) ?: [];
     $messages['locale'] = $locale;
     $messages['translations'] = [$locale => App::translator()->getCatalogue($locale)->all()];
     $messages = json_encode($messages);
     $request = App::request();
     $json = $request->isXmlHttpRequest();
     $response = $json ? App::response()->json() : App::response('', 200, ['Content-Type' => 'application/javascript']);
     $response->setETag(md5($json . $messages))->setPublic();
     if ($response->isNotModified($request)) {
         return $response;
     }
     return $response->setContent($json ? $messages : sprintf('var $locale = %s;', $messages));
 }
Example #13
0
 /**
  * @Request({"type": "string"}, csrf=true)
  */
 public function uploadAction($type)
 {
     $file = App::request()->files->get('file');
     if ($file === null || !$file->isValid()) {
         App::abort(400, __('No file uploaded.'));
     }
     $package = $this->loadPackage($file->getPathname());
     if (!$package->getName() || !$package->get('title') || !$package->get('version')) {
         App::abort(400, __('"composer.json" file not valid.'));
     }
     if ($package->get('type') !== 'pagekit-' . $type) {
         App::abort(400, __('No Pagekit %type%', ['%type%' => $type]));
     }
     $filename = str_replace('/', '-', $package->getName()) . '-' . $package->get('version') . '.zip';
     $file->move(App::get('path') . '/tmp/packages', $filename);
     return compact('package');
 }
Example #14
0
 /**
  * @Route("/", name="index")
  */
 public function indexAction()
 {
     $request = App::request();
     $config = App::module('shoutzor')->config('shoutzor');
     $config = array_merge($config, $_POST);
     $form = new FormGenerator('', 'POST', 'uk-form uk-form-horizontal');
     $form->addField(new DivField("Permission Check", $config['mediaDir'] . (is_writable($config['mediaDir']) ? " is writable" : " is not writable! chown manually to www-data:www-data"), "", is_writable($config['mediaDir']) ? "uk-alert uk-alert-success" : "uk-alert uk-alert-danger"));
     $form->addField(new DivField("Permission Check", App::module('shoutzor')->config('root_path') . $config['imageDir'] . (is_writable(App::module('shoutzor')->config('root_path') . $config['imageDir']) ? " is writable" : " is not writable! chown manually to www-data:www-data"), "", is_writable(App::module('shoutzor')->config('root_path') . $config['imageDir']) ? "uk-alert uk-alert-success" : "uk-alert uk-alert-danger"));
     $form->addField(new DividerField());
     $form->addField(new SelectField("upload", "upload", "Allow Uploads", "text", $config['upload'], array(['value' => 0, 'title' => 'Disabled'], ['value' => 1, 'title' => 'Enabled']), false, "Changing this setting will not delete uploaded content"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new SelectField("request", "request", "Allow Requests", "text", $config['request'], array(['value' => 0, 'title' => 'Disabled'], ['value' => 1, 'title' => 'Enabled']), false, "Changing this setting will allow / deny user requests"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new DividerField());
     $form->addField(new InputField("mediaDir", "mediaDir", "Media Storage Directory", "text", $config['mediaDir'], "The directory where uploads should be stored", "uk-form-width-large"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("imageDir", "imageDir", "Image Storage Directory", "text", $config['imageDir'], "The directory where downloaded images should be stored", "uk-form-width-large"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("parserLastRun", "parserLastRun", "Parser Last Run Timestamp", "text", $config['parserLastRun'], "The timestamp of when the parser last ran - in general you will not have to make any changes to this value"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("parserMaxItems", "parserMaxItems", "Parser Max Items", "text", $config['parserMaxItems'], "The maximum amount of items the parser should parse on each run"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new DividerField());
     $form->addField(new InputField("userRequestDelay", "userRequestDelay", "User Request Delay", "text", $config['userRequestDelay'], "The delay in minutes that a user has to wait to be able to request a media object again"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("mediaRequestDelay", "mediaRequestDelay", "Media Request Delay", "text", $config['mediaRequestDelay'], "The delay in minutes before a media object can be played again"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("artistRequestDelay", "artistRequestDelay", "Artist Request Delay", "text", $config['artistRequestDelay'], "The delay in minutes before a media object from the same artist can be played again"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("uploadDurationLimit", "uploadDurationLimit", "Media Duration Limit (Minutes)", "text", $config['uploadDurationLimit'], "The limit of the duration from uploaded media files in minutes - changing this will have no effect on already uploaded files"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new SelectField("useFilenameIfUntitled", "useFilenameIfUntitled", "Use Filename If Untitled", "text", $config['useFilenameIfUntitled'], array(['value' => 0, 'title' => 'Disabled'], ['value' => 1, 'title' => 'Enabled']), false, "Use the filename as title when no title could be detected and/or found"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("submit", "", "Save Changes", "submit", "Save Changes", "", "uk-button uk-button-primary"));
     $alert = array();
     //Check if a POST request has been made
     if ($request->isMethod('POST')) {
         $form->validate();
         //Make sure no errors have occured during validation
         if ($form->hasErrors() === false) {
             $configValues = array();
             foreach ($form->getFields() as $field) {
                 if (!empty($field->getName())) {
                     $configValues[$field->getName()] = $field->getValue();
                 }
             }
             App::config('shoutzor')->set('shoutzor', $configValues);
             //Do stuff
             $alert = array('type' => 'success', 'msg' => __('Changes saved. Make sure the applicable liquidsoap scripts are restarted for the changes to take effect'));
         } else {
             $alert = array('type' => 'error', 'msg' => __('Not all fields passed validation, correct the problems and try again'));
         }
     }
     $content = $form->render();
     return ['$view' => ['title' => __('Shoutzor Settings'), 'name' => 'shoutzor:views/admin/shoutzor.php'], 'form' => $content, 'alert' => $alert];
 }
 public function onUserChange($event, User $user)
 {
     /** @var \Bixie\Userprofile\Model\Profilevalue $profilevalue */
     foreach (App::request()->request->get('profilevalues', []) as $data) {
         // is new ?
         if (!($profilevalue = Profilevalue::find($data['id']))) {
             if ($data['id']) {
                 App::abort(404, __('Userprofilevalue not found.'));
             }
             $profilevalue = Profilevalue::create();
         }
         $profilevalue->field_id = $data['field_id'];
         $profilevalue->user_id = $user->id;
         $profilevalue->multiple = $data['multiple'];
         $profilevalue->setValue($data['value']);
         $profilevalue->save();
     }
 }
Example #16
0
 /**
  * Adds a menu item.
  *
  * @param string $id
  * @param array  $item
  */
 public function addItem($id, array $item)
 {
     $meta = App::user()->get('admin.menu', []);
     $route = App::request()->attributes->get('_route');
     $item = new ArrObject($item, ['id' => $id, 'label' => $id, 'parent' => 'root', 'priority' => 0]);
     if (!App::user()->hasAccess($item['access'])) {
         return;
     }
     if (isset($meta[$id])) {
         $item['priority'] = $meta[$id];
     }
     if ($item['icon']) {
         $item['icon'] = App::url()->getStatic($item['icon']);
     }
     $item['active'] = (bool) preg_match('#^' . str_replace('*', '.*', $item['active'] ?: $item['url']) . '$#', $route);
     $item['url'] = App::url($item['url']);
     $this->items[$id] = $item;
 }
Example #17
0
 /**
  * @Route("/", name="index")
  */
 public function indexAction()
 {
     $request = App::request();
     $config = App::module('shoutzor')->config('lastfm');
     $config = array_merge($config, $_POST);
     //Set the value to the new POST data
     $liquidsoapManager = new LiquidsoapManager();
     $form = new FormGenerator('', 'POST', 'uk-form uk-form-horizontal');
     $form->addField(new DivField("Notice", "Make sure to have provided a working Application API Key before enabling LastFM to prevent any issues", "", "uk-alert uk-alert-info"));
     $form->addField(new CheckboxField("enabled", "enabled", "Enable LastFM", array($config['enabled']), array(['value' => "1", 'title' => 'enabled'], ['value' => "0", 'title' => 'disabled']), false, "Enable the LastFM Integration"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY, FormValidation::REQ_VALUE => array('1', '0')));
     $form->addField(new InputField("apikey", "apikey", "Application API Key", "text", $config['apikey'], "The Application Key for LastFM, if you don't have one, get one at: <a href='hhttp://www.last.fm/api/account/create'>http://www.last.fm/api/account/create</a>"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("secret", "secret", "Application Secret", "text", $config['secret'], "The Application Secret for LastFM, if you don't have one, get one at: <a href='http://www.last.fm/api/account/create'>http://www.last.fm/api/account/create</a>"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new DividerField());
     $form->addField(new InputField("submit", "", "Save Changes", "submit", "Save Changes", "", "uk-button uk-button-primary"));
     $alert = array();
     //Check if a POST request has been made
     if ($request->isMethod('POST')) {
         $form->validate();
         //Make sure no errors have occured during validation
         if ($form->hasErrors() === false) {
             $configValues = array();
             foreach ($form->getFields() as $field) {
                 if (!empty($field->getName())) {
                     $configValues[$field->getName()] = $field->getValue();
                 }
             }
             //Save our config changes
             App::config('shoutzor')->set('lastfm', $configValues);
             //Show success message
             $alert = array('type' => 'success', 'msg' => __('Changes saved'));
         } else {
             $alert = array('type' => 'error', 'msg' => __('Not all fields passed validation, correct the problems and try again'));
         }
     }
     $content = $form->render();
     return ['$view' => ['title' => __('Shoutzor LastFM'), 'name' => 'shoutzor:views/admin/lastfm.php'], 'form' => $content, 'alert' => $alert];
 }
 /**
  * @Route("/", name="index")
  */
 public function indexAction()
 {
     $request = App::request();
     $config = App::module('shoutzor')->config('liquidsoap');
     $config = array_merge($config, $_POST);
     //Set the value to the new POST data
     $form = new FormGenerator('', 'POST', 'uk-form uk-form-horizontal');
     $form->addField(new InputField("pidFileDirectory", "pidFileDirectory", "Pid File Directory", "text", $config['pidFileDirectory'], "The directory where liquidsoap stores its script PID files"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("logDirectoryPath", "logDirectoryPath", "Log Directory Path", "text", $config['logDirectoryPath'], "The directory where to store the logs (without ending slash)"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("socketPath", "socketPath", "Socket Path", "text", $config['socketPath'], "The directory where to create the socket files (without ending slash)"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("socketPermissions", "socketPermissions", "Socket Permissions", "text", $config['socketPermissions'], "The permissions to set to the created socket files"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new DividerField());
     $form->addField(new CheckboxField("wrapperLogStdout", "wrapperLogStdout", "Wrapper Log Stdout", array($config['wrapperLogStdout']), array(['value' => "true", 'title' => 'enable'], ['value' => "false", 'title' => 'disable']), false, "Show stdout output in the logs"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY, FormValidation::REQ_VALUE => array('true', 'false')));
     $form->addField(new CheckboxField("wrapperServerTelnet", "wrapperServerTelnet", "Wrapper Enable Telnet", array($config['wrapperServerTelnet']), array(['value' => "true", 'title' => 'enable'], ['value' => "false", 'title' => 'disable']), false, "Enable telnet access to the wrapper"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY, FormValidation::REQ_VALUE => array('true', 'false')));
     $form->addField(new CheckboxField("wrapperServerSocket", "wrapperServerSocket", "Wrapper Enable Socket", array($config['wrapperServerSocket']), array(['value' => "true", 'title' => 'enable'], ['value' => "false", 'title' => 'disable']), false, "Enable socket access to the wrapper - REQUIRED FOR CONTROLS TO WORK"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY, FormValidation::REQ_VALUE => array('true', 'false')));
     $form->addField(new DividerField());
     $form->addField(new CheckboxField("shoutzorLogStdout", "shoutzorLogStdout", "Shoutzor Log Stdout", array($config['shoutzorLogStdout']), array(['value' => "true", 'title' => 'enable'], ['value' => "false", 'title' => 'disable']), false, "Show stdout output in the logs"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY, FormValidation::REQ_VALUE => array('true', 'false')));
     $form->addField(new CheckboxField("shoutzorServerTelnet", "shoutzorServerTelnet", "Shoutzor Enable Telnet", array($config['shoutzorServerTelnet']), array(['value' => "true", 'title' => 'enable'], ['value' => "false", 'title' => 'disable']), false, "Enable telnet access to shoutzor"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY, FormValidation::REQ_VALUE => array('true', 'false')));
     $form->addField(new CheckboxField("shoutzorServerSocket", "shoutzorServerSocket", "Shoutzor Enable Socket", array($config['shoutzorServerSocket']), array(['value' => "true", 'title' => 'enable'], ['value' => "false", 'title' => 'disable']), false, "Enable socket access to shoutzor - REQUIRED FOR CONTROLS TO WORK"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY, FormValidation::REQ_VALUE => array('true', 'false')));
     $form->addField(new DividerField());
     $form->addField(new InputField("wrapperInputListeningMount", "wrapperInputListeningMount", "Wrapper Input Listening Mount", "text", $config['wrapperInputListeningMount'], "The mount that the wrapper and shoutzor should be using to communicate locally"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("wrapperInputListeningPort", "wrapperInputListeningPort", "Wrapper Input Listening Port", "text", $config['wrapperInputListeningPort'], "The port the wrapper and shoutzor should be using to communicate locally"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("wrapperInputListeningPassword", "wrapperInputListeningPassword", "Wrapper Input Listening Password", "password", $config['wrapperInputListeningPassword'], "The password the wrapper and shoutzor should be using to communicate locally"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new DividerField());
     $form->addField(new InputField("wrapperOutputHost", "wrapperOutputHost", "Wrapper Output Host", "text", $config['wrapperOutputHost'], "The IP of the icecast server to stream to"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("wrapperOutputMount", "wrapperOutputMount", "Wrapper Output Mount", "text", $config['wrapperOutputMount'], "The mount of the icecast server to stream to"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("wrapperOutputPort", "wrapperOutputPort", "Wrapper Output Port", "text", $config['wrapperOutputPort'], "The port of the icecast server to stream to"))->setValidationType(FormValidation::TYPE_NUMERIC)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new InputField("wrapperOutputPassword", "wrapperOutputPassword", "Wrapper Output Password", "password", $config['wrapperOutputPassword'], "The password of the icecast server to stream to"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new DividerField());
     $form->addField(new InputField("shoutzorUrl", "shoutzorUrl", "Shoutzor Website URL", "text", $config['shoutzorUrl'], "The hostname of the url this website is running on, example: 'https://shoutzor.com' NO ENDING SLASH"))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY));
     $form->addField(new DividerField());
     $form->addField(new InputField("encodingBitrate", "encodingBitrate", "Encoding bitrate", "text", $config['encodingBitrate'], "The bitrate of our audio stream"));
     $form->addField(new InputField("encodingQuality", "encodingQuality", "LAME Encoding Quality", "text", $config['encodingQuality'], "The quality to be used by the LAME encoder, 0 - 9 where 0 is the highest quality"));
     $form->addField(new DividerField());
     $form->addField(new InputField("submit", "", "Save Changes", "submit", "Save Changes", "", "uk-button uk-button-primary"));
     $alert = array();
     //Check if a POST request has been made
     if ($request->isMethod('POST')) {
         $form->validate();
         //Make sure no errors have occured during validation
         if ($form->hasErrors() === false) {
             $replace_values = array();
             $configValues = array();
             foreach ($form->getFields() as $field) {
                 if (!empty($field->getName())) {
                     $configValues[$field->getName()] = $field->getValue();
                     $replace_values['%' . $field->getName() . '%'] = $field->getValue();
                 }
             }
             //Save our config changes
             App::config('shoutzor')->set('liquidsoap', $configValues);
             //Generate our new config file
             $liquidsoapManager = new liquidsoapManager();
             $liquidsoapManager->generateConfigFile($replace_values);
             //Show success message
             $alert = array('type' => 'success', 'msg' => __('Changes saved. Make sure the applicable liquidsoap scripts are restarted for the changes to take effect'));
         } else {
             $alert = array('type' => 'error', 'msg' => __('Not all fields passed validation, correct the problems and try again'));
         }
     }
     $content = $form->render();
     return ['$view' => ['title' => __('Liquidsoap Settings'), 'name' => 'shoutzor:views/admin/liquidsoap.php'], 'form' => $content, 'alert' => $alert];
 }
Example #19
0
 /**
  * save event
  * @param Event $event
  * @param File $file
  */
 public function onProductChange($event, $file)
 {
     $data = App::request()->request->get('product', []);
     if (!empty($data)) {
         // is new ?
         if (!($product = Product::find($data['id']))) {
             if ($data['id']) {
                 App::abort(404, __('Product not found.'));
             }
             $product = Product::createNew($data);
         }
         $product->save($data);
         $file->product = $product;
     }
 }
 /**
  * Redirects a user after successful logout.
  *
  * @param LogoutEvent $event
  */
 public function onLogout(LogoutEvent $event)
 {
     $event->setResponse(App::response()->redirect(App::request()->get(Auth::REDIRECT_PARAM)));
 }
 /**
  * @Route("/", methods="POST")
  * @Route("/{id}", methods="POST", requirements={"id"="\d+"})
  * @Request({"comment": "array", "id": "int"}, csrf=true)
  */
 public function saveAction($data, $id = 0)
 {
     if (!$id) {
         if (!$this->user->hasAccess('blog: post comments')) {
             App::abort(403, __('Insufficient User Rights.'));
         }
         $comment = Comment::create();
         if ($this->user->isAuthenticated()) {
             $data['author'] = $this->user->name;
             $data['email'] = $this->user->email;
             $data['url'] = $this->user->url;
         } elseif ($this->blog->config('comments.require_email') && (!@$data['author'] || !@$data['email'])) {
             App::abort(400, __('Please provide valid name and email.'));
         }
         $comment->user_id = $this->user->isAuthenticated() ? (int) $this->user->id : 0;
         $comment->ip = App::request()->getClientIp();
         $comment->created = new \DateTime();
     } else {
         if (!$this->user->hasAccess('blog: manage comments')) {
             App::abort(403, __('Insufficient User Rights.'));
         }
         $comment = Comment::find($id);
         if (!$comment) {
             App::abort(404, __('Comment not found.'));
         }
     }
     unset($data['created']);
     // check minimum idle time in between user comments
     if (!$this->user->hasAccess('blog: skip comment min idle') and $minidle = $this->blog->config('comments.minidle') and $commentIdle = Comment::where($this->user->isAuthenticated() ? ['user_id' => $this->user->id] : ['ip' => App::request()->getClientIp()])->orderBy('created', 'DESC')->first()) {
         $diff = $commentIdle->created->diff(new \DateTime("- {$minidle} sec"));
         if ($diff->invert) {
             App::abort(403, __('Please wait another %seconds% seconds before commenting again.', ['%seconds%' => $diff->s + $diff->i * 60 + $diff->h * 3600]));
         }
     }
     if (@$data['parent_id'] && !($parent = Comment::find((int) $data['parent_id']))) {
         App::abort(404, __('Parent not found.'));
     }
     if (!@$data['post_id'] || !($post = Post::where(['id' => $data['post_id']])->first()) or !($this->user->hasAccess('blog: manage comments') || $post->isCommentable() && $post->isPublished())) {
         App::abort(404, __('Post not found.'));
     }
     $approved_once = (bool) Comment::where(['user_id' => $this->user->id, 'status' => Comment::STATUS_APPROVED])->first();
     $comment->status = $this->user->hasAccess('blog: skip comment approval') ? Comment::STATUS_APPROVED : $this->user->hasAccess('blog: comment approval required once') && $approved_once ? Comment::STATUS_APPROVED : Comment::STATUS_PENDING;
     // check the max links rule
     if ($comment->status == Comment::STATUS_APPROVED && $this->blog->config('comments.maxlinks') <= preg_match_all('/<a [^>]*href/i', @$data['content'])) {
         $comment->status = Comment::STATUS_PENDING;
     }
     // check for spam
     //App::trigger('system.comment.spam_check', new CommentEvent($comment));
     $comment->save($data);
     return ['message' => 'success', 'comment' => $comment];
 }
 /**
  * Checks if the user is authorized to login to administration section.
  *
  * @param  AuthorizeEvent $event
  * @throws AuthException
  */
 public function onAuthorize(AuthorizeEvent $event)
 {
     if (strpos(App::request()->get('redirect'), App::url('@system', [], true)) === 0 && !$event->getUser()->hasAccess('system: access admin area')) {
         throw new AuthException(__('You do not have access to the administration area of this site.'));
     }
 }
Example #23
0
 protected function getPath($path = '')
 {
     $root = strtr(App::path(), '\\', '/');
     $path = $this->normalizePath($root . '/' . App::request()->get('root') . '/' . App::request()->get('path') . '/' . $path);
     return 0 === strpos($path, $root) ? $path : false;
 }
Example #24
0
 /**
  * Handles the file uploads
  * @method upload
  * @param musicfile the file that is beeing uploaded
  */
 public function upload($params)
 {
     //Make sure file uploads are enabled
     if (App::module('shoutzor')->config('shoutzor.upload') == 0) {
         return $this->formatOutput(__('File uploads have been disabled'), self::METHOD_NOT_AVAILABLE);
     }
     //Make sure file uploads are enabled
     if (!App::user()->hasAccess("shoutzor: upload files")) {
         return $this->formatOutput(__('You have no permission to upload files'), self::METHOD_NOT_AVAILABLE);
     }
     //Initialize our parser class
     $parser = new Parser();
     //Our temporary storage path
     $path = $parser->getTempMediaDir();
     //Make sure our temporary directory exists and is writable
     if (!is_dir($path) && !mkdir($path) || !is_writable($path)) {
         return $this->formatOutput(__('Directory ' . $path . ' is not writable, Permission denied'), self::ERROR_IN_REQUEST);
     }
     //Get the uploaded file
     $file = App::request()->files->get('musicfile');
     //Make sure the uploaded file is uploaded correctly
     if ($file === null) {
         return $this->formatOutput(__('No file has been uploaded with name: musicfile'), self::INVALID_PARAMETER_VALUE);
     }
     if ($file->isValid() === false) {
         return $this->formatOutput(__('The uploaded file has not been uploaded correctly'), self::INVALID_PARAMETER_VALUE);
     }
     $filename = md5(uniqid("", true)) . '.' . $file->getClientOriginalName();
     //Save the file into our temporary directory
     $file->move($path, $filename);
     $media = Media::create(['title' => $file->getClientOriginalName(), 'filename' => $filename, 'uploader_id' => App::user()->id, 'created' => new DateTime(), 'status' => Media::STATUS_UPLOADED, 'crc' => '', 'duration' => 0]);
     //Since its just an audio file, parse immediately
     $media->status = $parser->parse($media);
     //If the parse succeeded, save it in the database
     if ($media->status == Media::STATUS_FINISHED || $media->status == Media::STATUS_ERROR) {
         $media->save();
     }
     //If the parse failed, the status will be set to the relevant code. Also no need to save the record
     //No problems, return result
     return $this->formatOutput((array) $media);
 }