public function create($content, Users $user)
 {
     $message = new Messages();
     $valid = $message->setContent($content);
     if ($valid === true) {
         $valid = $message->setUser($user);
         if ($valid === true) {
             $content = mysqli_real_escape_string($this->database, $message->getContent());
             $id_user = $message->getUser();
             $query = "INSERT INTO messages (content, id_user) \n\t\t\t\t\tVALUES ('" . $content . "', '" . $id_user . "')";
             $result = mysqli_query($this->database, $query);
             if ($result) {
                 $id = mysqli_insert_id($this->database);
                 if ($id) {
                     return $this->findById($id);
                 } else {
                     return "Erreur serveur.";
                 }
             } else {
                 return mysqli_error();
             }
         } else {
             return $valid;
         }
     } else {
         return $valid;
     }
 }
function test_auto_marking_sc($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale'], '/new-question/errors');
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die($msg->_('invalid-format'), 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data) || !isset($input_data['question']) || !isset($input_data['source-code']) || !is_string($input_data['source-code'])) {
            Util::output_errors_and_die($msg->_('invalid-format'), 400);
        }
        $extra = !empty($input_data['extra']) ? $input_data['extra'] : [];
        $qd = $input_data['question'];
        set_empty_if_undefined($qd['type']);
        if ($qd['type'] != 'source-code') {
            Util::output_errors_and_die('', 400);
        }
        $q = new QuestionSC($qd, Question::FROM_USER, $extra);
        $q->mark_automatically(array('source-code' => $input_data['source-code']), $log, $result);
        http_response_code(200);
        header('Content-Type: application/json');
        echo my_json_encode($result);
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Example #3
0
 /** Responsible for presenting a collection back to the user. */
 public function actionIndex($p)
 {
     $this->bag->q = $query = strtolower($this->request->getQuery('q'));
     $messages = new Messages();
     $this->bag->nodes = $messages->findNodes()->orderBy('created_at DESC')->where(array('text' => "*{$query}*"));
     $this->renderAction('index');
 }
 public function actionSavemessage()
 {
     $subject = Yii::app()->Ini->v('subject');
     $message = Yii::app()->Ini->v('message');
     $to_usertype = Yii::app()->Ini->v('to_usertype');
     $from_id = Yii::app()->user->getId();
     $from_user_type = Yii::app()->user->role;
     $to_id = Yii::app()->Ini->v('receiver_id');
     $sent_date = date("Y-m-d H:i:s");
     $messages = new Messages();
     $messages->subject = $subject;
     $messages->message = $message;
     $messages->from_id = $from_id;
     $messages->to_id = $to_id;
     $messages->to_user_type = 'to_usertype';
     $messages->from_user_type = $from_user_type;
     $messages->date_sent = $sent_date;
     $this->sendEmailNotification($subject, $message, $to_id, Yii::app()->name);
     if ($messages->save()) {
         $status = array('success' => true);
     } else {
         $status = array('success' => false, 'error_message' => print_r($messages->getErrors()));
     }
     $this->renderJSON($status);
 }
Example #5
0
 /** Receives the form submission from the new action and creates the new object. */
 public function actionCreate()
 {
     // create a new message
     $messages = new Messages();
     $name = $messages->generateNewName($this->request->getPost());
     if (empty($name)) {
         $this->flashFail = 'The message cannot be blank';
         $this->redirectTo('topics/new');
     }
     $stamp = date("Y-m-d H:i:s", mktime());
     $save['name'] = $this->userRow['name'];
     // create new topic
     $save['name'] = $this->request->getPost('name');
     $save['created_at'] = $save['updated_at'] = $stamp;
     $save['created_by'] = $this->userRow['name'];
     $save['is_archived'] = 0;
     $topicId = $this->topics->save($save);
     // create new message... read by us
     $newId = $messages->save(array('topics_id' => $topicId, 'created_at' => $stamp, 'name' => $name, 'user' => $this->userRow['name'], 'read_by' => "!{$this->userRow['id']}!"));
     // create new mailer
     //$mailer = new Mailer();
     // save the text
     $nodes = new Nodes();
     $nodes->saveMessage(0, $this->request->getPost(0), $topicId, $newId, $this->userRow['name'], $mailer);
     // send email to all recipients
     //$users = new Users();
     //foreach ($users->select('email')->findAll() as $user) $recipients[] = $user['email'];
     //$mailer->sendMessage($recipients, $newId, $topicId, $this->topics);
     // redirect to the new message
     $this->redirectTo("messages/show/{$topicId}/{$newId}");
 }
