PHP User::getNickname Examples

PHP User::getNickname - 23 examples found. These are the top rated real world PHP examples of User::getNickname extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
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 #2
0
 public function run()
 {
     $msg = "";
     $to = 1;
     $user = new User();
     if (isset($_REQUEST['str'])) {
         $email = mysql_real_escape_string(base64_decode($_REQUEST['str']));
         $confirm_string = substr($_REQUEST['cs'], 0, 10);
         // verify the email belongs to a user
         if ($user->findUserByUsername($email) && substr($user->getConfirm_string(), 0, 10) == $confirm_string) {
             $sql = "\n                    UPDATE " . USERS . "\n                    SET\n                        confirm_string = '',\n                        confirm = 1,\n                        is_active = 1\n                    WHERE username = '" . $email . "'";
             mysql_query($sql);
             // send welcome email
             Utils::sendTemplateEmail($user->getUsername(), 'welcome', array('nickname' => $user->getNickname()), 'Worklist <contact@worklist.net>');
             User::login($user, false);
             //Optionally can login with confirm URL
             $jumbotron = "\n                    <h2>Welcome to Worklist!</h2>\n                    <p>\n                      Click on a job and add your bid, or come join us in our \n                      <a href='https://gitter.im/highfidelity/worklist' target='_blank'>public chat room</a>.\n                      Questions? Check out the <a href='./help'>help tab</a>.\n                    </p>";
         } else {
             Utils::redirect('./');
         }
     } elseif (isset($_REQUEST['ppstr'])) {
         // paypal address confirmation
         $paypal_email = mysql_real_escape_string(base64_decode($_REQUEST['ppstr']));
         $hash = mysql_real_escape_string($_REQUEST['pp']);
         // verify the email belongs to a user
         if (!$user->findUserByPPUsername($paypal_email, $hash)) {
             // hacking attempt, or some other error
             Utils::redirect('./');
         } else {
             $user->setPaypal_verified(true);
             $user->setPaypal_hash('');
             $user->save();
             $jumbotron = "\n                    <h2>Thank you for confirming your Paypal address.</h2>\n                    <p>You can now bid on items in the Worklist!</p>";
         }
     } elseif (isset($_REQUEST['emstr'])) {
         // new email address confirmation
         $new_email = mysql_real_escape_string(base64_decode($_REQUEST['emstr']));
         if (!$user->findUserByUsername($_SESSION['username'])) {
             Utils::redirect('login');
             //we are not logged in
         }
         //save new email
         $user->setUsername($new_email);
         $user->save();
         $_SESSION['username'] = $new_email;
         $jumbotron = "<h2>Thank you for confirming your changed email address.</h2>";
     }
     $jobs = new JobController();
     $jobs->view->jumbotron = $jumbotron;
     $jobs->listView();
 }
 /**
  * @param User $user
  */
 public function signIn($user)
 {
     $userID = $user->getId();
     $this->setAttribute('subscriber_id', $userID, self::SUBSCRIBER_NAMESPACE);
     $this->setAuthenticated(true);
     $this->setAttribute('nickname', $user->getNickname(), self::SUBSCRIBER_NAMESPACE);
     $this->addCredential('subscriber');
     if ($user->getIsModerator()) {
         $this->addCredential('moderator');
     }
     if ($user->getIsAdministrator()) {
         $this->addCredential('administrator');
     }
     $this->setHasAgents();
     $this->setHasVocabulary();
     $this->setHasSchema();
 }
Example #4
0
//$newPoint = new Point(0, 'Foyer');
//echo $newPoint->getName();
echo '<h2>Ok id etu</h2>';
$User = new User('6362', 2, '', 1);
echo $User->getState();
echo '<h2>Ok id buckutt</h2>';
$User = new User('1', 3, '', 1);
echo $User->getState();
echo '<h2>Ok login</h2>';
$User = new User('bernardx', 1, '', 1);
echo $User->getState();
echo '<h2>usr inconnu</h2>';
$User = new User('636462', 2, '', 1);
echo $User->getState();
echo $User->getFirstname();
echo '<h2>Avec mot de passe</h2>';
$User = new User('bernardx', 1, 'toto');
echo $User->getState() . '<br />';
echo $User->getId() . '<br />';
echo $User->getFirstname() . '<br />';
echo $User->getLastname() . '<br />';
echo $User->getNickname() . '<br />';
echo $User->getMail() . '<br />';
echo $User->getCredit() . '<br />';
echo $User->getIp();
/*
echo '<h2>Avec mot de passe faux</h2>';
$User = new User('6362', 2, 'pezfzev');
echo $User->getState();
echo $User->getLastname();
*/
Example #5
0
 /**
  * Deny acces to a special section. Sets a deny message and forwards the user to the login site.
  * @author  Clemens John <clemens-john@gmx.de>
  */
 public static function denyAccess($permission = false, $owner = false)
 {
     // if $permission is != false, then get the Names of the Roles that are wrapped into $permission
     if ($permission) {
         $role_string = "";
         foreach (Permission::getRolesByPermission($permission) as $key => $role) {
             if ($key) {
                 $role_string .= ", ";
             }
             $role_string .= permission::getRoleNameByRoleNumber($role);
         }
     }
     if ($owner) {
         $user = new User($owner);
         $user->fetch();
     }
     // prepare the "permission denied"-message for the user based on the combination of $permission and $owner
     if ($permission and !$owner) {
         $message[] = array("Auf diesen Bereich dürfen nur Benutzer mit den folgenden Rechten zugreifen: " . $role_string, 2);
     } elseif (!$permission and $owner) {
         $message[] = array("Auf diesen Bereich darf nur der Benutzer " . $user->getNickname() . " zugreifen.", 2);
     } elseif ($permission and $owner) {
         $message[] = array("Auf diesen Bereich dürfen nur der Benutzer " . $user->getNickname() . " oder Benutzer mit den folgenden Rechten zugreifen: " . $role_string, 2);
     } else {
         $message[] = array("Du darfst auf diesen Bereich nicht zugreifen.", 2);
     }
     // set the message
     Message::setMessage($message);
     // redirect the user to the last page he visited if it was a page inside netmon
     // if the page was not inside netmon, redirect to the default path
     if (!empty($_SESSION['last_page']) and $_SESSION['last_page'] != $_SESSION['current_page']) {
         header('Location: ' . $_SESSION['last_page']);
     } else {
         header('Location: ./');
     }
 }
