Ejemplo n.º 1
0
 public function submit($problem_id)
 {
     try {
         $problem = new Problem($problem_id);
         $language = fRequest::get('language', 'integer');
         if (!array_key_exists($language, static::$languages)) {
             throw new fValidationException('Invalid language.');
         }
         fSession::set('last_language', $language);
         $code = trim(fRequest::get('code', 'string'));
         if (strlen($code) == 0) {
             throw new fValidationException('Code cannot be empty.');
         }
         if ($problem->isSecretNow()) {
             if (!User::can('view-any-problem')) {
                 throw new fAuthorizationException('Problem is secret now. You are not allowed to submit this problem.');
             }
         }
         $record = new Record();
         $record->setOwner(fAuthorization::getUserToken());
         $record->setProblemId($problem->getId());
         $record->setSubmitCode($code);
         $record->setCodeLanguage($language);
         $record->setSubmitDatetime(Util::currentTime());
         $record->setJudgeStatus(JudgeStatus::PENDING);
         $record->setJudgeMessage('Judging... PROB=' . $problem->getId() . ' LANG=' . static::$languages[$language]);
         $record->setVerdict(Verdict::UNKNOWN);
         $record->store();
         Util::redirect('/status');
     } catch (fException $e) {
         fMessaging::create('error', $e->getMessage());
         fMessaging::create('code', '/submit', fRequest::get('code', 'string'));
         Util::redirect("/submit?problem={$problem_id}");
     }
 }
Ejemplo n.º 2
0
 public function show()
 {
     $this->editable = UserHelper::isEditor();
     $cons = array();
     $field = trim(fRequest::get('field'));
     $start_year = trim(fRequest::get('start_year'));
     $major = trim(fRequest::get('major'));
     $location = trim(fRequest::get('location'));
     $words = trim(fRequest::get('words'));
     $cons['login_name|display_name~'] = $words;
     if (!empty($field)) {
         $cons['field='] = $field;
     }
     if (!empty($start_year)) {
         $cons['start_year='] = $start_year;
     }
     if (!empty($major)) {
         $cons['major='] = $major;
     }
     if (!empty($location)) {
         $cons['location~'] = $location;
     }
     $this->users = fRecordSet::build('Profile', $cons, array('id' => 'asc'));
     $this->field = $field;
     $this->start_year = $start_year;
     $this->major = $major;
     $this->location = $location;
     $this->words = $words;
     $this->render('search/index');
 }
Ejemplo n.º 3
0
 /**
  * Crop image file and set coordinates
  */
 public function update()
 {
     $x = fRequest::get('x', 'integer');
     $y = fRequest::get('y', 'integer');
     $w = fRequest::get('w', 'integer');
     $h = fRequest::get('h', 'integer');
     $img_w = fRequest::get('img_w', 'integer');
     $img_h = fRequest::get('img_h', 'integer');
     try {
         // throw new Exception(sprintf('x=%d,y=%d,w=%d,h=%d,img_w=%d,img_h=%d', $x, $y, $w, $h, $img_w, $img_h));
         $img_r = imagecreatefromjpeg($this->uploadfile);
         $x = $x * imagesx($img_r) / $img_w;
         $y = $y * imagesy($img_r) / $img_h;
         $w = $w * imagesx($img_r) / $img_w;
         $h = $h * imagesy($img_r) / $img_h;
         $dst_r = imageCreateTrueColor($this->target_width, $this->target_height);
         imagecopyresampled($dst_r, $img_r, 0, 0, $x, $y, $this->target_width, $this->target_height, $w, $h);
         imagejpeg($dst_r, $this->avatarfile, $this->jpeg_quality);
         $dst_r = imageCreateTrueColor($this->mini_width, $this->mini_height);
         imagecopyresampled($dst_r, $img_r, 0, 0, $x, $y, $this->mini_width, $this->mini_height, $w, $h);
         imagejpeg($dst_r, $this->minifile, $this->jpeg_quality);
         Activity::fireUpdateAvatar();
         $this->ajaxReturn(array('result' => 'success'));
     } catch (Exception $e) {
         $this->ajaxReturn(array('result' => 'failure', 'message' => $e->getMessage()));
     }
 }
Ejemplo n.º 4
0
 public function updateJudgeStatus()
 {
     try {
         $op = strtolower(trim(fRequest::get('status', 'string')));
         $judge_message = base64_decode(fRequest::get('judgeMessage', 'string'));
         $verdict = fRequest::get('verdict', 'integer');
         $id = fRequest::get('id', 'integer');
         $r = new Record($id);
         if ($op == 'running') {
             $r->setJudgeStatus(JudgeStatus::RUNNING);
             $r->setJudgeMessage($r->getJudgeMessage() . "\n{$judge_message}");
             $r->store();
         } else {
             if ($op == 'done') {
                 $r->setJudgeStatus(JudgeStatus::DONE);
                 if (!empty($judge_message)) {
                     $r->setJudgeMessage($judge_message);
                 }
                 $r->setVerdict($verdict);
                 $r->store();
             }
         }
         echo "{$op}\n";
         echo "{$judge_message}\n";
         echo "{$verdict}\n";
         echo "{$id}\n";
     } catch (fException $e) {
         echo -1;
     }
 }