Example #6
0
 /**
  * View your inbox
  * @return void
  */
 private function viewInbox()
 {
     require_once FRAMEWORK_PATH . 'models/messages.php';
     $messages = new Messages($this->registry);
     $cache = $messages->getInbox($this->registry->getObject('authenticate')->getUser()->getUserID());
     $this->registry->getObject('template')->buildFromTemplates('header.tpl.php', 'messages/inbox.tpl.php', 'footer.tpl.php');
     $this->registry->getObject('template')->getPage()->addTag('messages', array('SQL', $cache));
 }
function test_auto_marking($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale'], '/new-question/errors');
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die($msg->_('invalid-format'), 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data) || !isset($input_data['question']) || !isset($input_data['studentAnswer'])) {
            Util::output_errors_and_die($msg->_('invalid-format'), 400);
        }
        $extra = !empty($input_data['extra']) ? $input_data['extra'] : [];
        $qd = $input_data['question'];
        set_empty_if_undefined($qd['type']);
        if (!Validator::validate_question_type($qd['type'])) {
            Util::output_errors_and_die($msg->_('invalid-type'), 400);
        }
        switch ($qd['type']) {
            case 'short-answer':
                $q = new QuestionSA($qd, Question::FROM_USER, $extra);
                break;
            case 'essay':
                $q = new QuestionES($qd, Question::FROM_USER, $extra);
                break;
            case 'multiple-choice':
                $q = new QuestionMC($qd, Question::FROM_USER, $extra);
                break;
            case 'matching':
                $q = new QuestionMA($qd, Question::FROM_USER, $extra);
                break;
            case 'fitb-type':
                $q = new QuestionFT($qd, Question::FROM_USER, $extra);
                break;
            case 'fitb-select':
                $q = new QuestionFS($qd, Question::FROM_USER, $extra);
                break;
            case 'source-code':
                $q = new QuestionSC($qd, Question::FROM_USER, $extra);
                break;
        }
        http_response_code(200);
        header('Content-Type: application/json');
        $mark = $q->mark_automatically($input_data['studentAnswer'], $log);
        foreach ($log as $i => $line) {
            $log[$i] = $msg->_('/auto-marking/' . $line[0], $line[1]);
        }
        $log = implode('<br/>', $log);
        echo my_json_encode(array('log' => $log, 'mark' => $mark));
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Example #8
0
 public function save()
 {
     $message = new Messages();
     $message->sender_id = Yii::app()->user->id;
     $message->receiver_id = $this->receiver_id;
     $message->text = $this->text;
     $message->is_new = TRUE;
     $message->save();
 }
