Example #1
0
function irccat_notify($check, $check_result, $subscription)
{
    global $status_array;
    $state = $status_array[$check_result->getStatus()];
    if ($state == 'OK') {
        $event_type = 'resolve';
    } else {
        $event_type = 'trigger';
    }
    $user = new User($subscription->getUserId());
    $irccat_channel = usr_var('irccat_channel', $user->getUserId());
    $irccat_ircnick = usr_var('irccat_ircnick', $user->getUserId());
    if (!empty($irccat_channel)) {
        $irc_target = $irccat_channel;
    } elseif (!empty($irccat_ircnick)) {
        $irc_target = '@' . $irccat_ircnick;
    } else {
        echo "No IRC Channel or Nickname selected for this users check " . $user->getUserId() . "\n";
        return false;
    }
    $message = $irc_target . " " . str_replace(array('{check_name}', '{check_state}'), array($check->prepareName(), $state), sys_var('irccat_subject')) . " Current : " . $check_result->prepareValue() . ", Error : " . $check->getError() . ", Warning : " . $check->getWarn();
    $fp = fsockopen(sys_var('irccat_hostname'), sys_var('irccat_port'), $errno, $errstr, 30);
    if (!$fp) {
        echo "{$errstr} ({$errno})<br />\n";
    } else {
        stream_set_timeout($fp, 4);
        fwrite($fp, $message);
        fclose($fp);
    }
}
 /**
  * Performs the action; returns true on success, false on error.
  *
  * @param $p_context - the current context object
  * @return bool
  */
 public function takeAction(CampContext &$p_context)
 {
     $p_context->default_url->reset_parameter('f_' . $this->m_name);
     $p_context->url->reset_parameter('f_' . $this->m_name);
     if (PEAR::isError($this->m_error)) {
         return false;
     }
     $auth = Zend_Auth::getInstance();
     $user = new User($p_context->user->identifier);
     if ($user->getUserId() != $auth->getIdentity() || $user->getUserId() == 0) {
         $this->m_error = new PEAR_Error('You must be logged in to create or edit your subscription.', ACTION_EDIT_SUBSCRIPTION_ERR_NO_USER);
         return false;
     }
     $subscriptions = Subscription::GetSubscriptions($p_context->publication->identifier, $user->getUserId());
     if (count($subscriptions) == 0) {
         $subscription = new Subscription();
         $created = $subscription->create(array('IdUser' => $user->getUserId(), 'IdPublication' => $p_context->publication->identifier, 'Active' => 'Y', 'Type' => $this->m_subscriptionType == 'trial' ? 'T' : 'P'));
         if (!$created) {
             $this->m_error = new PEAR_Error('Internal error (code 1)', ACTION_EDIT_SUBSCRIPTION_ERR_INTERNAL);
             exit(1);
         }
     } else {
         $subscription = $subscriptions[0];
     }
     $publication = new Publication($p_context->publication->identifier);
     $subscriptionDays = $this->computeSubscriptionDays($publication, $p_context->publication->subscription_time);
     $startDate = new Date();
     $columns = array('StartDate' => $startDate->getDate(), 'Days' => $subscriptionDays, 'PaidDays' => $this->m_subscriptionType == 'trial' ? $subscriptionDays : 0, 'NoticeSent' => 'N');
     if ($this->m_properties['subs_by_type'] == 'publication') {
         $sectionsList = Section::GetUniqueSections($p_context->publication->identifier);
         foreach ($sectionsList as $section) {
             $this->m_sections[] = $section['id'];
         }
     }
     foreach ($this->m_languages as $languageId) {
         foreach ($this->m_sections as $sectionNumber) {
             $subsSection = new SubscriptionSection($subscription->getSubscriptionId(), $sectionNumber, $languageId);
             $subsSection->create($columns);
         }
     }
     $fields = array('SubsType', 'tx_subs', 'nos', 'unitcost', 'unitcostalllang', 'f_substype', 'cb_subs', 'subs_all_languages', 'suma', 'tpl', 'subscription_language');
     foreach (CampRequest::GetInput() as $field => $value) {
         if (strncmp('tx_subs', $field, strlen('tx_subs')) == 0) {
             $fields[] = $field;
         }
     }
     foreach ($fields as $fieldName) {
         $p_context->default_url->reset_parameter($fieldName);
         $p_context->url->reset_parameter($fieldName);
     }
     $this->m_error = ACTION_OK;
     return true;
 }
 /**
  * saves a user object from memory to Database.
  *
  * @param User $user
  *
  * @return bool
  */
 public function save(User $user)
 {
     /* $data keys should correspond to valid Table columns on the Database */
     $data = array('userid' => $user->getUserId(), 'username' => $user->getUsername(), 'email' => $user->getEmail());
     /* if no ID specified create new user else update the one in the Database */
     if (null === ($id = $user->getUserId())) {
         unset($data['userid']);
         $this->adapter->insert($data);
         return true;
     } else {
         $this->adapter->update($data, array('userid = ?' => $id));
         return true;
     }
 }