Ejemplo n.º 5
0
 public function create()
 {
     try {
         $profileId = UserHelper::getProfileId();
         $msg = new Msg();
         $msg->setSender($profileId);
         $msg->setContent(trim(fRequest::get('msg-content')));
         $re = trim(fRequest::get('dest', 'integer'));
         $x = new Profile($re);
         $msg->setReceiver($re);
         if (strlen($msg->getContent()) < 1) {
             throw new fValidationException('信息长度不能少于1个字符');
         }
         if (strlen($msg->getContent()) > 140) {
             throw new fValidationException('信息长度不能超过140个字符');
         }
         $msg->store();
         //Activity::fireNewTweet();
         fMessaging::create('success', 'create msg', '留言成功!');
     } catch (fNotFoundException $e) {
         fMessaging::create('failure', 'create msg', '该用户名不存在!');
     } catch (fException $e) {
         fMessaging::create('failure', 'create msg', $e->getMessage());
     }
     fURL::redirect(SITE_BASE . '/profile/' . $re . '/msgs');
 }
Ejemplo n.º 6
0
 /**
  * Process action on page load
  */
 public function loadPassingsPage()
 {
     $table = $this->createPassingTableOnce();
     if (!fRequest::check('passing_id')) {
         return;
     }
     $this->processAction($table->current_action(), fRequest::get('passing_id', 'array'));
 }
Ejemplo n.º 7
0
 public function update($id)
 {
     try {
         $users = new Name($id);
         if (!UserHelper::isEditor()) {
             throw new fValidationException('not allowed');
         }
         $users->setStudentNumber(fRequest::get('stuid'));
         $users->setRealname(fRequest::get('realname'));
         $users->store();
         $this->ajaxReturn(array('result' => 'success', 'user_id' => $users->getId()));
     } catch (fException $e) {
         $this->ajaxReturn(array('result' => 'failure', 'message' => $e->getMessage()));
     }
 }
Ejemplo n.º 8
0
 public function reply($id)
 {
     try {
         $tweet = new Tweet($id);
         $comment = new TweetComment();
         $comment->setTweetId($tweet->getId());
         $comment->setProfileId(UserHelper::getProfileId());
         $comment->setContent(trim(fRequest::get('tweet-comment')));
         if (strlen($comment->getContent()) < 1) {
             throw new fValidationException('回复长度不能少于1个字符');
         }
         if (strlen($comment->getContent()) > 140) {
             throw new fValidationException('回复长度不能超过140个字符');
         }
         $comment->store();
     } catch (fException $e) {
         // TODO
     }
     fURL::redirect(SITE_BASE . '/profile/' . $tweet->getProfileId() . '#tweet/' . $tweet->getId());
 }
Ejemplo n.º 9
0
 public function index()
 {
     if (fAuthorization::checkLoggedIn()) {
         $this->cache_control('private', 2);
     } else {
         $this->cache_control('private', 5);
     }
     $top = fRequest::get('top', 'integer');
     $this->owner = trim(fRequest::get('owner'));
     $this->problem_id = trim(fRequest::get('problem'));
     $this->language = trim(fRequest::get('language'));
     $this->verdict = trim(fRequest::get('verdict'));
     $this->page = fRequest::get('page', 'integer', 1);
     $this->records = Record::find($top, $this->owner, $this->problem_id, $this->language, $this->verdict, $this->page);
     $this->page_records = $this->records;
     $common_url = SITE_BASE . "/status?owner={$this->owner}&problem={$this->problem_id}&language={$this->language}&verdict={$this->verdict}";
     $this->top_url = "{$common_url}&top=";
     $this->page_url = "{$common_url}&page=";
     $this->nav_class = 'status';
     $this->render('record/index');
 }
Ejemplo n.º 10
0
 public function create()
 {
     try {
         $profileId = UserHelper::getProfileId();
         $mail = new Mail();
         $mail->setSender($profileId);
         $mail->setContent(trim(fRequest::get('mail-content')));
         $re = trim(fRequest::get('dest'));
         if (empty($re)) {
             $re = trim(fRequest::get('destre', 'integer'));
             $pa = trim(fRequest::get('parent', 'integer', -1));
             $x = new Profile($re);
             $mail->setReceiver($re);
             $mail->setParent($pa);
         } else {
             //$receiver=fRecordSet::build('Profile',array('login_name=' => $re ),array())->getRecord(0);
             $receiver = fRecordSet::build('Profile', array('login_name=' => $re), array());
             if ($receiver->count()) {
                 $receiver = $receiver->getRecord(0);
             } else {
                 throw new fNotFoundException('user doesn\'t exist');
             }
             $mail->setReceiver($receiver->getId());
         }
         if (strlen($mail->getContent()) < 1) {
             throw new fValidationException('信息长度不能少于1个字符');
         }
         if (strlen($mail->getContent()) > 140) {
             throw new fValidationException('信息长度不能超过140个字符');
         }
         $mail->store();
         //Activity::fireNewTweet();
         fMessaging::create('success', 'create mail', '信息发送成功!');
     } catch (fNotFoundException $e) {
         fMessaging::create('failure', 'create mail', '该用户名不存在,或该用户没有创建个人资料!');
     } catch (fException $e) {
         fMessaging::create('failure', 'create mail', $e->getMessage());
     }
     fURL::redirect(SITE_BASE . '/inbox');
 }