function create_session($request)
{
    $raw_input = $request->getBody();
    $content_type = explode(';', $request->type)[0];
    switch ($content_type) {
        case 'application/json':
            $input_data = json_decode($raw_input, true);
            break;
        case 'application/x-www-form-urlencoded':
            $input_data = array();
            parse_str($raw_input, $input_data);
            break;
        default:
            Util::output_errors_and_die('', 415);
    }
    if ($input_data === null) {
        Util::output_errors_and_die('', 400);
    }
    set_empty_if_undefined($input_data['username_or_email']);
    set_empty_if_undefined($input_data['password']);
    $msg = new Messages($GLOBALS['locale'], '/signin');
    try {
        $model = new Model();
        $user_data = $model->is_valid_user($input_data['username_or_email'], $input_data['password']);
        if (!$user_data) {
            Util::output_errors_and_die($msg->_('invalid-username-pw'), 403);
        }
        switch ($user_data['status']) {
            case 'pending-activation':
                Util::output_errors_and_die($msg->_('pending-activation'), 403);
                break;
            case 'pending-approval':
                Util::output_errors_and_die($msg->_('pending-approval'), 403);
                break;
            case 'banned':
                Util::output_errors_and_die($msg->_('banned'), 403);
                break;
            case 'active':
                $token = generate_token($user_data);
                $now = new DateTime('now');
                $expires_at = clone $now;
                $expires_at->add(new DateInterval('P7D'));
                $model->insert_auth_token($user_data['user_id'], $token, $now, $expires_at);
                http_response_code(201);
                $output = array('token' => $token, 'expires_at' => $expires_at->format('Y-m-d H:i:s'));
                setcookie('authToken', $token, $expires_at->getTimestamp(), '/', '', $secure = true, $httponly = true);
                header('Content-Type: application/json');
                echo my_json_encode($output);
                die;
                break;
        }
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
 public static function assert_manager($token)
 {
     $user_data = self::assert_user($token);
     if ($user_data['role'] !== 'manager') {
         $msg = new Messages($GLOBALS['locale']);
         Util::output_errors_and_die($msg->_('/authentication/only-managers'), 403);
     }
     return $user_data;
 }
 public function __construct($message = null, $code = 0)
 {
     if ($message) {
         $msg = new Messages($GLOBALS['locale']);
         $err = array('DATABASE-ERROR' => $msg->_('/showmsg/database-error'));
         // discard original message
         $message = my_json_encode($err);
     }
     parent::__construct($message, $code);
 }
function create_question($request, $assignment_id = null)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die('', 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data)) {
            Util::output_errors_and_die('', 400);
        }
        set_empty_if_undefined($input_data['type']);
        if (!Validator::validate_question_type($input_data['type'])) {
            Util::output_errors_and_die($msg->_('invalid-type'), 400);
        }
        switch ($input_data['type']) {
            case 'short-answer':
                $q = new QuestionSA($input_data, Question::FROM_USER);
                break;
            case 'essay':
                $q = new QuestionES($input_data, Question::FROM_USER);
                break;
            case 'multiple-choice':
                $q = new QuestionMC($input_data, Question::FROM_USER);
                break;
            case 'matching':
                $q = new QuestionMA($input_data, Question::FROM_USER);
                break;
            case 'fitb-type':
                $q = new QuestionFT($input_data, Question::FROM_USER);
                break;
            case 'fitb-select':
                $q = new QuestionFS($input_data, Question::FROM_USER);
                break;
            case 'source-code':
                $q = new QuestionSC($input_data, Question::FROM_USER);
                break;
        }
        $qid = $model->create_question($q);
        header('Content-Type: text/plain');
        echo '/question_bank/questions/' . $qid;
        http_response_code(201);
        die;
    } catch (ConflictException $e) {
        Util::output_errors_and_die($e->getMessage(), 409);
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Example #13
0
 public function __construct()
 {
     parent::__construct('Fireside');
     // latest messages
     $messages = new Messages();
     $latestMessages = $messages->find()->orderBy('id DESC')->limit(20)->where(array('id' => '>0'));
     foreach ($latestMessages as $message) {
         $item = array('http://' . $_SERVER['HTTP_HOST'] . WWW_DIR . "/messages/show/{$message['topics_id']}/{$message['id']}" => array('title' => $message['name'], 'content' => 'Message by ' . $message['user'] . ' on ' . $message['created_at']));
         $this->atomise($item);
     }
     $this->generate();
 }
Example #14
0
 function render()
 {
     $message = new Messages($this->db);
     $message->key = 'Second message';
     $message->message = 'This is the second message inserted from code';
     $message->save();
     $messages = new Messages($this->db);
     $msg = $messages->all()[0];
     $this->f3->set('msg', $msg);
     $template = new Template();
     echo $template->render('template.htm');
 }
 /**
  * List latest messages
  * 
  * @return Response
  */
 public function inbox()
 {
     if (!empty($this->app['auth']['id'])) {
         $msg = new Messages();
         $offset = $this->app->request->getQuery("offset");
         $limit = $this->app->request->getQuery("limit");
         $this->app->response->setJsonContent($msg->getInbox($this->app['auth']['id'], $offset, $limit));
         return $this->app->response;
     } else {
         $this->app->response->setStatusCode(401, "Unauthorized")->setJsonContent(array('status' => 'ERROR', 'data' => 'Access is not authorized'));
     }
     return $this->app->response;
 }
function test_question($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale'], '/new-question/errors');
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die($msg->_('invalid-format'), 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data)) {
            Util::output_errors_and_die($msg->_('invalid-format'), 400);
        }
        set_empty_if_undefined($input_data['type']);
        if (!Validator::validate_question_type($input_data['type'])) {
            Util::output_errors_and_die($msg->_('invalid-type'), 400);
        }
        switch ($input_data['type']) {
            case 'short-answer':
                $q = new QuestionSA($input_data, Question::FROM_USER);
                break;
            case 'essay':
                $q = new QuestionES($input_data, Question::FROM_USER);
                break;
            case 'multiple-choice':
                $q = new QuestionMC($input_data, Question::FROM_USER);
                break;
            case 'matching':
                $q = new QuestionMA($input_data, Question::FROM_USER);
                break;
            case 'fitb-type':
                $q = new QuestionFT($input_data, Question::FROM_USER);
                break;
            case 'fitb-select':
                $q = new QuestionFS($input_data, Question::FROM_USER);
                break;
            case 'source-code':
                $q = new QuestionSC($input_data, Question::FROM_USER);
                break;
        }
        http_response_code(200);
        header('Content-Type: application/json');
        echo my_json_encode($q->to_auto_marking_test(true, true));
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Example #17
0
 public static function errorMessagesList(Messages $messages, $fields)
 {
     constraint_mustBeArray($fields);
     // just in case ... if there are no errors, we have nothing
     // to do here
     if ($messages->errorCount == 0) {
         return '';
     }
     // okay, we know for sure that there are errors ... but
     // the question is how many?
     $return = '<ul class="mfErrors2">';
     foreach ($fields as $field) {
         $errors = $messages->getErrorsForField($field);
         if (count($errors) == 0) {
             // no errors for this field
             // move on to the next one
             continue;
         }
         foreach ($errors as $error) {
             $return .= '<li>' . XHTML::translation($error['module'], $error['message'], $error['params']) . '</li>';
         }
     }
     $return .= '</ul>';
     return $return;
 }
Example #18
0
 public function login()
 {
     if (Session::get('isLoggedIn')) {
         Messages::addMessage("info", "You are already logged in.");
         return;
     } else {
         $response = array();
         // params have to be there
         $user_name = $this->params->getValue('user_name');
         $user_password = $this->params->getValue('password');
         if ($user_name != null && $user_password != null) {
             // check if user name and password are correct
             $usr = $this->userManager->findUser($user_name, $user_password);
             if ($usr != null) {
                 // log user in
                 Session::set("user_name", $usr['user_name']);
                 Session::set("id", $usr['ID']);
                 Session::set("isLoggedIn", true);
                 return $usr;
             } else {
                 Messages::addMessage("info", "Log in user and/or password incorrect.");
                 return null;
             }
         } else {
             Messages::addMessage("warning", "'user_name' and/or 'password' parameters missing.");
             return null;
         }
     }
 }
 public function actionRegister()
 {
     if (!Yii::app()->user->isGuest) {
         $this->redirect(array('site/index'));
     }
     $model = new Users();
     if (isset($_POST['Users'])) {
         $model->CreatedDate = date('Y-m-d H:i:s');
         $model->UserId = $this->getRandomNumber();
         $model->ActivationCode = $this->generateRandomString(15);
         $model->attributes = $_POST['Users'];
         if ($model->save()) {
             $message = Messages::model()->mailHeader();
             $message .= '<p>Dear ' . $model->UserName . '</p>';
             $message .= 'Thank you for registering with Getweiss.com';
             $message .= '<p>Please click the link below to activate your account</p>';
             $message .= '<p><a style="color:#FFF; text-decoration:none" href="' . Yii::app()->getBaseUrl(true) . '/site/activate/?ac=' . $model->ActivationCode . '">' . Yii::app()->getBaseUrl(true) . '/site/activate/?ac=' . $model->ActivationCode . '</a></p>';
             $message .= 'Regards<br/>Getweiss.com.';
             $message .= Messages::model()->mailFooter();
             // Messages::model()->sendMail('Get Weiss', 'Activation', Yii::app()->params['adminEmail'], $model->EmailAddress, $message);
             $adminmessage = Messages::model()->mailHeader();
             $adminmessage .= 'New User Registered in Getweiss.com';
             $adminmessage .= '<p><u>Name</u>: ' . $model->UserName . '</p>';
             $adminmessage .= '<p><u>Email</u>: ' . $model->EmailAddress . '</p>';
             $adminmessage .= Messages::model()->mailFooter();
             //Messages::model()->sendMail($model->UserName, 'New User Registration', $model->EmailAddress, Yii::app()->params['adminEmail'], $adminmessage);
             $this->redirect(array('index', 'msg' => 'success'));
         }
     }
     $this->render('index', array('model' => $model));
 }
Example #20
0
 public function register()
 {
     $response = array();
     // params have to be there
     $usr = $this->params->getValue('username');
     $pwd = $this->params->getValue('password');
     $encrypt = md5($pwd);
     $fname = $this->params->getValue('firstname');
     $lname = $this->params->getValue('lastname');
     $email = $this->params->getValue('email');
     echo $usr . " " . $pwd . " " . $fname . " " . $lname . " " . $email . " " . $encrypt;
     if ($usr != null && $pwd != null && $fname != null && $lname != null && $email != null) {
         // check if user name and password are correct
         $user = $this->userManager->addUser($fname, $lname, $usr, $encrypt, $email);
         if ($user != null) {
             // log user in
             Session::set("username", $user['username']);
             Session::set("id", $user['ID']);
             Session::set("isLoggedIn", true);
             return $user;
             return $user['ID'];
             return $encrypt;
             //return $response;
         } else {
             Messages::addMessage("warning", "'user_name' and/or 'password' parameters missing.");
             return null;
             return $usr;
         }
     }
 }
Example #21
0
 function validate()
 {
     if (!Session::has('vatsimauth')) {
         throw new AuthException('Session does not exist');
     }
     $SSO = new SSO(Config::get('vatsim.base'), Config::get('vatsim.key'), Config::get('vatsim.secret'), Config::get('vatsim.method'), Config::get('vatsim.cert'));
     $session = Session::get('vatsimauth');
     if (Input::get('oauth_token') !== $session['key']) {
         throw new AuthException('Returned token does not match');
         return;
     }
     if (!Input::has('oauth_verifier')) {
         throw new AuthException('No verification code provided');
     }
     $user = $SSO->checkLogin($session['key'], $session['secret'], Input::get('oauth_verifier'));
     if ($user) {
         Session::forget('vatsimauth');
         $authUser = User::find($user->user->id);
         if (is_null($authUser)) {
             $authUser = new User();
             $authUser->vatsim_id = $user->user->id;
             $authUser->name = trim($user->user->name_first . ' ' . $user->user->name_last);
         }
         $authUser->last_login = Carbon::now();
         $authUser->save();
         Auth::login($authUser);
         Messages::success('Welcome on board, <strong>' . $authUser->name . '</strong>!');
         return Redirect::intended('/');
     } else {
         $error = $SSO->error();
         throw new AuthException($error['message']);
     }
 }
Example #22
0
 public function action_delete()
 {
     $id = $this->request->param('id');
     DB::delete('address')->where('id', '=', $id)->execute();
     Messages::save('Address was successfully deleted!', 'info');
     $this->redirect('/address');
 }
Example #23
0
 public function display()
 {
     if (Session::get('isLoggedIn')) {
         $user_name = $this->params->values('username');
         $user_password = $this->params->values('password');
         return $user_name;
         echo $user_name;
         echo json_encode($user_name);
         echo json_encode($user_pass);
         return $user_pass;
         echo $user_pass;
         //$imp = implode($user_password);
         $imp = implode($user_password);
         $encrypt = md5($imp);
         $exp = explode(" ", $encrypt);
         $usr = $this->userManager->getUserProfile($user_name, $user_password);
         //echo $user_password . " " . $user_name;
         echo json_encode($usr);
         return $this;
     } else {
         Messages::addMessage("warning", "'user_name' and/or 'password' parameters missing.");
         return null;
         return $usr;
     }
 }
Example #24
0
 /**
  * Creates new instance of Url 
  * 
  * @param string  $url        The url as string
  * @param boolean $isAbsolute Whether the given url is absolute or not
  * 
  * @throws InvalidArgumentException Exception if url is malformed
  */
 public function __construct($url, $isAbsolute = true)
 {
     if ($isAbsolute) {
         if (!preg_match(self::ABS_URL_REGEXP, $url)) {
             throw new UrlFormatException(Messages::urlMalformedUrl($url));
         }
     } else {
         if (!preg_match(self::REL_URL_REGEXP, $url)) {
             throw new UrlFormatException(Messages::urlMalformedUrl($url));
         }
     }
     $this->_parts = parse_url($url);
     if ($this->_parts === false) {
         throw new UrlFormatException(Messages::urlMalformedUrl($url));
     }
     $path = $this->getPath();
     if ($path != null) {
         $this->_segments = explode('/', trim($path, '/'));
         foreach ($this->_segments as $segment) {
             $segment = trim($segment);
             if (empty($segment)) {
                 throw new UrlFormatException(Messages::urlMalformedUrl($url));
             }
         }
     }
     $this->_urlAsString = $url;
 }
Example #25
0
 /**
  * The index action
  * 
  * @access public
  * @return void
  */
 public function action_index()
 {
     $settings = \Config::load('autoresponder.db');
     // $autoResponder = Model_Setting::find(array('where' => array(array('meta_key', '=', 'auto-responders'))));
     if (\Input::post()) {
         $input = \Input::post();
         if (!\Input::is_ajax()) {
             $val = Model_Setting::validate('create');
             if (!$val->run()) {
                 if ($val->error() != array()) {
                     // show validation errors
                     \Messages::error('<strong>There was an error while trying to create settings</strong>');
                     foreach ($val->error() as $e) {
                         \Messages::error($e->get_message());
                     }
                 }
             } else {
                 try {
                     \Config::save('autoresponder.db', array('logo_url' => $input['logo_url'], 'company_name' => $input['company_name'], 'address' => $input['address'], 'website' => $input['website'], 'phone' => $input['phone'], 'email_address' => $input['email_address'], 'sender_email_address' => $input['sender_email_address'], 'contact_us_email_address' => $input['contact_us_email_address'], 'instagram_account_name' => $input['instagram_account_name'], 'facebook_account_name' => $input['facebook_account_name']));
                     // $setting->save();
                     \Messages::success('Settings successfully created.');
                     \Response::redirect('admin/settings');
                 } catch (\Database_Exception $e) {
                     // show validation errors
                     \Messages::error('<strong>There was an error while trying to create settings.</strong>');
                     // Uncomment lines below to show database errors
                     $errors = $e->getMessage();
                     \Messages::error($errors);
                 }
             }
         }
     }
     \View::set_global('title', 'Settings');
     \Theme::instance()->set_partial('content', $this->view_dir . 'index')->set('settings', $settings, false);
 }
Example #26
0
 private function getLoginForm()
 {
     try {
         $db = Database::getInstance();
         $frontpage_info = $db->getFrontpageInfo();
     } catch (Exception $exception) {
         // in this case, render exception as error.
         return $exception;
     }
     $result = '<form action="admin.php" name="login_form" method="post"><div id="loginform">';
     if (count($frontpage_info) > 1) {
         $result .= sprintf('<label for="project_id">%s: </label>', Messages::getString('General.Project'));
         $result .= '<select name="project_id" id="project_id_selector">';
         foreach ($frontpage_info as $id => $project) {
             $result .= sprintf('<option value="%03d" %s>%s&nbsp;&nbsp;</option>', $id, $id == Config::$default_project_id ? 'selected="selected"' : '', $project->name);
         }
         $result .= '</select><br/>';
     } else {
         foreach ($frontpage_info as $id => $project) {
             $result .= sprintf('<input type="hidden" name="project_id" value="%03d" />', $id);
         }
     }
     $result .= sprintf('<label for="password">%s: </label>', Messages::getString('LoginPage.EnterPassword')) . '  <input type="password" name="pwd" value="" /> ' . '  <input type="submit" value="Login" />' . '</div></form>&nbsp;';
     return $result;
 }
 protected function renderNotes()
 {
     $this->writeJavascript('var current_key = 0; var max_key = 0; var crypt_module = "";' . 'function clickRunButton() {' . '    if (current_key == 0) {' . '      max_key = parseInt(document.keygen_form.key_count.value,0);' . '      if (isNaN(max_key) || max_key == 0) { ' . sprintf('          alert("%s");', Messages::getString('GenerateKeysPage.EnterNumberBiggerZero')) . '          document.keygen_form.key_count.focus();' . '          return;' . '      }' . '      crypt_module = document.keygen_form.crypt_module[document.keygen_form.crypt_module.selectedIndex].value;' . sprintf('      document.keygen_form.run_button.value="%s";', Messages::getString('General.Cancel')) . sprintf('      document.getElementById("key_output").innerHTML = "<form action=\\"' . $this->KEY_PDF_PHP . '\\" method=\\"POST\\" target=\\"_blank\\"><table id=\\"key_output_table\\"><tbody id=\\"key_output_table_body\\"><tr><th class=\\"out\\">%s</th><th class=\\"out\\">%s</th></tr></tbody></table><input type=\\"submit\\" value=\\"%s\\" /><input type=\\"hidden\\" name=\\"ext\\" value=\\".pdf\\" /></form>&nbsp;";', Messages::getString('General.RKey'), Messages::getString('General.Password'), Messages::getString('GenerateKeysPage.GeneratePdf')) . '      generate();' . '    } else { ' . '      stop();' . '    }' . '}' . 'function generate() {' . '    current_key++;' . '    if (current_key > max_key) { stop(); return; }' . sprintf('    document.keygen_form.run_button.value="%s";', Messages::getString('General.Cancel')) . '    keygen_frame.location.href = "' . $this->GEN_KEY_PHP . '?crypt=" + escape(crypt_module) + "&current=" + current_key + "&max=" + max_key;' . '}' . 'function store_result(reson_key,password) {' . '   add_table_line(reson_key,password);' . '       window.setTimeout("generate()", 10);' . '}' . 'function stop() {' . '    current_key = 0;' . '    max_key = 0;' . sprintf('    document.keygen_form.run_button.value="%s";', Messages::getString('General.Run')) . '}' . 'function add_table_line(key,pwd) {' . '    table = document.getElementById("key_output_table_body");' . '    newTR = document.createElement("tr");' . '    table.appendChild(newTR);' . '    newTD = document.createElement("td");' . '    newTD.setAttribute("class","out");' . '    newTR.appendChild(newTD);' . '    text = document.createTextNode(key);' . '    newTD.appendChild(text);' . '    inp = document.createElement("input");' . '    inp.setAttribute("type","hidden");' . '    inp.setAttribute("name","key[]");' . '    inp.setAttribute("value",key);' . '    newTD.appendChild(inp);' . '    newTD = document.createElement("td");' . '    newTD.setAttribute("class","out");' . '    newTR.appendChild(newTD);' . '    text = document.createTextNode(pwd);' . '    newTD.appendChild(text);' . '    inp = document.createElement("input");' . '    inp.setAttribute("type","hidden");' . '    inp.setAttribute("name","pwd[]");' . '    inp.setAttribute("value",pwd);' . '    newTD.appendChild(inp);' . '}');
     $note = '<form name="keygen_form" onsubmit="clickRunButton(); return false;">' . sprintf('%s: <input type="text" name="key_count" value="1" size="5" />', Messages::getString('GenerateKeysPage.NumberOfKeys')) . sprintf('&nbsp;<input type="button" name="run_button" value="%s" onclick="clickRunButton();" />', Messages::getString('General.Run')) . '<br />' . sprintf('%s: %s', Messages::getString('GenerateKeysPage.EncryptionModule'), $this->getCryptSelect()) . '</form>' . sprintf('<iframe src="%s" name="keygen_frame" id="keygen_frame" scrolling="no" frameborder="0">%s</iframe><br />', $this->GEN_KEY_PHP, Messages::getString('GenerateKeysPage.NoKeyGeneration'));
     $this->renderNote($note, Messages::getString('GenerateKeysPage.RKeyGeneration'));
     $this->renderNote(sprintf('<div id="key_output" style="text-align:center">%s</div>', Messages::getString('General.None')), Messages::getString('GenerateKeysPage.NewRKeys'));
 }
Example #28
0
 /**
  * Singeltone Get Instance
  *
  * @return Messages
  */
 public static function getInstance()
 {
     if (!self::$instance) {
         self::$instance = new self();
     }
     return self::$instance;
 }
    /**
     * Before action load knight data of user
     * @param unknown_type $action
     */
    public function beforeAction($action)
    {
        //Load user's knight data
        if (!Yii::app()->user->isGuest) {
            $this->user_data['knights'] = Knights::model()->with('knightsCard', 'knightsStats')->find('id=:id', array(':id' => Yii::app()->user->knights_id));
            $this->user_data['knights_card'] =& $this->user_data['knights']->knightsCard;
            //Load stats of knight
            $this->user_data['knights_stats'] =& $this->user_data['knights']->knightsStats;
            //Load if user has new friendship request
            $sql = 'SELECT friends.id as id, k1.name as name, k1.avatars_id as avatars_id FROM friends
					INNER JOIN users ON users.id = friends.from_user
					INNER JOIN knights as k1 ON k1.users_id = users.id
					WHERE friends.status = :status AND to_user = :users_knights_id1
					ORDER BY start_date DESC';
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(':status', Friends::STATUS_ONWAITING, PDO::PARAM_INT);
            $command->bindValue(':users_knights_id1', $this->user_data['knights']->id, PDO::PARAM_INT);
            $this->user_data['knights_new_friends'] = $command->queryAll();
            //Load last messages
            $this->user_data['new_messages'] = Messages::getNewMessages(Yii::app()->user->users_id);
            //Load all attributes name attributes
            $this->app_data['attribute_list'] = Constants::model()->findAll('type=:type', array(':type' => Constants::KNIGHTS_ATTRIBUTES));
        }
        return true;
    }
Example #30
0
 public function action_index()
 {
     $code = $this->request->param('code');
     if ($code === NULL) {
         Model_Page_Front::not_found();
     }
     $reflink_model = ORM::factory('user_reflink', $code);
     if (!$reflink_model->loaded()) {
         Messages::errors(__('Reflink not found'));
         $this->go_home();
     }
     $next_url = Arr::get($reflink_model->data, 'next_url');
     try {
         Database::instance()->begin();
         Reflink::factory($reflink_model)->confirm();
         $reflink_model->delete();
         Database::instance()->commit();
     } catch (Kohana_Exception $e) {
         Database::instance()->rollback();
         Messages::errors($e->getMessage());
     }
     if (Valid::url($next_url)) {
         $this->go($next_url);
     }
     $this->go_home();
 }