Example #4
0
 /**
  * Add a user to the game
  * 
  * @param User $user
  * @return Game
  */
 public function addUser(User $user)
 {
     // Add a user and clear its score sheet
     $this->users[$user->getUserId()] = $user;
     $this->clearScore($user);
     return $this;
 }
Example #5
0
 /**
  * Sets the currently logged in user.
  * @param User $user The user to set.
  * @param string $password The password of the user, just to be sure.
  */
 public static function setUser(User $user, $password)
 {
     // Let's first issue a new session token to null out any old forms
     Session::issueToken();
     // Make sure the user isn't a guest and the password works
     if ($user == null || $user->isGuest() || !$user->isPassword($password)) {
         // Delete the cookies
         Cookie::delete('userid');
         Cookie::delete('sid');
         // Set the user to a guest
         self::$user = User::guest();
         return;
     }
     // Make sure this isn't already the signed in user
     if (self::$user != null && self::$user->getUserId() == $user->getUserId()) {
         return;
     }
     // Set the cookies
     Cookie::set('userid', $user->getUserId());
     Cookie::set('sid', $user->getCookiePassword());
     // Update the user's visit times
     $user->updateVisitInfo();
     // Let's now set the local version
     self::$user = $user;
 }
Example #6
0
function email_plugin_notify_master($check, $check_result, $subscription, $alt_email = false)
{
    global $status_array;
    $user = new User($subscription->getUserId());
    $email = new fEmail();
    // This sets up fSMTP to connect to the gmail SMTP server
    // with a 5 second timeout. Gmail requires a secure connection.
    $smtp = new fSMTP(sys_var('smtp_server'), sys_var('smtp_port'), sys_var('require_ssl') === 'true' ? TRUE : FALSE, 5);
    if (sys_var('require_auth') === 'true') {
        $smtp->authenticate(sys_var('smtp_user'), sys_var('smtp_pass'));
    }
    if ($alt_email) {
        $email_address = usr_var('alt_email', $user->getUserId());
    } else {
        $email_address = $user->getEmail();
    }
    $email->addRecipient($email_address, $user->getUsername());
    // Set who the email is from
    $email->setFromEmail(sys_var('email_from'), sys_var('email_from_display'));
    $state = $status_array[$check_result->getStatus()];
    // Set the subject include UTF-8 curly quotes
    if ($state == 'OK') {
        $email->setSubject(str_replace('{check_name}', $check->prepareName(), sys_var('email_end_alert_subject')));
    } else {
        $email->setSubject(str_replace('{check_name}', $check->prepareName(), sys_var('email_subject')));
    }
    // Set the body to include a string containing UTF-8
    $check_type = '';
    if ($check->getType() == 'threshold') {
        $check_type = ' Threshold';
    } elseif ($check->getType() == 'predictive') {
        $check_type = ' Standard Deviation';
    }
    $state_email_injection = $state . " Alert ";
    if ($state == 'OK') {
        $state_email_injection = "Everything's back to normal ";
    }
    // Remind : ('0' => 'OK', '1'   => 'Error', '2' => 'Warning');
    $state_int = $check_result->getStatus();
    if ($state_int == 0) {
        $color = "green";
    } else {
        if ($state_int == 2) {
            $color = "orange";
        } else {
            $color = "red";
        }
    }
    $html_body = "<p style='color:" . $color . ";'>" . $state_email_injection . "for {$check->prepareName()} </p>" . "<p>The check returned {$check_result->getValue()}</p>" . "<p>Warning" . $check_type . " is : " . $check->getWarn() . "</p>" . "<p>Error" . $check_type . " is : " . $check->getError() . "</p>" . "<p>View Alert Details : <a href='" . $GLOBALS['TATTLE_DOMAIN'] . '/' . CheckResult::makeURL('list', $check_result) . "'>" . $check->prepareName() . "</a></p>";
    $email->setHTMLBody($html_body);
    $email->setBody("\n  {$state} Alert for {$check->prepareName()}\nThe check returned {$check_result->getValue()}\nWarning" . $check_type . " is : " . $check->getWarn() . "\nError" . $check_type . " is : " . $check->getError() . "\n           ");
    try {
        $message_id = $email->send($smtp);
    } catch (fConnectivityException $e) {
        fCore::debug($e, FALSE);
        fCore::debug("email send failed", FALSE);
        $e->printMessage();
        $e->printTrace();
    }
}
 public function __construct(User $user)
 {
     $this->user = $user;
     parent::setEmployeeNumber($user->getEmployeeNumber());
     parent::setUserId($user->getUserId());
     parent::setUserTimeZoneOffset($user->getUserTimeZoneOffset());
 }
