Example #1
0
 public function onRemove()
 {
     $points = post('points');
     if (!is_numeric($points)) {
         return;
     }
     $userExtend = new UserExtend($this->model);
     $userExtend->removePoints($points, false);
     return ['span.points' => $userExtend->user->points, 'span.points-today' => $userExtend->user->points_today, 'span.points-week' => $userExtend->user->points_this_week];
 }
 public function testCanHaveAndRemovePoints()
 {
     $incrementVal = 10;
     $user = FactoryMuffin::create('RainLab\\User\\Models\\User');
     $points = $user->points;
     $points_this_week = $user->points_this_week;
     $userExtend = new UserExtend($user);
     // Add points
     $userExtend->addPoints($incrementVal);
     $points += $incrementVal;
     $points_this_week += $incrementVal;
     $this->assertEquals($user->points, $points);
     $this->assertEquals($user->points_this_week, $points_this_week);
     // Remove Points
     $userExtend->removePoints($incrementVal);
     $points -= $incrementVal;
     $points_this_week -= $incrementVal;
     $this->assertEquals($user->points, $points);
     $this->assertEquals($user->points_this_week, $points_this_week);
 }
 /**
  * Redeem a reward for a user
  * @param int $id
  * The id of the reward to redeem
  * @param User $user
  * The user model to redeem the reward for
  */
 public static function redeem($id, $user)
 {
     $reward = Reward::find($id);
     if (!$reward) {
         throw SystemException(Lang::get('dma.friends.exceptions.missingReward', ['id' => $id]));
     }
     try {
         // Check overall inventory
         if ($reward->inventory !== null && $reward->inventory == 0) {
             Session::put('rewardError', Lang::get('dma.friends::lang.rewards.noInventory'));
             return;
         }
         // Check a users individual inventory
         $count = $user->rewards()->where('reward_id', $reward->id)->count();
         if (!empty($reward->user_redeem_limit) && $count >= $reward->user_redeem_limit) {
             Session::put('rewardError', Lang::get('dma.friends::lang.rewards.alreadyRedeemed'));
             return;
         }
         $userExtend = new UserExtend($user);
         if ($userExtend->removePoints($reward->points, false)) {
             if ($reward->inventory > 0) {
                 $reward->inventory--;
                 $reward->save();
             }
             $user->rewards()->save($reward);
             Event::fire('dma.friends.reward.redeemed', [$reward, $user]);
             $params = ['user' => $user, 'object' => $reward];
             FriendsLog::reward($params);
             // TODO handle printing of reward coupon
             Session::put('rewardMessage', Lang::get('dma.friends::lang.rewards.redeemed', ['title' => $reward->title]));
         } else {
             Session::put('rewardError', Lang::get('dma.friends::lang.rewards.noPoints'));
         }
     } catch (Exception $e) {
         throw SystemException(Lang::get('dma.friends.exceptions.rewardFailed'));
     }
 }
 /**
  * Convert user phone field in to E.164 format
  * @param unknown $user
  * @return Ambigous <NULL, string, unknown, string>
  */
 protected function normalizePhone($user)
 {
     $cleanPhone = null;
     $key = 'valid_phone';
     try {
         if (!($cleanPhone = UserExtend::parsePhone($user->phone))) {
             // Emails that contain numbers can be mistaken as a vanity number ( 800 GODMA )
             // so just for reporting purpose I check if the phone containts '@' is more likely it is an email
             $isEmail = preg_match('/@/', $user->phone);
             $key = $isEmail ? 'not_a_phone' : 'invalid_phone';
             $this->addToReport($user, $key, $user->phone);
         }
     } catch (\libphonenumber\NumberParseException $e) {
         $key = 'phone_empty';
         if (!empty($user->phone)) {
             $key = 'not_a_phone';
             $this->addToReport($user, $key, $user->phone);
         }
     }
     $this->increaseCounter($key);
     return $cleanPhone;
 }