Example #6
0
 public function acceptBid($bid_id, $budget_id = 0, $is_mechanic = true)
 {
     $this->conditionalLoadByBidId($bid_id);
     /*if ($this->hasAcceptedBids()) {
           throw new Exception('Can not accept an already accepted bid.');
       }*/
     $user_id = isset($_SESSION['userid']) ? (int) $_SESSION['userid'] : 0;
     $is_runner = isset($_SESSION['is_runner']) ? (int) $_SESSION['is_runner'] : 0;
     // If a bid is being accepted, and the runner for the workitem does not exist (incase a bid went from suggested straight
     // to working) or is different than current user, then we should set the person accepting the bid as the runner;
     if ($this->getRunnerId() != $user_id) {
         $this->setRunnerId($user_id);
     }
     $res = mysql_query('SELECT * FROM `' . BIDS . '` WHERE `id`=' . $bid_id);
     $bid_info = mysql_fetch_assoc($res);
     $workitem_info = $this->getWorkItem($bid_info['worklist_id']);
     // Get bidder information
     $bidder = new User();
     if (!$bidder->findUserById($bid_info['bidder_id'])) {
         // If bidder doesn't exist, return false. Don't want to throw an
         // exception because it would kill multiple bid acceptances
         return false;
     }
     $bid_info['nickname'] = $bidder->getNickname();
     $project = new Project($this->getProjectId());
     // Get the repo for this project
     $repository = $this->getRepository();
     $job_id = $this->getId();
     /* Verify whether the user already has this repo forked on his account
      *If not create the fork
      *Check for existing unix account in dev.  If new, make call to create account
      */
     $GitHubUser = new User($bid_info['bidder_id']);
     $url = TOWER_API_URL;
     $fields = array('action' => 'create_unixaccount', 'nickname' => $bidder->getNickname());
     $result = CURLHandler::Post($url, $fields);
     if (!$GitHubUser->verifyForkExists($project)) {
         $forkStatus = $GitHubUser->createForkForUser($project);
         $bidderEmail = $bidder->getUsername();
         $emailTemplate = 'forked-repo';
         $data = array('project_name' => $forkStatus['data']['full_name'], 'nickname' => $bidder->getNickname(), 'users_fork' => $forkStatus['data']['git_url'], 'master_repo' => str_replace('https://', 'git://', $project->getRepository()));
         $senderEmail = 'Worklist <contact@worklist.net>';
         Utils::sendTemplateEmail($bidderEmail, $emailTemplate, $data, $senderEmail);
         sleep(10);
     }
     // Create a branch for the user
     if (!$forkStatus['error']) {
         $branchStatus = $GitHubUser->createBranchForUser($job_id, $project);
         $bidderEmail = $bidder->getUsername();
         $emailTemplate = 'branch-created';
         $data = array('branch_name' => $job_id, 'nickname' => $bidder->getNickname(), 'users_fork' => $forkStatus['data']['git_url'], 'master_repo' => str_replace('https://', 'git://', $project->getRepository()));
         $bid_info = array_merge($data, $bid_info);
     }
     if (!$branchStatus['error']) {
         $bid_info['sandbox'] = $branchStatus['branch_url'];
     }
     $bid_info['bid_done'] = strtotime('+' . $bid_info['bid_done_in'], time());
     // Adding transaction wrapper around steps
     if (mysql_query('BEGIN')) {
         $is_runner_or_assignee = $is_runner || $this->getAssigned_id() == $user_id;
         // changing mechanic of the job
         $sql = "UPDATE `" . WORKLIST . "` SET " . ($is_mechanic ? "`mechanic_id` =  '" . $bid_info['bidder_id'] . "', " : '') . ($is_runner_or_assignee && $user_id > 0 && $workitem_info['runner_id'] != $user_id ? "`runner_id` =  '" . $user_id . "', " : '') . " `status` = 'In Progress',`status_changed`=NOW(),`sandbox` = '" . $bid_info['sandbox'] . "',`budget_id` = " . $budget_id . " WHERE `" . WORKLIST . "`.`id` = " . $bid_info['worklist_id'];
         if (!($myresult = mysql_query($sql))) {
             error_log("AcceptBid:UpdateMechanic failed: " . mysql_error());
             mysql_query("ROLLBACK");
             return false;
         }
         // marking bid as "accepted"
         if (!($result = mysql_query("UPDATE `" . BIDS . "` SET `accepted` =  1, `bid_done` = FROM_UNIXTIME('" . $bid_info['bid_done'] . "') WHERE `id` = " . $bid_id))) {
             error_log("AcceptBid:MarkBid failed: " . mysql_error());
             mysql_query("ROLLBACK");
             return false;
         }
         // adding bid amount to list of fees
         if (!($result = mysql_query("INSERT INTO `" . FEES . "` (`id`, `worklist_id`, `amount`, `user_id`, `desc`, `bid_notes`, `date`, `bid_id`) VALUES (NULL, " . $bid_info['worklist_id'] . ", '" . $bid_info['bid_amount'] . "', '" . $bid_info['bidder_id'] . "', 'Accepted Bid', '" . mysql_real_escape_string($bid_info['notes']) . "', NOW(), '{$bid_id}')"))) {
             error_log("AcceptBid:Insert Fee failed: " . mysql_error());
             mysql_query("ROLLBACK");
             return false;
         }
         $creator_fee = 0;
         $creator_fee_desc = 'Creator';
         $creator_fee_added = false;
         $runner_fee = 0;
         $runner_fee_desc = 'Designer';
         $runner_fee_added = false;
         $accepted_bid_amount = $bid_info['bid_amount'];
         $fee_category = '';
         $is_expense = '';
         $is_rewarder = '';
         $fees = $this->getFees($this->getId());
         foreach ($fees as $fee) {
             // find the accepted bid amount
             if ($fee['desc'] == 'Accepted Bid') {
                 $accepted_bid_amount = $fee['amount'];
             }
             if (preg_match($reviewer_fee_desc, $fee['desc'])) {
                 $reviewer_fee_added = true;
             }
             if ($fee['desc'] == $creator_fee_desc) {
                 $creator_fee_added = true;
             }
             if ($fee['desc'] == $runner_fee_desc) {
                 $runner_fee_added = true;
             }
         }
         // get project creator role settings, if not available, no fee is added
         // and will need to be added manually if applicable
         $project = new Project();
         $project_roles = $project->getRoles($this->getProjectId(), "role_title = 'Creator'");
         if (count($project_roles) != 0 && !$creator_fee_added) {
             // fees are not automatically created for internal users
             if (!$this->getCreator()->isInternal()) {
                 $creator_role = $project_roles[0];
                 if ($creator_role['percentage'] !== null && $creator_role['min_amount'] !== null) {
                     $creator_fee = $creator_role['percentage'] / 100 * $accepted_bid_amount;
                     if ((double) $creator_fee < $creator_role['min_amount']) {
                         $creator_fee = $creator_role['min_amount'];
                     }
                     // add the fee
                     /**
                      * @TODO - We call addfees and then deduct from budget
                      * seems we should add the deduction process to the Fee::add
                      * function
                      *
                      */
                     Fee::add($this->getId(), $creator_fee, $fee_category, $creator_fee_desc, $this->getCreatorId(), $is_expense, $is_rewarder);
                     // and reduce the runners budget
                     $myRunner = new User();
                     $myRunner->findUserById($this->getRunnerId());
                     $myRunner->updateBudget(-$creator_fee, $this->getBudget_id());
                 }
             }
         }
         $project_roles = $project->getRoles($this->getProjectId(), "role_title = 'Runner'");
         if (count($project_roles) != 0 && !$runner_fee_added) {
             error_log("[FEES] we have a role for runner");
             $runner_role = $project_roles[0];
             // fees are not automatically created for internal users
             if (!$this->getRunner()->isInternal()) {
                 if ($runner_role['percentage'] !== null && $runner_role['min_amount'] !== null) {
                     $runner_fee = $runner_role['percentage'] / 100 * $accepted_bid_amount;
                     if ((double) $runner_fee < $runner_role['min_amount']) {
                         $runner_fee = $runner_role['min_amount'];
                     }
                     // add the fee
                     Fee::add($this->getId(), $runner_fee, $fee_category, $runner_fee_desc, $this->getRunnerId(), $is_expense, $is_rewarder);
                     // and reduce the runners budget
                     $myRunner = new User();
                     $myRunner->findUserById($this->getRunnerId());
                     $myRunner->updateBudget(-$runner_fee, $this->getBudget_id());
                 }
             }
         }
         // add an entry to the status log
         $status_sql = "\n                INSERT INTO " . STATUS_LOG . " (worklist_id, status, user_id, change_date)\n                VALUES({$bid_info['worklist_id']}, 'Working', {$_SESSION['userid']}, NOW())";
         if (!($result = mysql_query($status_sql))) {
             error_log("AcceptedBid:Insert status log failed: " . mysql_error());
             mysql_query("ROLLBACK");
             return false;
         }
         // When we get this far, commit and return bid_info
         if (mysql_query('COMMIT')) {
             $bid_info['summary'] = $workitem_info['summary'];
             $this->setMechanicId($bid_info['bidder_id']);
             return $bid_info;
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
Example #7
0
 public function view($id)
 {
     try {
         $project = Project::find($id);
     } catch (Exception $e) {
         $error = $e->getMessage();
         die($error);
     }
     $is_runner = !empty($_SESSION['is_runner']) ? 1 : 0;
     $is_payer = !empty($_SESSION['is_payer']) ? 1 : 0;
     //get the project owner
     $project_user = new User();
     $project_user->findUserById($project->getOwnerId());
     $this->write('project_user', $project_user);
     $userId = Session::uid();
     if ($userId > 0) {
         Utils::initUserById($userId);
         $user = new User();
         $user->findUserById($userId);
         // @TODO: this is overwritten below..  -- lithium
         $nick = $user->getNickname();
         $userbudget = $user->getBudget();
         $budget = number_format($userbudget);
         $is_owner = $project->isOwner($user->getId());
         $is_admin = $user->getIs_admin();
     } else {
         $is_owner = false;
         $is_admin = false;
     }
     $runners = $project->getRunners();
     if (isset($_REQUEST['save_project']) && ($is_runner || $is_payer || $is_owner)) {
         $project->setDescription($_REQUEST['description'])->setShortDescription($_REQUEST['short_description']);
         $project->setWebsite($_REQUEST['website']);
         $cr_anyone = $_REQUEST['cr_anyone'] ? 1 : 0;
         $cr_3_favorites = $_REQUEST['cr_3_favorites'] ? 1 : 0;
         $cr_project_admin = isset($_REQUEST['cr_project_admin']) ? 1 : 0;
         $cr_users_specified = isset($_REQUEST['cr_users_specified']) ? 1 : 0;
         $cr_job_runner = isset($_REQUEST['cr_job_runner']) ? 1 : 0;
         $internal = isset($_REQUEST['internal']) ? 1 : 0;
         $require_sandbox = isset($_REQUEST['require_sandbox']) ? 1 : 0;
         $hipchat_enabled = isset($_REQUEST['hipchat_enabled']) ? 1 : 0;
         $project->setCrAnyone($cr_anyone);
         $project->setCrFav($cr_3_favorites);
         $project->setCrAdmin($cr_project_admin);
         $project->setCrRunner($cr_job_runner);
         $project->setCrUsersSpecified($cr_users_specified);
         $project->setHipchatEnabled($hipchat_enabled);
         $project->setHipchatNotificationToken($_REQUEST['hipchat_notification_token']);
         $project->setHipchatRoom($_REQUEST['hipchat_room']);
         $project->setHipchatColor($_REQUEST['hipchat_color']);
         if ($user->getIs_admin()) {
             $project->setInternal($internal);
         }
         if ($user->getIs_admin()) {
             $project->setRequireSandbox($require_sandbox);
         }
         if ($_REQUEST['logoProject'] != "") {
             $project->setLogo(basename($_REQUEST['logoProject']));
         }
         $project->save();
         // we clear post to prevent the page from redirecting
         $_POST = array();
     }
     $project_id = $project->getProjectId();
     $hide_project_column = true;
     // save,edit,delete roles <mikewasmie 16-jun-2011>
     if ($is_runner || $is_payer || $project->isOwner($userId)) {
         if (isset($_POST['save_role'])) {
             $args = array('role_title', 'percentage', 'min_amount');
             foreach ($args as $arg) {
                 ${$arg} = mysql_real_escape_string($_POST[$arg]);
             }
             $role_id = $project->addRole($project_id, $role_title, $percentage, $min_amount);
         }
         if (isset($_POST['edit_role'])) {
             $args = array('role_id', 'role_title', 'percentage', 'min_amount');
             foreach ($args as $arg) {
                 ${$arg} = mysql_real_escape_string($_POST[$arg]);
             }
             $res = $project->editRole($role_id, $role_title, $percentage, $min_amount);
         }
         if (isset($_POST['delete_role'])) {
             $role_id = mysql_real_escape_string($_POST['role_id']);
             $res = $project->deleteRole($role_id);
         }
     }
     /* Prevent reposts on refresh */
     if (!empty($_POST)) {
         unset($_POST);
         header('Location: ' . $projectName);
         exit;
     }
     $edit_mode = false;
     if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit' && ($is_admin || $is_owner)) {
         $edit_mode = true;
     }
     $this->write('project', $project);
     $this->write('edit_mode', $edit_mode);
     $this->write('is_owner', $is_owner);
     parent::run();
 }
Example #8
0
function setFavorite()
{
    if (!isset($_REQUEST['favorite_user_id']) || !isset($_REQUEST['newVal'])) {
        echo json_encode(array('error' => "Invalid parameters!"));
    }
    $userId = Session::uid();
    if ($userId > 0) {
        Utils::initUserById($userId);
        $user = new User();
        $user->findUserById($userId);
        $favorite_user_id = (int) $_REQUEST['favorite_user_id'];
        $newVal = (int) $_REQUEST['newVal'];
        $users_favorites = new Users_Favorite();
        $res = $users_favorites->setMyFavoriteForUser($userId, $favorite_user_id, $newVal);
        if ($res == "") {
            // send chat if user has been marked a favorite
            $favorite_user = new User();
            $favorite_user->findUserById($favorite_user_id);
            if ($newVal == 1) {
                $resetUrl = SECURE_SERVER_URL . 'user/' . $favorite_user_id;
                $resetUrl = '<a href="' . $resetUrl . '" title="Your profile">' . $resetUrl . '</a>';
                $data = array();
                $data['link'] = $resetUrl;
                $nick = $favorite_user->getNickname();
                if (!Utils::sendTemplateEmail($favorite_user->getUsername(), 'trusted', $data)) {
                    error_log("setFavorite: Utils::send_email failed on favorite notification");
                }
                // get favourite count
                $count = $users_favorites->getUserFavoriteCount($favorite_user_id);
                if ($count > 0) {
                    if ($count == 1) {
                        $message = "**{$count}** person";
                    } else {
                        $message = "**{$count}** people";
                    }
                    $journal_message = '@' . $nick . ' is now trusted by ' . $message . '!';
                    //sending journal notification
                    Utils::systemNotification(stripslashes($journal_message));
                }
            }
            echo json_encode(array('return' => "Trusted saved."));
        } else {
            echo json_encode(array('error' => $res));
        }
    } else {
        echo json_encode(array('error' => "You must be logged in!"));
    }
}
Example #9
0
            header('Location: user.php?user_id=' . $_GET['user_id']);
        } else {
            header('Location: user_edit.php?section=edit&user_id=' . $_GET['user_id']);
        }
    } else {
        Permission::denyAccess(PERM_ROOT, (int) $_GET['user_id']);
    }
} elseif ($_GET['section'] == "delete") {
    if (permission::checkIfUserIsOwnerOrPermitted(PERM_ROOT, (int) $_GET['user_id'])) {
        if ($_POST['delete'] == "true") {
            //fetch user data
            $user = new User((int) $_GET['user_id']);
            $user->fetch();
            //logout user if the logged in user is the user to be deleted
            if ($_GET['user_id'] == $_SESSION['user_id']) {
                Login::user_logout();
            }
            //delete user
            $user->delete();
            $message[] = array("Der Benutzer " . $user->getNickname() . " wurde gelöscht.", 1);
            message::setMessage($message);
            header('Location: index.php');
        } else {
            $message[] = array("Sie müssen das Häckchen bei <i>Ja</i> setzen um den Benutzer zu löschen.", 2);
            message::setMessage($message);
            header('Location: user_edit.php?section=edit&user_id=' . $_GET['user_id']);
        }
    } else {
        Permission::denyAccess(PERM_ROOT, (int) $_GET['user_id']);
    }
}
Example #10
0
        $message = $sql->query('
			SELECT connector_id, subject
			FROM ' . DB_PREFIX . 'pm
			WHERE id = ' . u3 . ' AND folder != 1')->fetch(PDO::FETCH_ASSOC);
        $form['subject'] = 'Re: ' . $message['subject'];
    } else {
        $message = $sql->query('
			SELECT connector_id, subject, message
			FROM ' . DB_PREFIX . 'pm
			WHERE id = ' . (int) u3 . ' AND folder = 1')->fetch(PDO::FETCH_ASSOC);
        $form['subject'] = $message['subject'];
        $form['message'] = $message['message'];
    }
    $form['receiver'] = User::getNickname(BY_ID, $message['connector_id']);
} elseif (ctype_digit(u2)) {
    $form['receiver'] = User::getNickname(BY_ID, u2);
}
if ($_POST['send']) {
    // Form values
    $form = array('receiver' => filter($_POST['receiver'], 100), 'subject' => filter($_POST['subject'], 100), 'save' => $_POST['save'], 'bbcode' => $_POST['bbcode'] ? BBCODE : 0, 'emoticons' => $_POST['emoticons'] ? EMOTICONS : 0, 'autolinks' => $_POST['autolinks'] ? AUTOLINKS : 0, 'message' => filter($_POST['message'], 250));
    $err->receiver_empty(t('ERROR_RECEIVER_EMPTY'), !$form['receiver']);
    $err->receiver_not_exists(t('ERROR_RECEIVER_NOT_EXISTS'), $form['receiver'] && !User::getId(BY_NICKNAME, $form['receiver']));
    $err->subject_empty(t('ERROR_SUBJECT_EMPTY'), !$form['subject']);
    $err->message_empty(t('ERROR_MESSAGE_EMPTY'), !$form['message']);
    // No errors
    if (!$err->count()) {
        $form['receiver'] = User::getId(BY_NICKNAME, $form['receiver']);
        $form['message'] = cut($form['message'], $cfg->pm['message_max']);
        $form['parsers'] = $form['bbcode'] . $form['autolinks'] . $form['emoticons'] . CENSURE . PRE;
        $stmt = $sql->prepare('
			INSERT INTO ' . DB_PREFIX . 'pm
Example #11
0
 public function getContent()
 {
     global $sql;
     $this->err = new Error();
     $pager = new Pager('guestbook', Kio::getStat('entries', 'guestbook'), Kio::getConfig('limit', 'guestbook'));
     if (Kio::getConfig('order_by', 'guestbook') == 'DESC') {
         $x = $pager->items + 1 - $pager->offset;
         $y = '$x--;';
     } else {
         $x = $pager->offset;
         $y = '$x++;';
     }
     //		$entries = $sql->getCache('guestbook_'.$pager->current);
     if (!$entries) {
         $stmt = $sql->query('
	SELECT gb.id, gb.added, gb.author, gb.email, gb.website, gb.message, gb.author_id, gb.author_ip,
		u.nickname, u.group_id, u.avatar, u.signature
	FROM ' . DB_PREFIX . 'guestbook gb
	LEFT JOIN ' . DB_PREFIX . 'users u ON u.id = gb.author_id
	ORDER BY gb.id ' . Kio::getConfig('order_by', 'guestbook') . '
	LIMIT ' . $pager->limit . '
	OFFSET ' . $pager->offset);
         if ($stmt->rowCount()) {
             while ($row = $stmt->fetch()) {
                 eval($y);
                 $row['number'] = $x;
                 if ($row['author_id']) {
                     $row['author'] = User::format($row['author_id'], $row['nickname'], $row['group_id']);
                 }
                 $row['message'] = parse($row['message'], Kio::getConfig('parsers', 'guestbook'));
                 $row['signature'] = $row['signature'] ? parse($row['signature'], Kio::getConfig('parsers', 'guestbook')) : '';
                 $entries[] = $row;
             }
             $sql->putCacheContent('guestbook_' . $pager->current, $entries);
         } else {
             $this->note->info('Jeszcze nikt nie dodał żadnego wpisu.');
         }
     }
     // Editing entry
     if (ctype_digit(u2)) {
         // guestbook/edit/u2
         $edited_id = u1 == 'edit' ? u2 : '';
         if (!User::hasPermit('guestbook edit')) {
             $this->note->error(t('You do not have access to edit entries.'));
         } else {
             if ($edited_id) {
                 $row = $sql->query('
		SELECT id, added, author, author_id, author_ip, email, website, message
		FROM ' . DB_PREFIX . 'guestbook
		WHERE id = ' . $edited_id)->fetch();
                 // Entry exists
                 if ($row) {
                     $form = $row;
                     $form['edit_mode'] = true;
                     if (!$row['author']) {
                         $form['author'] = User::getNickname(BY_ID, $row['author_id']);
                     }
                 } else {
                     $this->note->error(t('Selected entry doesn&apos;t exist.'));
                 }
             }
         }
     }
     if (!$form['edit_mode']) {
         $form['author'] = User::$nickname;
     }
     // Form action
     $add = $_POST['add'] ? true : false;
     $edit = $_POST['edit'] ? true : false;
     // On form submit
     if ($add || $edit) {
         $this->formSumbit();
     } else {
         if (ctype_digit($_POST['delete_id']) && $_POST['auth'] == AUTH && User::hasPermit('guestbook delete')) {
             $sql->exec('
	UPDATE ' . DB_PREFIX . 'stats SET content = content - 1 WHERE name = "guestbook_entries";
	DELETE FROM ' . DB_PREFIX . 'guestbook WHERE id = ' . $_POST['delete_id']);
             $sql->clearCacheGroup('guestbook_*');
         }
     }
     try {
         $tpl = new PHPTAL('modules/guestbook/guestbook.tpl.html');
         $tpl->message_limit = Kio::getConfig('message_max', 'guestbook');
         $tpl->form = $form;
         $tpl->entries = $entries;
         $tpl->err = $this->err->toArray();
         $tpl->note = $this->note;
         $tpl->pagination = $pager->getLinks();
         return $tpl->execute();
     } catch (Exception $e) {
         return template_error($e);
     }
 }
Example #12
0
 public function getContent()
 {
     global $sql;
     $this->err = new Error();
     $this->pager = new Pager('guestbook', Kio::getStat('entries', 'guestbook'), Kio::getConfig('limit', 'guestbook'));
     $show_form = true;
     $entries = $this->getEntries();
     // Editing entry
     if (ctype_digit(u2)) {
         // guestbook/edit/u2
         $edited_id = u1 == 'edit' ? u2 : '';
         if (!User::hasPermit('guestbook edit')) {
             $this->note->error(t('You don&apos;t have access to edit entries.'));
             $show_form = false;
         } else {
             if ($edited_id) {
                 $row = $sql->query('
		SELECT id, added, author, author_id, author_ip, email, website, message
		FROM ' . DB_PREFIX . 'guestbook
		WHERE id = ' . $edited_id)->fetch();
                 // Entry exists
                 if ($row) {
                     $form = $row;
                     $this->edit_mode = true;
                     if (!$row['author']) {
                         $form['author'] = User::getNickname(BY_ID, $row['author_id']);
                     }
                 } else {
                     $this->note->error(t('Selected entry doesn&apos;t exist.'));
                 }
             }
         }
     }
     if (!$this->edit_mode) {
         $form['author'] = User::$nickname;
     }
     // Form action
     $add = isset($_POST['add']) ? true : false;
     $edit = isset($_POST['edit']) ? true : false;
     // On form submit
     if ($add || $edit) {
         $form = $this->formSumbit();
     } else {
         if (isset($_POST['delete_id']) && ctype_digit($_POST['delete_id']) && $_POST['auth'] == AUTH && User::hasPermit('guestbook delete')) {
             $sql->exec('
	UPDATE ' . DB_PREFIX . 'stats SET content = content - 1 WHERE name = "guestbook_entries";
	DELETE FROM ' . DB_PREFIX . 'guestbook WHERE id = ' . $_POST['delete_id']);
             $sql->clearCacheGroup('guestbook_*');
         }
     }
     try {
         $tpl = new PHPTAL('modules/guestbook/guestbook.tpl.html');
         $tpl->message_limit = Kio::getConfig('message_max', 'guestbook');
         $tpl->form = $form;
         $tpl->edit_mode = $this->edit_mode;
         $tpl->entries = $entries;
         $tpl->err = $this->err->toArray();
         $tpl->show_form = $show_form;
         $tpl->note = $this->note;
         $tpl->pagination = $this->pager->getLinks();
         return $tpl->execute();
     } catch (Exception $e) {
         return template_error($e);
     }
 }
Example #13
0
 case 'get-rewarder-list':
     $period = $rewarder->getPeriod($_REQUEST['period_id']);
     $rewarderList = $rewarder->getRewarderUserList($period['id']);
     $json = json_encode(array(0, $rewarderList, $period));
     echo $json;
     break;
 case 'get-audit-list':
     $rewarderList = $rewarder->getRewarderAuditList();
     $json = json_encode($rewarderList);
     echo $json;
     break;
 case 'get-rewarder-user-detail':
     $detailUser = new User();
     $detailUser->findUserById($_REQUEST['id']);
     $rewarderList = $rewarder->getRewarderUserDetail($_REQUEST['id']);
     $json = json_encode(array($detailUser->getNickname(), $rewarderList));
     echo $json;
     break;
 case 'update-rewarder-auditor':
     $auditorUser = new User();
     $auditorUser->findUserById($_REQUEST['id']);
     $toggledAuditor = $auditorUser->getIs_auditor() ? 0 : 1;
     $auditorUser->getIs_auditor($toggledAuditor);
     $auditorUser->save();
     break;
 case 'update-rewarder-user':
     $period_id = $_REQUEST['period_id'];
     $rewardeeId = intval($_REQUEST["id"]);
     $points_val = isset($_REQUEST["points_val"]) ? max(0, intval($_REQUEST["points_val"])) : 0;
     $points_perc = isset($_REQUEST["points_perc"]) ? max(0, floatval($_REQUEST["points_perc"])) : 0;
     $delete = isset($_REQUEST["delete"]) ? intval($_REQUEST["delete"]) : 0;
Example #14
0
 function getContent()
 {
     global $cfg, $user, $sql, $plug;
     $note = new Notifier();
     $tpl = new PHPTAL('plugins/comments/comments.tpl.html');
     $err = new Error();
     $tpl->entries = '';
     if ($this->total_comments != -1 && !Kio::getConfig('view_only_logged', 'comments')) {
         if ($this->total_comments > 0) {
             $tpl->backlink = $this->backlink;
             $tpl->cfg = $cfg;
             $tpl->user = $user;
             $tpl->entries = $this->getEntries();
         } else {
             $note->info('There is no comments.');
         }
         if (!Kio::getConfig('add_only_logged', 'comments') || LOGGED) {
             if ($this->edited) {
                 $form = array('id' => $this->edited['comment_id'], 'author' => $this->edited['comment_author'], 'author_id' => $this->edited['comment_author_id'], 'message' => $this->edited['comment_message']);
                 if (!$form['author']) {
                     $form['author'] = User::getNickname(BY_ID, $this->edited['comment_author_id']);
                 }
                 $this->edit_mode = true;
             } else {
                 $form['author'] = User::$nickname;
             }
             $add = isset($_POST['add']) ? true : false;
             $edit = isset($_POST['edit']) ? true : false;
             // Add or delete
             if (isset($_POST['add']) || $edit) {
                 $form['author'] = isset($_POST['add']) && LOGGED ? User::$nickname : filter($_POST['author'], 100);
                 $form['message'] = filter($_POST['message'], Kio::getConfig('message_max', 'comments'));
                 $err->setError('author_empty', t('Author field is required.'))->condition(!$form['author']);
                 $err->setError('author_exists', t('Entered nickname is registered.'))->condition($add && !LOGGED && is_registered($form['author'], 'nickname'));
                 $err->setError('message_empty', t('Message field is required.'))->condition(!$form['message']);
                 // No errors
                 if ($err->noErrors()) {
                     // Add
                     if (isset($_POST['add'])) {
                         $sql->exec('
					INSERT INTO ' . DB_PREFIX . 'comments (
						comment_owner, comment_owner_child_id, comment_author,
						comment_author_id, comment_author_ip, comment_added,
						comment_message, comment_backlink)
					VALUES(
						"' . u0 . '",
						' . $this->connector_id . ',
						"' . (!LOGGED || isset($_POST['edit']) ? $form['author'] : '') . '",
						' . UID . ',
						"' . IP . '",
						' . TIMESTAMP . ',
						"' . $form['message'] . '",
						"' . $this->backlink . '")');
                         $last = $sql->lastInsertId();
                         $sql->exec('
					UPDATE ' . DB_PREFIX . $this->owner . '
					SET comments = (comments + 1)
					WHERE id = ' . $this->connector_id);
                         setcookie(COOKIE . '-comments', 'true', TIMESTAMP + Kio::getConfig('flood_interval', 'comments') + 1, '/');
                         redirect(HREF . PATH . '#comment-' . $last);
                     } else {
                         if (isset($_POST['edit'])) {
                             if ($form['author_id'] = User::getId(BY_NICKNAME, $form['author'])) {
                                 $form['author'] = '';
                             } else {
                                 $form['author_id'] = 0;
                             }
                             $sql->exec('
					UPDATE ' . DB_PREFIX . 'comments
					SET
						comment_author = "' . $form['author'] . '",
						comment_author_id = ' . $form['author_id'] . ',
						comment_message = "' . $form['message'] . '"
					WHERE comment_id = ' . $this->edited['comment_id']);
                             redirect(HREF . $this->edited['comment_backlink'] . '#comment-' . $this->edited['comment_id']);
                         }
                     }
                 } else {
                     $note->error($err->toArray());
                 }
             } else {
                 if (isset($_POST['delete_id']) && ctype_digit($_POST['delete_id'])) {
                     $sql->exec('
			DELETE FROM ' . DB_PREFIX . 'comments WHERE comment_id = ' . $_POST['delete_id'] . ';
			UPDATE ' . DB_PREFIX . $this->owner . ' SET comments = (comments - 1) WHERE id = ' . $this->connector_id);
                     redirect(strpos(REFERER, 'admin') ? REFERER : '#comments');
                 }
             }
             //$tpl->comments = $comments;
             $tpl->form = $form;
             $tpl->err = $err->toArray();
         } else {
             $note->error(sprintf('Dodawanie komentarzy jest możliwe tylko dla <a href="%1$slogin">zalogowanych</a> osób, <a href="%1$sregistration">zarejestruj się</a> jeśli nie masz jeszcze konta.', HREF));
         }
     } else {
         if ($this->total_comments != -1) {
             $note->error(array('Komentarze są widoczne tylko dla zalogowanych osób.', '<a href="' . HREF . 'registration">Zarejestruj się</a> jeśli nie masz jeszcze konta.'));
         }
     }
     $tpl->edit_mode = $this->edit_mode;
     $tpl->total_comments = $this->total_comments;
     $tpl->note = $note;
     return $tpl->execute();
 }
Example #15
0
 public function info($id)
 {
     $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : false;
     $this->write('tab', isset($_REQUEST['tab']) ? $_REQUEST['tab'] : "");
     $reqUserId = Session::uid();
     $this->write('reqUserId', $reqUserId);
     $reqUser = new User();
     if ($reqUserId > 0) {
         $reqUser->findUserById($reqUserId);
         $budget = $reqUser->getBudget();
     }
     $this->write('reqUser', $reqUser);
     $is_runner = isset($_SESSION['is_runner']) ? $_SESSION['is_runner'] : 0;
     $is_payer = isset($_SESSION['is_payer']) ? $_SESSION['is_payer'] : 0;
     // admin posting data
     if (!empty($_POST) && ($is_runner || $is_payer) && !$action) {
         $user_id = (int) $_POST['user_id'];
         if (!empty($_POST['save-salary'])) {
             $field = 'salary';
             $value = mysql_real_escape_string($_POST['value']);
         } else {
             $field = $_POST['field'];
             $value = (int) $_POST['value'];
         }
         $updateUser = new User();
         if ($updateUser->findUserById($user_id)) {
             switch ($field) {
                 case 'salary':
                     $updateUser->setAnnual_salary($value);
                     Utils::systemNotification("A new salary has been set for @" . $updateUser->getNickname());
                     break;
                 case 'ispayer':
                     $updateUser->setIs_payer($value);
                     break;
                 case 'isrunner':
                     $updateUser->setIs_runner($value);
                     break;
                 case 'isinternal':
                     $updateUser->setIs_internal($value);
                     break;
                 case 'ispaypalverified':
                     $updateUser->setPaypal_verified($value);
                     if ($value) {
                         $updateUser->setHas_w2(false);
                     }
                     break;
                 case 'isw2employee':
                     $updateUser->setHas_w2($value);
                     if ($value) {
                         $updateUser->setPaypal_verified(false);
                         $updateUser->setw9_status('not-applicable');
                     }
                     break;
                 case 'manager':
                     $updateUser->setManager($value);
                     if ($value) {
                         $manager = new User();
                         $manager->findUserById($value);
                         // Send journal notification
                         Utils::systemNotification("The manager for @" . $updateUser->getNickname() . " is now set to @" . $manager->getNickname());
                     } else {
                         Utils::systemNotification("The manager for @" . $updateUser->getNickname() . " has been removed");
                     }
                     break;
                 case 'referrer':
                     $updateUser->setReferred_by($value);
                     if ($value) {
                         $referrer = new User();
                         $referrer->findUserById($value);
                         // Send journal notification
                         Utils::systemNotification("The referrer for @" . $updateUser->getNickname() . " is now set to @" . $referrer->getNickname());
                     } else {
                         Utils::systemNotification("The referrer for @" . $updateUser->getNickname() . " has been removed");
                     }
                     break;
                 case 'isactive':
                     $updateUser->setIs_active($value);
                     break;
                 default:
                     break;
             }
             $updateUser->save();
             $response = array('succeeded' => true, 'message' => 'User details updated successfully');
             echo json_encode($response);
             exit(0);
         } else {
             die(json_encode(array('succeeded' => false, 'message' => 'Error: Could not determine the user_id')));
         }
     }
     $user = new User();
     $user = User::find($id ? $id : Session::uid());
     $userId = $user->getId();
     /**
      * If we couldn't find a valid User, return an ErrorView
      */
     if (!$user->getId()) {
         $this->write('msg', 'That user doesn\'t exist.');
         $this->write('link', WORKLIST_URL);
         $this->view = new ErrorView();
         parent::run();
     }
     $this->write('userId', $userId);
     $this->write('user', $user);
     $this->write('Annual_Salary', $user->getAnnual_salary() > 0 ? $user->getAnnual_salary() : '');
     $this->write('manager', $user->getManager());
     $this->write('referred_by', $user->getReferred_by());
     if ($action == 'create-sandbox') {
         $result = array();
         try {
             if (!$is_runner) {
                 throw new Exception("Access Denied");
             }
             $args = array('unixusername', 'projects');
             foreach ($args as $arg) {
                 ${$arg} = mysql_real_escape_string($_REQUEST[$arg]);
             }
             $projectList = explode(",", str_replace(" ", "", $projects));
             // Create sandbox for user
             $sandboxUtil = new SandBoxUtil();
             $sandboxUtil->createSandbox($user->getUsername(), $user->getNickname(), $unixusername, $projectList);
             // If sb creation was successful, update users table
             $user->setHas_sandbox(1);
             $user->setUnixusername($unixusername);
             $user->setProjects_checkedout($projects);
             $user->save();
             // add to project_users table
             foreach ($projectList as $project) {
                 $project_id = Project::getIdFromRepo($project);
                 $user->checkoutProject($project_id);
             }
         } catch (Exception $e) {
             $result["error"] = $e->getMessage();
         }
         echo json_encode($result);
         die;
     }
     $reviewee_id = (int) $userId;
     $review = new Review();
     $this->write('reviewsList', $review->getReviews($reviewee_id, $reqUserId));
     $this->write('projects', $this->getProjectList());
     $user_projects = $user->getProjects_checkedout();
     $this->write('has_sandbox', count($user_projects) > 0);
     $users_favorite = new Users_Favorite();
     $favorite_enabled = 1;
     $favorite = $users_favorite->getMyFavoriteForUser($reqUserId, $userId);
     if (isset($favorite['favorite'])) {
         $favorite_enabled = $favorite['favorite'];
     }
     $favorite_count = $users_favorite->getUserFavoriteCount($userId);
     $this->write('favorite_count', $favorite_count);
     $this->write('favorite_enabled', $favorite_enabled);
     parent::run();
 }
Example #16
0
 public function listView($projectName = null, $filterName = null)
 {
     $this->view = new JobsView();
     // $nick is setup above.. and then overwritten here -- lithium
     $nick = '';
     $userId = Session::uid();
     if ($userId > 0) {
         Utils::initUserById($userId);
         $user = new User();
         $user->findUserById($userId);
         // @TODO: this is overwritten below..  -- lithium
         $nick = $user->getNickname();
         $userbudget = $user->getBudget();
         $budget = number_format($userbudget);
         $this->is_internal = $user->isInternal();
     }
     $this->is_runner = !empty($_SESSION['is_runner']) ? 1 : 0;
     $is_payer = !empty($_SESSION['is_payer']) ? 1 : 0;
     $is_admin = !empty($_SESSION['is_admin']) ? 1 : 0;
     $workitem = new WorkItem();
     $queryFilter = empty($_REQUEST['query']) ? '' : $_REQUEST['query'];
     $this->write('queryFilter', $queryFilter);
     $this->write('followingFilter', $filterName != null && $filterName == "following" ? true : false);
     if ($projectName != null && $projectName != "all") {
         $project = Project::find($projectName);
         $this->write('projectFilter', $project ? $project->getProjectId() : 0);
     } else {
         $this->write('projectFilter', 0);
     }
     if ($filterName != null && $filterName != "following") {
         $this->write('statusFilter', $filterName);
     } else {
         $this->write('statusFilter', empty($queryFilter) ? 'Active' : 'All');
     }
     $this->write('labelsFilter', array_slice(func_get_args(), 2));
     // Prevent reposts on refresh
     if (!empty($_POST)) {
         unset($_POST);
         $this->view = null;
         Utils::redirect('./jobs');
         exit;
     }
     $worklist_id = isset($_REQUEST['job_id']) ? intval($_REQUEST['job_id']) : 0;
     $this->write('req_status', isset($_GET['status']) ? $_GET['status'] : '');
     $this->write('review_only', isset($_GET['status']) && $_GET['status'] == 'needs-review' ? 'true' : 'false');
     parent::run();
 }
Example #17
0
 public function testLoadByUsernameIsCaseInsensitive()
 {
     $failureAffects = "Login cannot load users case insensitive";
     $dbConfig = array();
     $dbConfig['adapter'] = 'mysqli';
     $dbConfig['host'] = 'mysql.dev.sendlove.us';
     $dbConfig['dbname'] = 'LM_logintest';
     $dbConfig['username'] = 'LM_logintest';
     $dbConfig['password'] = 'a8f0bfedef741c7285f88012c126d06e';
     $userId = 2;
     // load by username test case insensitivity
     $user = new User(new mysqli($dbConfig['host'], $dbConfig['username'], $dbConfig['password'], $dbConfig['dbname']));
     $user->loadByUsername('ExistingUser@domain.com');
     $this->assertEquals($userId, $user->getId(), $failureAffects);
     $this->assertEquals('existingUser@domain.com', $user->getUsername(), $failureAffects);
     $this->assertTrue($user->authenticate('9*NvF6rU'), $failureAffects);
     $this->assertEquals('existingUser', $user->getNickname(), $failureAffects);
     $this->assertEquals(User::USER_CONFIRMED, $user->getConfirmed(), $failureAffects);
     $this->assertEquals('2010-09-15 17:38:53', $user->getDateAdded(), $failureAffects);
     $this->assertEquals('0000-00-00 00:00:00', $user->getDateModified(), $failureAffects);
 }
Example #18
0
 public static function sendReviewNotification($reviewee_id, $type, $oReview)
 {
     $review = $oReview[0]['feeRange'] . " " . $oReview[0]['review'];
     $reviewee = new User();
     $reviewee->findUserById($reviewee_id);
     $worklist_link = WORKLIST_URL;
     $to = $reviewee->getNickname() . ' <' . $reviewee->getUsername() . '>';
     $body = "<p>" . $review . "</p>";
     $nickname = $reviewee->getNickname();
     $headers = array();
     if ($type == "new") {
         $userinfo_link = WORKLIST_URL . 'user/?id=' . $reviewee->getId();
         $headers['From'] = 'worklist<donotreply@worklist.net>';
         $subject = 'New Peer Review';
         $journal = '@' . $nickname . " received a new review: " . $review;
         $body = '<p>Hello ' . $nickname . ',</p><br />';
         $body .= '<p>You have received a review from one of your peers in the Worklist.</p><br />';
         $body .= '<p>To see your current user reviews, click <a href="' . $userinfo_link . '">here</a>.</p>';
         $body .= '<p><a href="' . $userinfo_link . '">' . $userinfo_link . '</a></p><br />';
         $body .= '<p><a href="' . WORKLIST_URL . '"jobs>worklist' . '</a></p>';
     } else {
         if ($type == "update") {
             $subject = "A review of you has been updated";
             $journal = "A review of @" . $nickname . " has been updated: " . $review;
         } else {
             $subject = "One of your reviews has been deleted";
             $journal = "One review of @" . $nickname . " has been deleted: " . $review;
         }
     }
     if (!Utils::send_email($to, $subject, $body, null, $headers)) {
         error_log("Utils::sendReviewNotification: Utils::send_email failed");
     }
     Utils::systemNotification($journal);
 }
Example #19
0
<?php

session_start();
$user = new User();
if ($user->selectByEmail(Database::sessionDecrypt($_SESSION['user']))) {
    if ($_POST['update'] == 'true') {
        $user->setNickname($_POST['nick']);
        $user->setCellPhone($_POST['phone']);
        $user->setName($_POST['name']);
        $user->setSurname($_POST['surname']);
        if ($user->update()) {
            echo ReturnCode::$success;
        } else {
            echo ReturnCode::$error;
        }
    } else {
        echo $user->getNickname() . PHP_EOL;
        echo $user->getName() . PHP_EOL;
        echo $user->getSurname() . PHP_EOL;
        echo $user->getCellPhone();
    }
} else {
    echo ReturnCode::$userNotFound;
}
Example #20
0
 private function closeOutBudgetSource($remainingFunds, $budget, $budgetReceiver, $budgetGiver)
 {
     $sources = $budget->loadSources(" ORDER BY s.transfer_date DESC");
     if ($sources == null) {
         $this->setOutput(array('success' => true, 'message' => 'No source budget found!'));
         exit;
     }
     foreach ($sources as $source) {
         $budgetGiver = new User();
         if (!$budgetGiver->findUserById($source["giver_id"])) {
             $this->setOutput(array('success' => true, 'message' => 'Invalid giver id.'));
             exit;
         }
         if ($remainingFunds < 0) {
             if ($budget->seed != 1) {
                 $budget->updateSources($source["source_id"], -$remainingFunds);
                 $budgetGiver->updateBudget($remainingFunds, $source["budget_id"]);
             }
             $this->sendBudgetcloseOutEmail(array("budget_id" => $budget->id, "reason" => $budget->reason, "giver_id" => $source["giver_id"], "receiver_id" => $budget->receiver_id, "receiver_nickname" => $budgetReceiver->getNickname(), "receiver_email" => $budgetReceiver->getUsername(), "giver_nickname" => $budgetGiver->getNickname(), "giver_email" => $budgetGiver->getUsername(), "remainingFunds" => $remainingFunds, "original_amount" => $budget->original_amount, "amount" => $budget->amount, "seed" => $budget->seed));
             return;
         } else {
             if ($remainingFunds > $source["amount_granted"]) {
                 $remainingFundsToGiveBack = $source["amount_granted"];
                 $remainingFunds = $remainingFunds - $source["amount_granted"];
             } else {
                 $remainingFundsToGiveBack = $remainingFunds;
                 $remainingFunds = 0;
             }
             if ($budget->seed != 1) {
                 $budget->updateSources($source["source_id"], -$remainingFundsToGiveBack);
                 $budgetGiver->updateBudget($remainingFundsToGiveBack, $source["budget_id"]);
             }
             $this->sendBudgetcloseOutEmail(array("budget_id" => $budget->id, "reason" => $budget->reason, "giver_id" => $source["giver_id"], "receiver_id" => $budget->receiver_id, "receiver_nickname" => $budgetReceiver->getNickname(), "receiver_email" => $budgetReceiver->getUsername(), "giver_nickname" => $budgetGiver->getNickname(), "giver_email" => $budgetGiver->getUsername(), "remainingFunds" => $remainingFundsToGiveBack, "original_amount" => $budget->original_amount, "amount" => $budget->amount, "seed" => $budget->seed));
             if ($remainingFunds == 0) {
                 return;
             }
         }
     }
     if ($remainingFunds != 0) {
         error_log("closeOutBudgetSource, remainingFunds not equal to 0, budget id: " . $budget->id);
     }
 }
Example #21
0
 /**
  * Synchronise data between GitHub and Worklist User
  *
  * @param User $user Worklist User object
  * @param object $gh_user GitHub User JSON object
  */
 public function sync($user, $gh_user)
 {
     /**
      * Compare User nickname with GitHub login. If they differ,
      * verify the GitHub login does not already exist in Worklist.
      *
      * If it exists, try the GitHub name with spaces removed
      * If it sill exists, append a random number to the login, and
      * to the name, until we get a unique Worklist nickname
      */
     if ($user->getNickname() != $gh_user->login) {
         $nicknameTestUser = new User();
         $nickname = $gh_user->login;
         if ($nicknameTestUser->findUserByNickname($nickname)) {
             $nickname = preg_replace('/[^a-zA-Z0-9]/', '', $gh_user->name);
         }
         while ($nicknameTestUser->findUserByNickname($nickname)) {
             $rand = mt_rand(1, 99999);
             $nickname = $gh_user->login . $rand;
             if ($nicknameTestUser->findUserByNickname($nickname)) {
                 $nickname = preg_replace('/[^a-zA-Z0-9]/', '', $gh_user->name) . $rand;
             }
         }
         $user->setNickname($nickname);
     }
     // save the name to the worklist database
     if (isset($gh_user->name)) {
         $fullname = $gh_user->name;
         $nameArray = explode(' ', $fullname);
         $user->setFirst_name($nameArray[0]);
         $user->setLast_name(end($nameArray));
     }
     $user->setPicture($gh_user->avatar_url);
     $user->save();
 }
/**
 * Notify a user that one of their notices has been chosen as a 'fave'
 *
 * @param User    $rcpt   The user whose notice was faved
 * @param Profile $sender The user who faved the notice
 * @param Notice  $notice The notice that was faved
 *
 * @return void
 */
function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
{
    if (!$rcpt->receivesEmailNotifications() || !$rcpt->getConfigPref('email', 'notify_fave')) {
        return;
    }
    // This test is actually "if the sender is sandboxed"
    if (!$sender->hasRight(Right::EMAILONFAVE)) {
        return;
    }
    if ($rcpt->hasBlocked($sender)) {
        // If the author has blocked us, don't spam them with a notification.
        return;
    }
    // We need the global mail.php for various mail related functions below.
    require_once INSTALLDIR . '/lib/mail.php';
    $bestname = $sender->getBestName();
    common_switch_locale($rcpt->language);
    // TRANS: Subject for favorite notification e-mail.
    // TRANS: %1$s is the adding user's long name, %2$s is the adding user's nickname.
    $subject = sprintf(_('%1$s (@%2$s) added your notice as a favorite'), $bestname, $sender->getNickname());
    // TRANS: Body for favorite notification e-mail.
    // TRANS: %1$s is the adding user's long name, $2$s is the date the notice was created,
    // TRANS: %3$s is a URL to the faved notice, %4$s is the faved notice text,
    // TRANS: %5$s is a URL to all faves of the adding user, %6$s is the StatusNet sitename,
    // TRANS: %7$s is the adding user's nickname.
    $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s" . " as one of their favorites.\n\n" . "The URL of your notice is:\n\n" . "%3\$s\n\n" . "The text of your notice is:\n\n" . "%4\$s\n\n" . "You can see the list of %1\$s's favorites here:\n\n" . "%5\$s"), $bestname, common_exact_date($notice->created), common_local_url('shownotice', array('notice' => $notice->id)), $notice->content, common_local_url('showfavorites', array('nickname' => $sender->getNickname())), common_config('site', 'name'), $sender->getNickname()) . mail_footer_block();
    $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());
    common_switch_locale();
    mail_to_user($rcpt, $subject, $body, $headers);
}
Example #23
0
 private function getComposeForm()
 {
     global $sql;
     Kio::addTitle(t('Compose message'));
     Kio::addBreadcrumb(t('Compose message'), 'pm/write');
     $err = new Error();
     $note = new Notifier();
     if ((u2 == 'resend' || u2 == 'reply') && ctype_digit(u3)) {
         if (u2 == 'reply') {
             $message = $sql->query('
		SELECT connector_id, subject
		FROM ' . DB_PREFIX . 'pm
		WHERE id = ' . u3 . ' AND folder != 1')->fetch(PDO::FETCH_ASSOC);
             $form['subject'] = 'Re: ' . $message['subject'];
         } else {
             $message = $sql->query('
		SELECT connector_id, subject, message
		FROM ' . DB_PREFIX . 'pm
		WHERE id = ' . (int) u3 . ' AND folder = 1')->fetch(PDO::FETCH_ASSOC);
             $form['subject'] = $message['subject'];
             $form['message'] = $message['message'];
         }
         $form['receiver'] = User::getNickname(BY_ID, $message['connector_id']);
     } else {
         if (ctype_digit(u2)) {
             $form['receiver'] = User::getNickname(BY_ID, u2);
         }
     }
     if (isset($_POST['send'])) {
         // Form values
         $form = array('receiver' => filter($_POST['receiver'], 100), 'subject' => filter($_POST['subject'], 100), 'save' => $_POST['save'], 'bbcode' => $_POST['bbcode'] ? BBCODE : 0, 'emoticons' => $_POST['emoticons'] ? EMOTICONS : 0, 'autolinks' => $_POST['autolinks'] ? AUTOLINKS : 0, 'message' => filter($_POST['message'], 250));
         $err->setError('receiver_empty', t('ERROR_RECEIVER_EMPTY'))->condition(!$form['receiver']);
         $err->setError('receiver_not_exists', t('ERROR_RECEIVER_NOT_EXISTS'))->condition($form['receiver'] && !User::getId(BY_NICKNAME, $form['receiver']));
         $err->setError('subject_empty', t('ERROR_SUBJECT_EMPTY'))->condition(!$form['subject']);
         $err->setError('message_empty', t('ERROR_MESSAGE_EMPTY'))->condition(!$form['message']);
         // No errors
         if ($err->noErrors()) {
             $form['receiver'] = User::getId(BY_NICKNAME, $form['receiver']);
             $form['message'] = cut($form['message'], Kio::getConfig('message_max', 'pm'));
             $form['parsers'] = $form['bbcode'] . $form['autolinks'] . $form['emoticons'] . CENSURE . PRE;
             $stmt = $sql->prepare('
		INSERT INTO ' . DB_PREFIX . 'pm
			(sent, owner_id, connector_id, subject, message, folder, is_read, parsers)
		VALUES
			(:sent, :owner_id, :connector_id, :subject, :message, :folder, :is_read, :parsers)' . ($form['save'] ? ', (:sent, :owner_id, :connector_id, :subject, :message, :folder, :is_read, :parsers)' : ''));
             $stmt->execute(array('sent' => TIMESTAMP, 'owner_id' => $form['receiver'], 'connector_id' => UID, 'subject' => $form['subject'], 'message' => $form['message'], 'folder' => 0, 'is_read' => 0, 'parsers' => $form['parsers']));
             setcookie(COOKIE . '-pm', 'true', TIMESTAMP + Kio::getConfig('flood_interval', 'pm') + 1, '/');
             $note->success('Wiadomość została wysłana.');
             redirect(HREF . 'pm/inbox');
         } else {
             $note->error($err->toArray());
         }
     } else {
         $note->info(array(t('WELCOME_MESSAGE'), t('REQUIRED')));
     }
     try {
         $tpl = new PHPTAL('modules/pm/write.tpl.html');
         $tpl->err = $err->toArray();
         $tpl->form = $form;
         $tpl->note = $note;
         return $tpl->execute();
     } catch (Exception $e) {
         return template_error($e);
     }
 }