Ejemplo n.º 11
0
 public function index()
 {
     $this->cache_control('private', 5);
     if ($pid = fRequest::get('id', 'integer')) {
         Util::redirect('/problem/' . $pid);
     }
     $view_any = User::can('view-any-problem');
     $this->page = fRequest::get('page', 'integer', 1);
     $this->title = trim(fRequest::get('title', 'string'));
     $this->author = trim(fRequest::get('author', 'string'));
     $this->problems = Problem::find($view_any, $this->page, $this->title, $this->author);
     $this->page_url = SITE_BASE . '/problems?';
     if (!empty($this->title)) {
         $this->page_url .= 'title=' . fHTML::encode($this->title) . '&';
     }
     if (!empty($this->author)) {
         $this->page_url .= 'author=' . fHTML::encode($this->author) . '&';
     }
     $this->page_url .= 'page=';
     $this->page_records = $this->problems;
     $this->nav_class = 'problems';
     $this->render('problem/index');
 }
Ejemplo n.º 12
0
    // Get manufacturers also for drop-down box
    #$manufacturers = fRecordSet::build('Manufacturer', NULL, array('name' => 'asc'));
    // Get list of models
    $models = Model::getSimple($db);
    // Get types
    if (feature('consumable_types')) {
        $types = Tag::get_by_type('consumable_type');
    }
    include 'views/consumables/addedit.php';
}
/**
 * Delete a consumable
 */