Example #5
0
 /**
  * Register a user
  *
  * @param array $data
  * An array of attributes to register a user.
  * Any fields that are not properties on the user object
  * Will be applied to the Usermeta object
  *
  * @param array $rules
  * A set of validation rules to validate against
  * see http://laravel.com/docs/5.1/validation
  *
  * @return User $user
  * return the user object after registration
  */
 public static function register($data, $rules = [])
 {
     $rules += ['first_name' => 'required|min:2', 'last_name' => 'required|min:2', 'email' => 'required|email|between:2,64', 'password' => 'required|min:6', 'password_confirmation' => 'required|min:6'];
     Event::fire('auth.preRegister', [$data, $rules]);
     $validation = Validator::make($data, $rules);
     if ($validation->fails()) {
         throw new ValidationException($validation);
     }
     /*
      * Register user
      */
     $requireActivation = UserSettings::get('require_activation', true);
     $automaticActivation = UserSettings::get('activate_mode') == UserSettings::ACTIVATE_AUTO;
     $userActivation = UserSettings::get('activate_mode') == UserSettings::ACTIVATE_USER;
     /*
      * Data altercations
      */
     $data['first_name'] = ucwords($data['first_name']);
     $data['last_name'] = ucwords($data['last_name']);
     $data['birth_date'] = UserExtend::parseBirthdate($data['birthday']);
     $data['phone'] = UserExtend::parsePhone($data['phone']);
     $data['email_optin'] = isset($data['email_optin']) ? $data['email_optin'] : false;
     // Split the data into whats required for the user and usermeta models
     $userData = ['name' => $data['first_name'] . ' ' . $data['last_name'], 'password' => $data['password'], 'password_confirmation' => $data['password_confirmation'], 'email' => $data['email'], 'street_addr' => $data['street_addr'], 'city' => $data['city'], 'state' => $data['state'], 'zip' => $data['zip'], 'phone' => $data['phone']];
     $user = Auth::register($userData, $automaticActivation);
     // Save user metadata
     $usermeta = Usermeta::create($data);
     $user->metadata()->save($usermeta);
     if (isset($data['avatar'])) {
         UserExtend::uploadAvatar($user, $data['avatar']);
     }
     /*
      * Activation is by the user, send the email
      */
     if ($userActivation) {
         $this->sendActivationEmail($user);
     }
     /*
      * Automatically activated or not required, log the user in
      */
     if ($automaticActivation || !$requireActivation) {
         Auth::login($user);
     }
     if ($user) {
         /*
          * Fire event that user has registered
          */
         Event::fire('auth.register', [$user]);
         return $user;
     }
     return false;
 }
Example #6
0
 /**
  * Save the users profile
  */
 public function onSave()
 {
     $user = $this->getUser();
     $vars = post();
     foreach ($vars as $key => $val) {
         if ($key == 'metadata') {
             foreach ($val as $metakey => $metaval) {
                 $user->metadata->{$metakey} = $metaval;
             }
         } else {
             if ($key == "phone") {
                 $val = UserExtend::parsePhone($val);
             }
             $user->{$key} = $val;
         }
     }
     if ($user->push()) {
         Flash::info(Lang::get('dma.friends::lang.user.save'));
     } else {
         Flash::error(Lang::get('dma.friends::lang.user.saveFailed'));
     }
     return ['#flashMessages' => $this->renderPartial('@flashMessages')];
 }