Example #8
0
 public static function create(User $user, $uploaded_filename, $name)
 {
     // Create a new row in the database for the image
     $query = Database::connection()->prepare('INSERT INTO attachment (size, name, created_by, created_at) VALUES (?, ?, ?, ?)');
     $query->bindValue(1, filesize($uploaded_filename), PDO::PARAM_INT);
     $query->bindValue(2, $name, PDO::PARAM_INT);
     $query->bindValue(3, $user->getUserId(), PDO::PARAM_INT);
     $query->bindValue(4, time(), PDO::PARAM_INT);
     if (!$query->execute()) {
         throw new Exception('Unable to create attachment.');
     }
     // Get the image that we just created
     $attachment = Attachment::fromId(Database::connection()->lastInsertId());
     if (is_uploaded_file($uploaded_filename)) {
         if (!move_uploaded_file($uploaded_filename, self::getStoragePath($attachment->getAttachmentId()))) {
             $attachment->delete();
             throw new Exception('Unable to move attachment into place.');
         }
     } else {
         if (!rename($uploaded_filename, self::getStoragePath($attachment->getAttachmentId()))) {
             $attachment->delete();
             throw new Exception('Unable to move attachment into place.');
         }
     }
     //$imagick = new Imagick();
     //$imagick->readimage(self::getStoragePath($image->getId()));
     //$imagick->setimagetype('png');
     //$imagick->writeimage();
     return $attachment;
 }
 public function createAction()
 {
     $responseData = array();
     if (!$this->request->isPost()) {
         $this->setBadRequestStatus();
     } else {
         $this->setOkStatus();
         if (User::exist($this->request->getPost('email'))) {
             $responseData = array('result' => ResponseMessage::USER_EXIST);
         } else {
             try {
                 $user = new User();
                 $user->setEmail($this->request->getPost('email'));
                 $user->setPassword($this->request->getPost('password'), true);
                 if ($firstName = $this->request->getPost('firstname')) {
                     $user->setFirstname($firstName);
                 }
                 if ($lastName = $this->request->getPost('lastname')) {
                     $user->setLastname($lastName);
                 }
                 if ($fb_id = $this->request->getPost('facebook_id')) {
                     $user->setFacebookId($fb_id);
                 }
                 $user->save();
                 $responseData = array('result' => ResponseMessage::OK, 'user_id' => $user->getUserId());
             } catch (Exception $e) {
                 $this->handleError($e->getMessage());
                 return;
             }
         }
     }
     $this->sendResponse($responseData);
 }