if ($action == 'delete') {
    // Get ID
    $id = fRequest::get('id', 'integer');
    try {
        $c = new Consumable($id);
        if (fRequest::isPost()) {
            $c->delete();
            fMessaging::create('success', fURL::get(), 'The consumable ' . $c->getName() . ' was successfully deleted.');
            fURL::redirect(fURL::get());
        }
    } catch (fNotFoundException $e) {
        fMessaging::create('error', fURL::get(), 'The consumable requested, ID ' . $id . ', could not be found.');
        fURL::redirect($manage_url);
    } catch (fExpectedException $e) {
        fMessaging::create('error', fURL::get(), $e->getMessage());
    } catch (fSQLException $e) {
        fMessaging::create('error', fURL::get(), 'Database error: ' . $e->getMessage());
    }
Ejemplo n.º 13
0
$tmpl->set('title', 'Log In');
$tmpl->set('no-nav', true);
$tmpl->place('header');
?>
   <form action="<?php 
echo fURL::get() . '?action=log_in';
?>
" method="post">
     <div class="main" id="main">
       <fieldset>
         <div class="clearfix">
           <label for="username">Username</label>
           <div class="input">
             <input id="username" type="text" name="username" value="<?php 
echo fRequest::get('username');
?>
" />
           </div>
         </div><!-- /clearfix -->
         <div class="clearfix">
           <label for="password">Password</label>
           <div class="input">
             <input id="password" type="password" name="password" value="" />
           </div>
         </div><!-- /clearfix -->
         <div class="actions">       
           <input class="btn" type="submit" value="Log In" />
           <a class="btn" href="<?php 
echo User::makeUrl('add');
?>
Ejemplo n.º 14
0
        fRequest::validateCSRFToken($_POST['token']);
        $validator = new fValidation();
        $validator->addRequiredFields('password', 'email');
        $validator->addEmailFields('email');
        $validator->validate();
        $users = fRecordSet::build('User', array('email=' => strtolower($_POST['email'])));
        if ($users->count() == 0) {
            throw new fValidationException('Invalid username or password.');
        }
        $rec = $users->getRecords();
        $user = $rec[0];
        if (!fCryptography::checkPasswordHash($_POST['password'], $user->getPassword())) {
            throw new fValidationException('Invalid username or password.');
        }
        fSession::set('user', $user->getId());
        if (fRequest::get('persistent_login', 'boolean')) {
            fSession::enablePersistence();
        }
        if (isset($_POST['forward'])) {
            fURL::redirect('http://' . $_SERVER['SERVER_NAME'] . $_POST['forward']);
        } else {
            fURL::redirect('/members');
        }
        exit;
    } catch (fValidationException $e) {
        echo "<p>" . $e->printMessage() . "</p>";
    } catch (fSQLException $e) {
        echo "<p>An unexpected error occurred, please try again later</p>";
        trigger_error($e);
    }
}
Ejemplo n.º 15
0
    include VIEW_PATH . '/add_edit_user.php';
} elseif ('settings' == $action) {
    $user = new User($user_id);
    if (fRequest::isPost()) {
        try {
            $user->populate();
        } catch (fExpectedException $e) {
            fMessaging::create('error', fURL::get(), $e - getMessage());
        }
    }
    include VIEW_PATH . '/add_edit_user_settings.php';
} elseif ('delete' == $action) {
    try {
        $user = new User($user_id);
        if (fRequest::isPost()) {
            fRequest::validateCSRFToken(fRequest::get('token'));
            $user->delete();
            fMessaging::create('success', User::makeUrl('edit', $user), 'The user ' . $user->getName() . ' was successfully deleted');
            fURL::redirect(User::makeUrl('edit', $user));
        }
    } catch (fNotFoundException $e) {
        fMessaging::create('error', User::makeUrl('edit', $user), 'The line requested could not be found');
        fURL::redirect(User::makeUrl('edit', $user));
    } catch (fExpectedException $e) {
        fMessaging::create('error', fURL::get(), $e->getMessage());
    }
    include VIEW_PATH . '/delete.php';
} else {
    if (!fAuthorization::checkAuthLevel('admin')) {
        fURL::redirect(User::makeURL('edit', fSession::get('user_id')));
    } else {
Ejemplo n.º 16
0
 /**
  * Uploads a file
  * 
  * @internal
  * 
  * @param  fActiveRecord $object            The fActiveRecord instance
  * @param  array         &$values           The current values
  * @param  array         &$old_values       The old values
  * @param  array         &$related_records  Any records related to this record
  * @param  array         &$cache            The cache array for the record
  * @param  string        $method_name       The method that was called
  * @param  array         $parameters        The parameters passed to the method
  * @return fFile  The uploaded file
  */
 public static function upload($object, &$values, &$old_values, &$related_records, &$cache, $method_name, $parameters)
 {
     $class = get_class($object);
     list($action, $column) = fORM::parseMethod($method_name);
     $existing_temp_file = FALSE;
     // Try to upload the file putting it in the temp dir incase there is a validation problem with the record
     try {
         $upload_dir = self::$file_upload_columns[$class][$column];
         $temp_dir = self::prepareTempDir($upload_dir);
         if (!fUpload::check($column)) {
             throw new fExpectedException('Please upload a file');
         }
         $uploader = self::setUpFUpload($class, $column);
         $file = $uploader->move($temp_dir, $column);
         // If there was an eror, check to see if we have an existing file
     } catch (fExpectedException $e) {
         // If there is an existing file and none was uploaded, substitute the existing file
         $existing_file = fRequest::get('existing-' . $column);
         $delete_file = fRequest::get('delete-' . $column, 'boolean');
         $no_upload = $e->getMessage() == self::compose('Please upload a file');
         if ($existing_file && $delete_file && $no_upload) {
             $file = NULL;
         } elseif ($existing_file) {
             $file_path = $upload_dir->getPath() . $existing_file;
             $file = fFilesystem::createObject($file_path);
             $current_file = $values[$column];
             // If the existing file is the same as the current file, we can just exit now
             if ($current_file && $file->getPath() == $current_file->getPath()) {
                 return;
             }
             $existing_temp_file = TRUE;
         } else {
             $file = NULL;
         }
     }
     // Assign the file
     fActiveRecord::assign($values, $old_values, $column, $file);
     // Perform the file upload inheritance
     if (!empty(self::$column_inheritence[$class][$column])) {
         foreach (self::$column_inheritence[$class][$column] as $other_column) {
             if ($file) {
                 // Image columns will only inherit if it is an fImage object
                 if (!$file instanceof fImage && isset(self::$image_upload_columns[$class][$other_column])) {
                     continue;
                 }
                 $other_upload_dir = self::$file_upload_columns[$class][$other_column];
                 $other_temp_dir = self::prepareTempDir($other_upload_dir);
                 if ($existing_temp_file) {
                     $other_file = fFilesystem::createObject($other_temp_dir->getPath() . $file->getName());
                 } else {
                     $other_file = $file->duplicate($other_temp_dir, FALSE);
                 }
             } else {
                 $other_file = $file;
             }
             fActiveRecord::assign($values, $old_values, $other_column, $other_file);
             if (!$existing_temp_file && $other_file) {
                 self::processImage($class, $other_column, $other_file);
             }
         }
     }
     // Process the file
     if (!$existing_temp_file && $file) {
         self::processImage($class, $column, $file);
     }
     return $file;
 }
Ejemplo n.º 17
0
<?php

include '../inc/init.php';
$term = fRequest::get('term', 'string');
if ($GLOBALS['PRIMARY_SOURCE'] == 'GANGLIA') {
    if ($GLOBALS['GANGLIA_URL'] != '') {
        $json = file_get_contents($GLOBALS['GANGLIA_URL'] . '/tattle_autocomplete.php?term=' . $term);
        print $json;
    }
} else {
    $path = str_replace('.', '/', fRequest::get('term', 'string'));
    $return_arr = array();
    if ($GLOBALS['GRAPHITE_AUTOCOMPLETE_RECURSIVE'] == true) {
        $dir = new fDirectory($GLOBALS['WHISPER_DIR']);
        $directories = $dir->scanRecursive($path . '*');
    } else {
        $searchPattern = "*";
        if (!file_exists($GLOBALS['WHISPER_DIR'] . $path)) {
            $dirParts = explode("/", $path);
            $searchPattern = array_pop($dirParts) . $searchPattern;
            $path = implode("/", $dirParts);
        }
        $dir = new fDirectory($GLOBALS['WHISPER_DIR'] . $path);
        $directories = $dir->scan($searchPattern);
    }
    foreach ($directories as $directory) {
        $return_arr[] = array('value' => str_replace('.wsp', '', str_replace('/', '.', str_replace($GLOBALS['WHISPER_DIR'], '', $directory->getPath()))));
    }
    print json_encode($return_arr);
}
Ejemplo n.º 18
0
 /**
  * Gets the current value of a search field
  *
  * If a value is an empty string and no cast to is specified, the value will
  * become `NULL`.
  *
  * If a query string of `?reset` is passed, all previous search values will
  * be erased.
  *
  * @param  string $column   The column that is being pulled back
  * @param  string $cast_to  The data type to cast to
  * @param  string $default  The default value
  * @return mixed  The current value
  */
 public static function getSearchValue($column, $cast_to = NULL, $default = NULL)
 {
     // Reset values if requested
     if (self::wasResetRequested()) {
         self::setPreviousSearchValue($column, NULL);
         return;
     }
     if (self::getPreviousSearchValue($column) && !fRequest::check($column)) {
         self::$search_values[$column] = self::getPreviousSearchValue($column);
         self::$loaded_values[$column] = self::$search_values[$column];
     } else {
         self::$search_values[$column] = fRequest::get($column, $cast_to, $default);
         self::setPreviousSearchValue($column, self::$search_values[$column]);
     }
     return self::$search_values[$column];
 }
Ejemplo n.º 19
0
 /**
  * Validates one-to-* related records
  *
  * @param  string $class             The class to validate the related records for
  * @param  array  &$values           The values for the object
  * @param  array  &$related_records  The related records for the object
  * @param  string $related_class     The name of the class for this record set
  * @param  string $route             The route between the table and related table
  * @return array  An array of validation messages
  */
 private static function validateOneToStar($class, &$values, &$related_records, $related_class, $route)
 {
     $schema = fORMSchema::retrieve($class);
     $table = fORM::tablize($class);
     $related_table = fORM::tablize($related_class);
     $relationship = fORMSchema::getRoute($schema, $table, $related_table, $route);
     $first_pk_column = self::determineFirstPKColumn($class, $related_class, $route);
     $filter = self::determineRequestFilter($class, $related_class, $route);
     $pk_field = $filter . $first_pk_column;
     $input_keys = array_keys(fRequest::get($pk_field, 'array', array()));
     $related_record_name = self::getRelatedRecordName($class, $related_class, $route);
     $messages = array();
     $one_to_one = fORMSchema::isOneToOne($schema, $table, $related_table, $route);
     if ($one_to_one) {
         $records = array(self::createRecord($class, $values, $related_records, $related_class, $route));
     } else {
         $records = self::buildRecords($class, $values, $related_records, $related_class, $route);
     }
     foreach ($records as $i => $record) {
         fRequest::filter($filter, isset($input_keys[$i]) ? $input_keys[$i] : $i);
         $record_messages = $record->validate(TRUE);
         foreach ($record_messages as $column => $record_message) {
             // Ignore validation messages about the primary key since it will be added
             if ($column == $relationship['related_column']) {
                 continue;
             }
             if ($one_to_one) {
                 $token_field = fValidationException::formatField('__TOKEN__');
                 $extract_message_regex = '#' . str_replace('__TOKEN__', '(.*?)', preg_quote($token_field, '#')) . '(.*)$#D';
                 preg_match($extract_message_regex, $record_message, $matches);
                 $column_name = self::compose('%1$s %2$s', $related_record_name, $matches[1]);
                 $messages[$related_table . '::' . $column] = self::compose('%1$s%2$s', fValidationException::formatField($column_name), $matches[2]);
             } else {
                 $main_key = $related_table . '[' . $i . ']';
                 if (!isset($messages[$main_key])) {
                     if (isset(self::$validation_name_methods[$class][$related_class][$route])) {
                         $name = $record->{self::$validation_name_methods[$class][$related_class][$route]}($i + 1);
                     } else {
                         $name = $related_record_name . ' #' . ($i + 1);
                     }
                     $messages[$main_key] = array('name' => $name, 'errors' => array());
                 }
                 $messages[$main_key]['errors'][$column] = $record_message;
             }
         }
         fRequest::unfilter();
     }
     return $messages;
 }
Ejemplo n.º 20
0
 /**
  * Runs all valid-values rules
  * 
  * @param  array &$messages  The messages to display to the user
  * @return void
  */
 private function checkValidValuesRules(&$messages)
 {
     foreach ($this->valid_values_rules as $field => $valid_values) {
         $value = fRequest::get($field);
         if (self::stringlike($value) && !in_array($value, $valid_values, TRUE)) {
             $messages[$field] = self::compose('%1$sPlease choose from one of the following: %2$s', fValidationException::formatField($this->makeFieldName($field)), $this->joinRecursive(', ', $valid_values));
         }
     }
 }
Ejemplo n.º 21
0
                    foreach ($subscriptions as $sub) {
                        $user_id = $sub['user_id'];
                        if (!in_array($user_id, $alt_ids) && $user_id != $id_user_session) {
                            $user = new User($sub['user_id']);
                            $recipients[] = array("mail" => $user->getEmail(), "name" => $user->getUsername());
                        }
                    }
                    if (!empty($recipients)) {
                        // Send the mail to everybody
                        notify_multiple_users($user_session, $recipients, $subject_mail, $content_mail);
                        fMessaging::create('success', fURL::get(), 'The mail "' . $subject_mail . '" was successfully sent to all the users who subscribe to "' . $check->getName() . '"');
                    } else {
                        fMessaging::create('error', fURL::get(), "Nobody subscribe to this check");
                    }
                }
            }
        } catch (fNotFoundException $e) {
            fMessaging::create('error', $manage_url, 'The check requested, ' . fHTML::encode($check_id) . ', could not be found');
            fURL::redirect($manage_url);
        } catch (fExpectedException $e) {
            fMessaging::create('error', fURL::get(), $e->getMessage());
        }
        $page_num = fRequest::get('page', 'int', 1);
        $url_redirect = CheckResult::makeURL('list', $check) . "&page=" . $page_num;
        fURL::redirect($url_redirect);
    } else {
        $page_num = fRequest::get('page', 'int', 1);
        $check_results = CheckResult::findAll($check_id, false, $GLOBALS['PAGE_SIZE'], $page_num);
        include VIEW_PATH . '/list_check_results.php';
    }
}
Ejemplo n.º 22
0
        header('Location: ' . SITE);
        exit("No se ha podido acceder a esta secci&oacite;n");
    }
}
//echo  fRequest::encode('id_zone','integer');
//echo  fRequest::encode('id_section','integer');
/*
 * Add Article
 */