Example #7
0
 /**
  * @SWG\Definition(
  *     definition="request.avatar",
  *     type="object",
  *     required={"source"},
  *     @SWG\Property(
  *         description="Source can be one of the URLs returned by  users/profile-options/avatar endpoint or by uploading a Base64 encode string of a JPG, PNG or GIF",
  *         property="source",
  *         type="string"
  *     )
  * )
  * 
  * @SWG\Post(
  *     path="users/{id}/upload-avatar",
  *     summary="Change user avatar",
  *     description="Change user avatar. Avatar must be a valid JPG, GIF or PNG. And not bigger that 400x400 pixels.",
  *     tags={ "user"},
  *
  *     @SWG\Parameter(
  *         description="ID of user to fetch",
  *         format="int64",
  *         in="path",
  *         name="id",
  *         required=true,
  *         type="integer"
  *     ),
  *
  *     @SWG\Parameter(
  *         description="Avatar payload",
  *         name="body",
  *         in="body",
  *         required=true,
  *         schema=@SWG\Schema(ref="#/definitions/request.avatar")
  *     ),
  *     @SWG\Response(
  *         response=200,
  *         description="Successful response",
  *         @SWG\Schema(
  *              @SWG\Property(
  *                  property="success",
  *                  type="boolean"
  *              )
  *         )
  *     ),
  *     @SWG\Response(
  *         response=500,
  *         description="Unexpected error",
  *         @SWG\Schema(ref="#/definitions/error500")
  *     ),
  *     @SWG\Response(
  *         response=404,
  *         description="User not found",
  *         @SWG\Schema(ref="#/definitions/UserError404")
  *     )
  * )
  */
 public function uploadAvatar($userId)
 {
     if (is_null($user = User::find($userId))) {
         return Response::api()->errorNotFound('User not found');
     }
     $data = Request::all();
     $rules = ['source' => 'required'];
     $validation = Validator::make($data, $rules);
     if ($validation->fails()) {
         return $this->errorDataValidation('Data fails to validated', $validation->errors());
     }
     if ($source = array_get($data, 'source', null)) {
         // Check if is a selected avatar from the theme
         $avatars = $this->getThemeAvatarOptions();
         $avatars = array_keys($avatars);
         $keyAvatar = trim(strtolower(basename(basename($source))));
         if (in_array($keyAvatar, $avatars)) {
             UserExtend::uploadAvatar($user, $source);
         } else {
             UserExtend::uploadAvatarFromString($user, $source);
         }
         return ['success' => true];
     }
 }
 /** 
  * Process and determine if an award can be issued
  * based on a provided activity code
  *
  * @param object $user
  * A user model for which the activity should act upon
  * 
  * @param array $params
  * An array of parameters for validating activities 
  *
  * @return boolean
  * returns true if the process was successful
  */
 public static function process(User $user, $params = [])
 {
     $activity = $params['activity'];
     if (self::canComplete($activity, $user)) {
         if ($user->activities()->save($activity)) {
             Event::fire('dma.friends.activity.completed', [$activity, $user]);
             // log an entry to the activity log
             FriendsLog::activity(['user' => $user, 'object' => $activity]);
             // Award points
             $userExtend = new UserExtend($user);
             $userExtend->addPoints($activity->points);
             // Hand everything off to the badges
             BadgeManager::applyActivityToBadges($user, $activity);
             $messages = Session::get('activityMessage');
             if (!is_array($messages) && $messages) {
                 $messages = [$messages];
             }
             $message = !empty(trim(strip_tags($activity->complete_message))) ? $activity->complete_message : Lang::get('dma.friends::lang.activities.codeSuccess', ['title' => $activity->title]);
             $messages[] = $message;
             Session::put('activityMessage', $messages);
             return $activity;
         }
     }
     return false;
 }
Example #9
0
 /**
  * Complete the step and proceed to complete a badge if it can be completed
  *
  * @param Step $step
  * A step model
  * @param User $user
  * A user model
  */
 private static function completeBadge(Step $step, User $user)
 {
     $badge = $step->badge;
     // Check badge global limit
     if ($badge->maximum_earnings_global > 0 && count($badge->users) > $badge->maximum_earnings_global) {
         return false;
     }
     // Complete step
     try {
         $user->steps()->save($step);
         Event::fire('dma.friends.step.completed', [$step, $user]);
     } catch (Exception $e) {
         throw new Exception(Lang::get('dma.friends::lang.exceptions.stepFailed'));
     }
     // See if the user has completed all steps for a badge
     foreach ($badge->steps as $step) {
         if (!$user->steps->contains($step->id)) {
             //user did not complete a step in badge so we cannot complete the badge
             return;
         }
     }
     try {
         // If loop completes with out returning false the user has completed all steps
         $user->badges()->save($badge);
         $userExtend = new UserExtend($user);
         $userExtend->addPoints($badge->points);
         Event::fire('dma.friends.badge.completed', [$badge, $user]);
         // log an entry to the activity log
         FriendsLog::unlocked(['user' => $user, 'object' => $badge]);
         if ($badge->congratulations_text) {
             $notificationText = $badge->congratulations_text;
         } else {
             $notificationText = Lang::get('dma.friends::lang.badges.completed', ['title' => $badge->title]);
         }
         //Flash::info($notificationText);
         Postman::send('simple', function (NotificationMessage $notification) use($user, $badge, $notificationText) {
             // Set user
             $notification->to($user, $user->name);
             // Send code and activity just in case we want to use in the template
             $notification->addData(['badge' => $badge]);
             $notification->message($notificationText);
         }, ['flash', 'kiosk']);
     } catch (Exception $e) {
         throw new Exception(Lang::get('dma.friends::lang.exceptions.badgeFailed'));
     }
 }