Example #10
0
function email_plugin_notify($check,$check_result,$subscription,$alt_email=false) {
  global $status_array;
  $user = new User($subscription->getUserId());
  $email = new fEmail();
  // This sets up fSMTP to connect to the gmail SMTP server
  // with a 5 second timeout. Gmail requires a secure connection.
  $smtp = new fSMTP(sys_var('smtp_server'), sys_var('smtp_port'), TRUE, 5);
  $smtp->authenticate(sys_var('smtp_user'), sys_var('smtp_pass'));
  if ($alt_email) {
    $email_address = usr_var('alt_email',$user->getUserId());
  } else {
    $email_address = $user->getEmail(); 
  }
  $email->addRecipient($email_address, $user->getUsername());
  // Set who the email is from
  $email->setFromEmail(sys_var('email_from'), sys_var('email_from_display'));
  // Set the subject include UTF-8 curly quotes
  $email->setSubject(str_replace('{check_name}', $check->prepareName(), sys_var('email_subject')));
  // Set the body to include a string containing UTF-8
  $state = $status_array[$check_result->getStatus()];
  $email->setHTMLBody("<p>$state Alert for {$check->prepareName()} </p><p>The check returned {$check_result->prepareValue()}</p><p>Warning Threshold is : ". $check->getWarn() . "</p><p>Error Threshold is : ". $check->getError() . '</p><p>View Alert Details : <a href="' . fURL::getDomain() . '/' . CheckResult::makeURL('list',$check_result) . '">'.$check->prepareName()."</a></p>");
  $email->setBody("
  $state Alert for {$check->prepareName()}
The check returned {$check_result->prepareValue()}
Warning Threshold is : ". $check->getWarn() . "
Error Threshold is : ". $check->getError() . "
           ");
  try {  
    $message_id = $email->send($smtp);
  } catch ( fConnectivityException $e) { 
    fCore::debug("email send failed",FALSE);
  }
}
Example #11
0
 static function getTotalEnvironments($username)
 {
     require 'db.php';
     $userId = User::getUserId($username);
     $sth = $dbh->query("SELECT envId FROM environments WHERE userId='{$userId}'");
     $sth->setFetchMode(PDO::FETCH_OBJ);
     $result = $sth->fetchAll();
     return $result;
 }
Example #12
0
 function topMenu()
 {
     $menu = array();
     if (Permission::checkPermission(pow(2, 2))) {
         $user = new User((int) $_SESSION['user_id']);
         $user->fetch();
         $menu[] = array('name' => $user->getNickname(), 'href' => 'user.php?user_id=' . $user->getUserId());
     }
     return $menu;
 }
Example #13
0
 /**
  * Save a new emoji
  * @param object $app 
  * @return array
  */
 public function post($app)
 {
     $user = new User();
     $this->name = $app->request->params('name');
     $this->category = $app->request->params('category');
     $this->emoji = $app->request->params('emoji');
     $this->keywords = $app->request->params('keywords');
     date_default_timezone_set('Africa/Lagos');
     $this->date_created = date('Y-m-d H:i:s', time());
     $this->created_by = $user->getUserId($app->request->headers['token']);
     return $this->save() ? ["msg" => "Emoji saved succesfully"] : ["msg" => "Unable to save emoji"];
 }
Example #14
0
 /**
  * test inserting a Rating and grabbing it from my sql
  */
 public function testGetValidRatingByTrail()
 {
     // count the number of rows and save it for later
     $numRows = $this->getConnection()->getRowCount("rating");
     // create a new rating and insert it into my sql
     $rating = new Rating($this->trail->getTrailId(), $this->user->getUserId(), $this->VALID_RATINGVALUE);
     $rating->insert($this->getPDO());
     //grab the data from mySQL and enforce the fields match expectations
     $pdoRatings = Rating::getRatingValueByTrailId($this->getPDO(), $this->trail->getTrailId());
     foreach ($pdoRatings as $pdoRating) {
         $this->assertSame($numRows + 1, $this->getConnection()->getRowCount("rating"));
         $this->assertSame($pdoRating->getRatingValue(), $this->VALID_RATINGVALUE);
     }
 }
Example #15
0
 /**
  * This function update and insert user record
  * @param \Music\Model\User $user
  * @throws \Exception
  */
 public function saveUser(User $user, $user_id)
 {
     $data = array('username' => $user->getUsername(), 'password' => md5($user->getPassword()), 'role' => $user->getRole(), 'fullname' => $user->getFullName());
     $user_id = (int) $user->getUserId();
     if (!$user_id) {
         $this->tableGateway->insert($data);
     } else {
         if ($user_id) {
             $this->tableGateway->update($data, array('user_id' => $user_id));
         } else {
             throw new \Exception('Form id does not exist');
         }
     }
 }
Example #16
0
 /**
  * Establece las variables de sesión del usuario.
  *
  * @param User $User
  * @throws SPException
  */
 public static function loadUserSession(User $User)
 {
     Session::setUserId($User->getUserId());
     Session::setUserName($User->getUserName());
     Session::setUserLogin($User->getUserLogin());
     Session::setUserProfileId($User->getUserProfileId());
     Session::setUserGroupId($User->getUserGroupId());
     Session::setUserGroupName($User->getUserGroupName());
     Session::setUserEMail($User->getUserEmail());
     Session::setUserIsAdminApp($User->isUserIsAdminApp());
     Session::setUserIsAdminAcc($User->isUserIsAdminAcc());
     Session::setUserIsLdap($User->isUserIsLdap());
     Session::setUserProfile(Profile::getProfile($User->getUserProfileId()));
 }
Example #17
0
 public static function send(User $objUser, Notificationemail $objNot)
 {
     $to = $objUser->getUserCredential();
     $usetId = $objUser->getUserId();
     $subject = $objNot->getSubject();
     $message = $objNot->getBody();
     //        $headers  = "Content-type: text/html; charset=windows-1251 \r\n";
     //        $headers .= "From: Birthday Reminder <*****@*****.**>\r\n";
     //        $headers .= "Bcc: birthday-archive@example.com\r\n";
     if (mail($to, $subject, $message)) {
         echo 'письмо отправлено пользователю id: ' . $usetId . '<br>';
     } else {
         echo 'ошибка отправки письма пользователю id: ' . $usetId . '<br>';
     }
 }
Example #18
0
 /**
  * Статический метод позволяет зарегистрировать нового пользователя и вернуть его значения или вернуть значения существующего пользователя
  * @param string $bitcoin Принмает строку биткоина
  * @param string $ref Принмает строку для реферала(указан родительский биткоин)
  * @return array Вернет массив значений пользователя привязанного к указанному биткоину
  */
 public static function login($bitcoin, $ref)
 {
     //проверяем зарегистрирован ли биткоин, если нет то регим и получаем его id, так же устанавливаем ему подарочный бонус
     if (empty(@User::getUserId($bitcoin))) {
         $parentId = !empty($ref) ? User::getUserId($ref) : $ref;
         $result = User::setUser($bitcoin, $parentId, Config::DEF_BONUS);
         if (!empty($result)) {
             $userId = User::getUserId($bitcoin);
         }
     } else {
         $userId = User::getUserId($bitcoin);
     }
     $userData = User::getUser(['id', 'bitcoin', 'parentId', 'nextVisit', 'withdraw', 'balance', 'lastPayOut', 'lastDateOut', 'bonus', 'dailyBonus', 'pauseGame', 'pauseBonus'], $userId);
     return $userData;
 }
Example #19
0
function pushover_plugin_notify($check, $check_result, $subscription)
{
    $user = new User($subscription->getUserId());
    global $status_array;
    $check_status = $status_array[$check_result->getStatus()];
    $check_name = $check->prepareName();
    $check_value = $check_result->prepareValue();
    $check_warning_level = $check->getWarn();
    $check_error_level = $check->getError();
    $check_type = $check->getType();
    $title = "{$check_status} for {$check_name}";
    $message = "Check returned: {$check_value}\n" . "Warning {$check_type} is: {$check_warning_level}\n" . "Error {$check_type} is: {$check_error_level}";
    $data = array('token' => sys_var('pushover_plugin_application_token'), 'user' => usr_var('pushover_plugin_user_key', $user->getUserId()), 'message' => $message, 'title' => $title, 'url' => $GLOBALS['TATTLE_DOMAIN'] . '/' . CheckResult::makeURL('list', $check_result));
    $options = array('http' => array('header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data)));
    $result = file_get_contents("https://api.pushover.net/1/messages.json", false, stream_context_create($options));
}
Example #20
0
 /**
  * @param : array $data
  * @return int $id
  */
 public static function insert($data)
 {
     if (!is_array($data) || !count($data)) {
         return;
     }
     $shipFromData = $data['shipFrom'];
     $shipToData = $data['shipTo'];
     $itemData = $data['item'];
     $companyData = $data['company'];
     $shipFromId = ShipFrom::insert($shipFromData);
     $shipToId = ShipTo::insert($shipToData);
     $itemId = Item::insert($itemData);
     $companyId = Company::insert($companyData);
     $orderData = array('reference_no' => 'SPR-' . rand(), 'created_on' => date('Y-m-d'), 'user_id' => User::getUserId(), 'ship_to' => $shipToId, 'ship_from' => $shipFromId, 'item_id' => $itemId, 'company_id' => $companyId);
     $id = DB::table('order')->insertGetId($orderData);
     return $id;
 }
 public function getSession($id)
 {
     $data = array();
     $social_actions = SocialAction::with('socialTarget', 'user')->where('id', $id)->first();
     if ($social_actions == false) {
         return App::abort('404');
     }
     $photos = Photo::where('type_name', '=', 'social_actions')->where('type_id', '=', $social_actions->id)->where('status', '=', 1)->get();
     $donations = Donation::with(array('user'))->where('type_name', '=', 'social_actions')->where('type_id', '=', $social_actions->id)->where('status', '=', 1)->orderBy('id', 'desc')->get();
     $user = User::getUserId($social_actions->user_id);
     $social_target_id = SocialTarget::getAll();
     $social_action_category_id = SocialActionCategory::getAll();
     $city_id = City::getAll();
     $data = array('social_action' => $social_actions, 'photos' => $photos, 'donations' => $donations, 'user' => $user, 'social_target_id' => $social_target_id, 'social_action_category_id' => $social_action_category_id, 'city_id' => $city_id);
     Session::put('type_name', 'SocialAction');
     Session::put('type_id', $social_actions->social_target_id);
     return Redirect::route('buat-aksi-sosial');
 }
Example #22
0
 public function __construct($username)
 {
     global $dbConn;
     $this->token = md5($username . strtotime("now"));
     $this->expiration = strtotime('+10 minutes');
     $userId = User::getUserId($username);
     //insert user in database as active if he is not already present.
     $result = $dbConn->query("SELECT * FROM tokens WHERE `account_id`='{$userId}'");
     //if user is not present we must create his token.
     if ($result->num_rows == 0) {
         $dateTimeFormat = date('Y-m-d H:i:s', $this->expiration);
         $tokenCreated = $dbConn->query("INSERT INTO `tokens` VALUES ('{$userId}', '{$this->token}', '{$dateTimeFormat}')");
     } else {
         //a token already exists retrieve the current token.
         $existingToken = $dbConn->query("SELECT token FROM tokens WHERE `account_id`='{$userId}'");
         $tokenData = $existingToken->fetch_array();
         $this->token = $tokenData["token"];
     }
 }
 /**
  * create dependent objects before running each test
  **/
 public function setUp()
 {
     //run the default setUp() method first
     parent::setUp();
     $this->VALID_DATE = DateTime::createFromFormat("Y-m-d H:i:s", $this->VALID_DATE);
     //create browser
     $this->VALID_BROWSER = "Chrome";
     $this->VALID_USERSALT = bin2hex(openssl_random_pseudo_bytes(32));
     $this->VALID_USERHASH = $this->VALID_USERHASH = hash_pbkdf2("sha512", "password4321", $this->VALID_USERSALT, 262144, 128);
     //create and insert a userId to own the trail
     $this->user = new User(null, $this->VALID_BROWSER, $this->VALID_DATE, "192.168.1.168", "S", "*****@*****.**", $this->VALID_USERHASH, "Hyourname.tomorrow", $this->VALID_USERSALT);
     $this->user->insert($this->getPDO());
     $this->VALID_TRAILNAME = "La Luz";
     //create and insert a trailId to own the test Trail Relationship
     //$newTrailId, $newUserId, $newBrowser, $newCreateDate, $newIpAddress, $newSubmitTrailId, $newTrailAccessibility, $newTrailAmenities, $newTrailCondition, $newTrailDescription, $newTrailDifficulty, $newTrailDistance, $newTrailName, $newTrailSubmissionType, $newTrailTerrain, $newTrailTraffic, $newTrailUse, $newTrailUuid
     $this->trail = new Trail(null, $this->user->getUserId(), "Safari", $this->VALID_DATE, "192.168.1.4", null, "y", "Picnic area", "Good", "This trail is a beautiful winding trail located in the Sandia Mountains", 3, 1054.53, $this->VALID_TRAILNAME, 1, "Mostly switchbacks with a few sections of rock fall", "Heavy", "Hiking", "SSEERFFV4444554");
     $this->trail->insert($this->getPDO());
     $this->segmentStart = new Point(35.554, 44.546);
     $this->segmentStop = new Point(6, 36);
     //create and insert a segmentId to own the test Trail Relationship
     $this->segment = new Segment(null, $this->segmentStart, $this->segmentStop, 1000, 2000);
     $this->segment->insert($this->getPDO());
 }
    // eine neue Session starten
    session_start();
    // Benutzername und Passwort aus den POST-Variablen auslesen
    // und in die beiden Variablen $usr und $pwd speichern
    $usr = $_POST['user'];
    $pwd = $_POST['password'];
    // Benutzername und Passwort werden überprüft
    if (User::checkLogInData($usr, $pwd)) {
        // wurden Benutzername und Passwort korrekt eingegeben, wird in
        // der am Anfang des Skripts geöffneten Session eine Variable
        // mit dem Namen "angemeldet" und dem Wert TRUE gespeichert.
        $_SESSION['angemeldet'] = true;
        // die ganzen Rechte, welche Seiten der Benutzer besuchen darf,
        // werden als Array in die Session-Variable geschrieben
        $_SESSION['user_role'] = User::getUserRole();
        // ID, Vor- und Nachname des Benutzers in die Session-Variable speichern
        $_SESSION['user_id'] = User::getUserId();
        $_SESSION['user_name'] = User::getUserName();
        // Spracheinstellung des Browsers ermitteln
        $_SESSION['user_lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
        // Weiterleitung zur Hauptseite der Anwendung.
        echo 1;
    } else {
        // Weiterleitung zurück zum Anmeldeformular
        echo 0;
    }
    // wichtig ist die die exit()-Anweisung nach der Weiterleitung,
    // damit kein weiterer Code ausgefuehrt werden kann und das
    // aktuelle Skript sofort beendet wird.
    die;
}
 public function canEdit(User $user)
 {
     if (!$this->userId() || $this->userId() != $user->getUserId()) {
         return false;
     }
     if ($this->dateAdded() <= time() - ARGUMENT_EDIT_INTERVAL) {
         return false;
     }
     if (count($this->arguments())) {
         return false;
     }
     return true;
 }
 /**
  * Declares an association between this object and a User object.
  *
  * @param      User $v
  * @return     void
  * @throws     PropelException
  */
 public function setUser($v)
 {
     if ($v === null) {
         $this->setUserId(NULL);
     } else {
         $this->setUserId($v->getUserId());
     }
     $this->aUser = $v;
 }
Example #27
0
 public function countPortfolios()
 {
     $oUser = new User();
     # the query
     $query = $this->mysqli->query('SELECT count(*) as countPortfolios FROM `portfolios` left join users as user on portfolios.users_id = user.id where user.id = ' . $oUser->getUserId());
     # the result
     $result = parent::fetchResultAssoc($query);
     return $result[0]['countPortfolios'];
 }
Example #28
0
 $subject_mail = fRequest::get('subject_mail');
 $content_mail = fRequest::get('content_mail');
 if (fRequest::isPost()) {
     if (empty($subject_mail) || empty($content_mail)) {
         fMessaging::create('error', fURL::get(), "You have to fill the subject and the content to send this mail");
     } else {
         fRequest::validateCSRFToken(fRequest::get('token'));
         $recipients = array();
         $id_user_session = fSession::get('user_id');
         $user_session = new User($id_user_session);
         $recipients[] = array("mail" => $user_session->getEmail(), "name" => $user_session->getUsername());
         $alt_ids = array();
         $subscription_alt = Subscription::findAll($check_id, NULL, NULL, NULL, TRUE);
         foreach ($subscription_alt as $alt) {
             $user = new User($alt->getUserId());
             $recipients[] = array("mail" => usr_var('alt_email', $user->getUserId()), "name" => $user->getUsername());
             $alt_ids[] = $alt->getUserId();
         }
         $subscriptions = $db->query("SELECT DISTINCT user_id,check_id FROM subscriptions WHERE check_id=" . $check_id . ";");
         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 {
Example #29
0
 /**
  * test #14.
  * Overriding automatic attributes using a future date. Because
  * a future date is used, the record can no longer be changed after
  * it was saved.
  * @depends testSaveEmptyObject
  * @depends testSetAttributes
  * @depends testUpdate
  * @depends testOverrideAutomaticAttributesNewRecord
  */
 public function testOverrideAutomaticAttributesFutureDate()
 {
     global $testUserId1;
     // Create the object, which automatically gets the current date
     $object = new User($testUserId1);
     $object->setName('Test User');
     $object->setExternalType('externaltype');
     $object->setExternalId('externalid');
     $object->setAccess('access');
     $object->setEmail('*****@*****.**');
     $object->setNotification('Y');
     $object->setTempCode('tempcode');
     $object->setDeleted('Y');
     $this->assertTrue($object->save());
     $this->assertEquals(1, $this->countTestRows());
     $originalCreated = $object->getCreated();
     $originalUpdated = $object->getUpdated();
     $originalHash = $object->getHash();
     // Change the object with different values, using a guaranteed
     // future date for the Created and Updated fields. Note that
     // the mySQL timestamp values allow for dates up to January 19,
     // 2038. Select as the future date for this test January 18, 2038
     // values after first save are unchanged
     $object->setCreated('2038-01-18 10:10:10.000000');
     $object->setUpdated('2038-01-18 10:10:11.000000');
     $object->setName('Test User 2');
     $object->setExternalType('externaltype 2');
     $object->setExternalId('externalid 2');
     $object->setAccess('access 2');
     $object->setEmail('*****@*****.**');
     $object->setNotification('N');
     $object->setTempCode('tempcode 2');
     $object->setDeleted('N');
     $object->setHash('future date hash');
     // Check the values before saving
     $this->assertEquals($testUserId1, $object->getUserId());
     $this->assertEquals('2038-01-18 10:10:10.000000', $object->getCreated());
     $this->assertEquals('2038-01-18 10:10:11.000000', $object->getUpdated());
     $this->assertEquals('Test User 2', $object->getName());
     $this->assertEquals('externaltype 2', $object->getExternalType());
     $this->assertEquals('externalid 2', $object->getExternalId());
     $this->assertEquals('access 2', $object->getAccess());
     $this->assertEquals('*****@*****.**', $object->getEmail());
     $this->assertEquals('N', $object->getNotification());
     $this->assertEquals('tempcode 2', $object->getTempCode());
     $this->assertEquals('N', $object->getDeleted());
     $this->assertEquals('future date hash', $object->getHash());
     // update the record, this adds a row in the database
     $this->assertTrue($object->save());
     $this->assertEquals(2, $this->countTestRows());
     // after the update, the information has been saved
     $this->assertEquals($testUserId1, $object->getUserId());
     $this->assertEquals('2038-01-18 10:10:10.000000', $object->getCreated());
     $this->assertEquals('2038-01-18 10:10:11.000000', $object->getUpdated());
     $this->assertEquals('Test User 2', $object->getName());
     $this->assertEquals('externaltype 2', $object->getExternalType());
     $this->assertEquals('externalid 2', $object->getExternalId());
     $this->assertEquals('access 2', $object->getAccess());
     $this->assertEquals('*****@*****.**', $object->getEmail());
     $this->assertEquals('N', $object->getNotification());
     $this->assertEquals('tempcode 2', $object->getTempCode());
     $this->assertEquals('N', $object->getDeleted());
     $this->assertEquals('future date hash', $object->getHash());
     // Try to update the record. This will add a row in the database
     $object->setName('Test User 3');
     $object->setExternalType('externaltype 3');
     $object->setExternalId('externalid 3');
     $object->setAccess('access 3');
     $object->setEmail('*****@*****.**');
     $object->setNotification('Y');
     $object->setTempCode('tempcode 3');
     $object->setDeleted('Y');
     $this->assertTrue($object->save());
     $this->assertEquals(3, $this->countTestRows());
     // but the new information is not saved. The previously saved
     // information cannot be overwritten without manually setting the
     // updated field.
     $this->assertEquals($testUserId1, $object->getUserId());
     $this->assertEquals('2038-01-18 10:10:10.000000', $object->getCreated());
     $this->assertEquals('2038-01-18 10:10:11.000000', $object->getUpdated());
     $this->assertEquals('Test User 2', $object->getName());
     $this->assertEquals('externaltype 2', $object->getExternalType());
     $this->assertEquals('externalid 2', $object->getExternalId());
     $this->assertEquals('access 2', $object->getAccess());
     $this->assertEquals('*****@*****.**', $object->getEmail());
     $this->assertEquals('N', $object->getNotification());
     $this->assertEquals('tempcode 2', $object->getTempCode());
     $this->assertEquals('N', $object->getDeleted());
     // Note: this will FAIL in the current implementation!
     //$this->assertEquals('future date hash', $object->getHash());
 }
Example #30
0
    include VIEW_PATH . '/add_edit_user.php';
    // --------------------------------- //
} elseif ('add' == $action) {
    $user = new User();
    if (fRequest::isPost()) {
        try {
            $user->populate();
            if ($GLOBALS['ALLOW_HTTP_AUTH']) {
                $password = '******';
            } else {
                $password = fCryptography::hashPassword($user->getPassword());
            }
            $user->setPassword($password);
            fRequest::validateCSRFToken(fRequest::get('token'));
            $user->store();
            if ($user->getUserId() == 1) {
                $user->setRole('admin');
                $user->store();
            }
            fMessaging::create('affected', User::makeURL('login'), $user->getUsername());
            fMessaging::create('success', User::makeURL('login'), 'The user ' . $user->getUsername() . ' was successfully created');
            fURL::redirect(User::makeURL('login'));
        } catch (fExpectedException $e) {
            fMessaging::create('error', fURL::get(), $e->getMessage());
        }
    }
    include VIEW_PATH . '/add_edit_user.php';
} elseif ('settings' == $action) {
    $user = new User($user_id);
    if (fRequest::isPost()) {
        try {