$banner = new Banner();
$banner->setId_zone(fRequest::encode('id_zone', 'integer'));
$banner->setLink(fRequest::encode('link', 'string'));
$banner->setOrder(fRequest::encode('order', 'integer'));
$banner->setId_section(fRequest::encode('id_section', 'integer'));
/* Limited By User Permissions */
$banner->setStatus(fRequest::get('id_state', 'integer'));
try {
    $banner->store();
} catch (Exception $e) {
    exit("Ha ocurrido un error.");
}
$lastId = $banner->prepareIdBanner();
/*
 * Add Region 
 * Limited By User Permissions
 */
/*
 * Add Files to Server
 */
if (!empty($_FILES)) {
    $uploader = new fUpload();
Ejemplo n.º 23
0
 /**
  * Sets the values for this record by getting values from the request through the fRequest class
  * 
  * @return fActiveRecord  The record object, to allow for method chaining
  */
 public function populate()
 {
     $class = get_class($this);
     if (fORM::getActiveRecordMethod($class, 'populate')) {
         return $this->__call('populate', array());
     }
     fORM::callHookCallbacks($this, 'pre::populate()', $this->values, $this->old_values, $this->related_records, $this->cache);
     $schema = fORMSchema::retrieve($class);
     $table = fORM::tablize($class);
     $column_info = $schema->getColumnInfo($table);
     foreach ($column_info as $column => $info) {
         if (fRequest::check($column)) {
             $method = 'set' . fGrammar::camelize($column, TRUE);
             $cast_to = $info['type'] == 'blob' ? 'binary' : NULL;
             $this->{$method}(fRequest::get($column, $cast_to));
         }
     }
     fORM::callHookCallbacks($this, 'post::populate()', $this->values, $this->old_values, $this->related_records, $this->cache);
     return $this;
 }
Ejemplo n.º 24
0
<?php

define('TATTLE_ROOT', '../..');
define('JS_CACHE', TATTLE_ROOT . '/js_cache/');
include '../includes.php';
include TATTLE_ROOT . '/inc/functions.php';
include TATTLE_ROOT . '/inc/config.php';
$filter_text = fRequest::get('filter_text', 'string');
if (!isset($filter_group_id)) {
    $filter_group_id = fRequest::get('filter_group_id', 'integer');
    if (empty($filter_group_id) || $filter_group_id < 0) {
        $filter_group_id = -1;
    }
}
?>
<script type="text/javascript">
    $('.badge').tooltip();
    var filter = $("#filter_text").val();
    var reg = new RegExp(filter, "i");
    $("#filtered_dashboards .description").each(function() {
        if (filter != '') {
            if ($(this).html().match(reg) != null) {
                $(this).addClass('success');
            } else {
                $(this).removeClass('success');
            }
        }
    });

    $("#filtered_dashboards .name a").each(function() {
        if (filter != '') {
Ejemplo n.º 25
0
<?php

include_once 'inc/init.php';
$debug = false;
if (isset($_SERVER['argc'])) {
    $args = getopt('d::h::', array('debug', 'help'));
    if (isset($args['debug']) || isset($args['d'])) {
        $debug = true;
    } elseif (isset($args['help']) || isset($args['h'])) {
        print "Tattle Check Processor: \n" . "\n" . "--help, -h : Displays this help \n" . "\n" . "--debug, -d : Enables debuging (?debug=true can be used via a web request) \n";
    }
} elseif ($debug = fRequest::get('debug', 'boolean')) {
    $debug = true;
}
if ($debug) {
    print "debug enabled";
    fCore::enableDebugging(TRUE);
}
$checks = Check::findActive();
foreach ($checks as $check) {
    $data = Check::getData($check);
    if (count($data) > 0) {
        $title = $check->prepareName();
        fCore::debug('Processing :' . $title . ":\n", FALSE);
        $check_value = Check::getResultValue($data, $check);
        fCore::debug("Result :" . $check_value . ":\n", FALSE);
        $result = Check::setResultsLevel($check_value, $check);
        fCore::debug("Check Value:" . $result . ":\n", FALSE);
        if (is_null($check->getLastCheckTime())) {
            $next_check = new fTimestamp();
            fCore::debug("is null?\n", FALSE);
Ejemplo n.º 26
0
 /**
  * Processes a form and produces output dependent upon the context in which process() is called.
  *
  * If the form is not being submitted, then it will be rendered in its initial state using the ->value() you set on each
  * element and showing placeholders if set (how these are shown depends on the renderer too.)
  *
  * If the form is being submitted, then it will validate the inputs using any supplied rules and finally validate the form
  * as a whole unit. You can supply validation rules or even callbacks for any element or the whole form.
  *
  * If the validation fails, the form will be re-rendered with the previous input values and with the errors shown.
  *
  * If the validation passes, then the success method will be called. It can take whatever actions are needed to handle the form
  * and it can redirect if needed or simply return some output that will then be rendered in place of the form.
  **/
 public function process()
 {
     $submitted = false;
     $form_ok = true;
     $src = strtoupper($this->_method);
     $this->_form_id = $this->_fingerprint();
     $r = $this->_renderer;
     //
     //	Has process been called following a form submission? Submission => method matches form
     //
     if (strtoupper($_SERVER['REQUEST_METHOD']) === $src) {
         $array = "_{$src}";
         $submitted = !empty($GLOBALS[$array]);
     }
     $r->setSubmitting($submitted);
     if ($submitted) {
         if (true == $this->_meta['show_submitted']) {
             fCore::expose(array($array => $GLOBALS[$array]));
         }
         // Signal to the renderer that a submission is underway. This allows it to conditionally add
         // classes when rendering
         $r->setSubmitting(true);
         // Do the id and token match what is expected?
         $id_ok = $this->_form_id === fRequest::get('_form_id');
         if (!$id_ok) {
             return '<p>An unexpected error occured. Form id mismatch.</p>';
         }
         $this->_form_token = fRequest::get('_form_token');
         $token_ok = fxCSRFToken::check($this->_form_id, $this->_form_token);
         if (!$token_ok) {
             return '<p>An unexpected error occured. Token mismatch.</p>';
         }
         //
         //	Iterate over elements, populating their values & evaluating them
         //
         foreach ($this->_elements as $e) {
             if (!is_string($e)) {
                 $e->_getSubmittedValue()->_validate($this->errors, $this);
             }
         }
         if (empty($this->errors)) {
             //
             //	Run the form validator (if any)
             //
             $validator = $this->_validation_cb;
             if (is_callable($validator)) {
                 $v = $validator($this);
                 $form_ok = true === $v;
             }
             if ($form_ok) {
                 if (is_callable($this->_onSuccess)) {
                     $fn = $this->_onSuccess;
                     return $fn($this);
                 } else {
                     throw new fxProgrammerException("Form submission successful but no onSuccess callback defined.");
                 }
             } else {
                 return $v;
             }
         }
     }
     fxCSRFToken::clear($this->_form_id);
     $this->_form_token = fxCSRFToken::generate($this->_form_id);
     if (true == $this->_show_form_elements) {
         fCore::expose($this);
     } elseif (true == $this->_show_form_errors) {
         fCore::expose($this->errors);
     }
     if (!$this->_form_id || !$this->_form_token) {
         throw new fxProgrammerException("Form cannot be rendered without _form_id and _form_token being defined.");
     }
     return $this->renderUsing($this->_renderer, $this, $this->id);
 }
Ejemplo n.º 27
0
 /**
  * Check if a field has a value
  * 
  * @param  string $key  The key to check for a value
  * @return boolean  If the key has a value
  */
 private static function hasValue($key)
 {
     $value = fRequest::get($key);
     if (self::stringlike($value)) {
         return TRUE;
     }
     if (is_array($value)) {
         foreach ($value as $individual_value) {
             if (self::stringlike($individual_value)) {
                 return TRUE;
             }
         }
     }
     return FALSE;
 }
 public function populate($recursive = FALSE)
 {
     $class = get_class($this);
     if (fORM::getActiveRecordMethod($class, 'populate')) {
         return $this->__call('populate', array());
     }
     fORM::callHookCallbacks($this, 'pre::populate()', $this->values, $this->old_values, $this->related_records, $this->cache);
     $schema = fORMSchema::retrieve($class);
     $table = fORM::tablize($class);
     $column_info = $schema->getColumnInfo($table);
     foreach ($column_info as $column => $info) {
         if (array_search($column, $this->protected_params) !== FALSE) {
             continue;
         }
         if (fRequest::check($column)) {
             $method = 'set' . fGrammar::camelize($column, TRUE);
             $cast_to = $info['type'] == 'blob' ? 'binary' : NULL;
             $this->{$method}(fRequest::get($column, $cast_to));
         }
     }
     fORM::callHookCallbacks($this, 'post::populate()', $this->values, $this->old_values, $this->related_records, $this->cache);
     if ($recursive) {
         $one_to_many_relationships = $schema->getRelationships($table, 'one-to-many');
         foreach ($one_to_many_relationships as $relationship) {
             $route_name = fORMSchema::getRouteNameFromRelationship('one-to-many', $relationship);
             $related_class = fORM::classize($relationship['related_table']);
             $method = 'populate' . fGrammar::pluralize($related_class);
             $this->{$method}(TRUE, $route_name);
         }
         $one_to_one_relationships = $schema->getRelationships($table, 'one-to-one');
         foreach ($one_to_one_relationships as $relationship) {
             $route_name = fORMSchema::getRouteNameFromRelationship('one-to-one', $relationship);
             $related_class = fORM::classize($relationship['related_table']);
             $this->__call('populate' . $related_class, array(TRUE, $route_name));
         }
     }
     return $this;
 }
Ejemplo n.º 29
0
<?php

include dirname(__FILE__) . '/../inc/init.php';
fAuthorization::requireLoggedIn();
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
$debug = fRequest::get('debug', 'boolean');
if (!$debug) {
    header('Content-type: application/json');
}
$check_id = fRequest::get('check_id', 'integer');
$check = new Check($check_id);
$url = GRAPHITE_URL . '/graphlot/rawdata?&from=-24hour&until=-0hour' . '&target=' . $check->prepareTarget() . '&target=keepLastValue(threshold(' . $check->prepareWarn() . '))';
//       '&target=threshold(' . $check->prepareError() . ')';
$contents = file_get_contents($url);
//$contents = file_get_contents(GRAPHITE_URL . '/graphlot/rawdata?&from=-24hour&until=-0hour&target=' . $check->prepareTarget() . '&target=' . $check->prepareWarn() . '&target=' . $check->prepareError());
print $contents;
Ejemplo n.º 30
0
*/
// Include initialisation file
include_once 'inc/init.php';
// Get action from query string
$action = fRequest::getValid('action', array('list'));
/**
 * Default action - show report of consumable installation
 */
if ($action == 'list') {
    // Set the users to be sortable by name or email, defaulting to name
    $sort = fCRUD::getSortColumn(array('events.date', 'models.name', 'printers.name', 'consumables.name'));
    // Set the sorting to default to ascending
    $dir = fCRUD::getSortDirection('desc');
    // Redirect the user if one of the values was loaded from the session
    fCRUD::redirectWithLoadedValues();
    // Get recordset object from tables
    $sql = "SELECT\n\t\t\t\tCAST(CONCAT(manufacturers.name, ' ', models.name) AS CHAR) AS model,\n\t\t\t\tprinters.name AS printer_name,\n\t\t\t\tprinters.ipaddress,\n\t\t\t\tconsumables.name AS consumable_name,\n\t\t\t\tconsumables.col_c, consumables.col_y, consumables.col_m, consumables.col_k, \n\t\t\t\tevents.*\n\t\t\tFROM events\n\t\t\tLEFT JOIN consumables ON events.consumable_id = consumables.id\n\t\t\tLEFT JOIN printers ON events.printer_id = printers.id\n\t\t\tLEFT JOIN models ON printers.model_id = models.id\n\t\t\tLEFT JOIN manufacturers ON models.manufacturer_id = manufacturers.id\n\t\t\t{where}\n\t\t\tORDER BY {$sort} {$dir}";
    // Get potential printer ID
    $printer_id = fRequest::get('printer_id', 'integer?');
    if ($printer_id == NULL) {
        $sql = str_replace('{where}', '', $sql);
        $events = $db->query($sql)->asObjects();
    } else {
        $sql_where = 'WHERE events.printer_id = %i';
        $sql = str_replace('{where}', $sql_where, $sql);
        $events = $db->query($sql, $printer_id)->asObjects();
        $printer = new Printer($printer_id);
    }
    // Include page to show table
    include 'views/reports/index.php';
}