示例#1
0
 public static function start($save_path, $session_name)
 {
     Session::$sid = session_id();
     //This is a core PHP function.  Save that a session has been started in the default server log.
     //error_log('Starting Session ' . $session_name . " ". $this->sid);//DEBUG//
     /*
      * Get the userID of the saved session (if exists).
      * If the query returns no valid rows (ie: this is a NEW session),
      * $data will be a blank array, thus never tripping the foreach and preserving $this->uid as FALSE.
      */
     $rs = Typeframe::Database()->prepare("SELECT `uid`\r\n      FROM #__sessions\r\n      WHERE `sid` = ? AND `ip_addr` = ? LIMIT 1");
     $rs->execute(Session::$sid, REMOTE_IP);
     /**
      * The session is NEW.  Create it.
      */
     if ($rs->recordcount() == 0) {
         $rs2 = Typeframe::Database()->prepare("INSERT INTO #__sessions\r\n        (`sid`, `ip_addr`, `uid`, `expires`)\r\n        VALUES\r\n        (?, ?, ?, ?)");
         $rs2->execute(Session::$sid, REMOTE_IP, 0, Session::$ttl + time());
     } else {
         $data = $rs->fetch_array();
         Session::$uid = $data['uid'];
         $rs2 = Typeframe::Database()->prepare("UPDATE #__sessions\r\n        SET `expires` = ?\r\n        WHERE `sid` = ? AND `ip_addr` = ?");
         $rs2->execute(Session::$ttl + time(), Session::$sid, REMOTE_IP);
     }
 }
示例#2
0
 public function runners()
 {
     $active = $this->read('activeUsers');
     $runners = User::getUserList(Session::uid(), $active, 1, true);
     $ret = array();
     $default = isset($_REQUEST['runner']) ? $_REQUEST['runner'] : null;
     foreach ($runners as $runner) {
         $ret[] = array('id' => $runner->getId(), 'nickname' => $runner->getNickname(), 'selected' => $default === $runner->getId());
     }
     return $ret;
 }
示例#3
0
 public function __construct()
 {
     parent::__construct();
     $this->name = strtolower(preg_replace('/Layout$/', '', get_class($this)));
     $user_id = Session::uid();
     $user = User::find($user_id);
     $this->currentUser['id'] = $user_id;
     $this->currentUser['username'] = $user_id ? $user->getUsername() : '';
     $this->currentUser['nickname'] = $user_id ? $user->getNickname() : '';
     $this->currentUser['is_runner'] = empty($_SESSION['is_runner']) ? false : true;
     $this->currentUser['runningProjects'] = json_encode($user->getProjectsAsRunner());
     $this->currentUser['is_payer'] = empty($_SESSION['is_payer']) ? false : true;
     $this->currentUser['is_admin'] = !$user->getIs_admin() ? false : true;
     if ($user_id) {
         Utils::initUserById($user_id);
         $user->findUserById($user_id);
         $this->currentUser['budget'] = array('feeSums' => Fee::getSums(), 'totalManaged' => money_format('$ %i', $user->getTotalManaged()), 'remainingFunds' => money_format('$ %i', $user->setRemainingFunds()), 'allocated' => money_format('$ %i', $user->getAllocated()), 'submitted' => money_format('$ %i', $user->getSubmitted()), 'paid' => money_format('$ %i', $user->getPaid()), 'transfered' => money_format('$ %i', $user->getTransfered()), 'transfersDetails' => $user->getBudgetTransfersDetails(), 'available' => $user->getBudget());
         $this->currentUser['can'] = array('addProject' => $user->getIs_admin() || $user->isRunner() || $user->isPaypalVerified());
         $this->currentUser['is_internal'] = $user->isInternal();
         $this->currentUser['budgetAuthorized'] = strpos(BUDGET_AUTHORIZED_USERS, "," . $user_id . ",") !== false;
     }
 }
示例#4
0
 public function setPaid($id, $paid)
 {
     try {
         $user = User::find(Session::uid());
         // Check if we have a payer
         if (!$user->isPayer()) {
             throw new Exception('Nothing to see here. Move along!');
         }
         // Get clean data
         $paid = $paid ? true : false;
         $notes = trim($_POST['notes']);
         if (!$notes) {
             throw new Exception('You must write a note!');
         }
         $fund_id = Fee::getFundId($id);
         // Exit of this script
         if (!Fee::markPaidById($id, $user->getId(), $notes, $paid, false, $fund_id)) {
             throw new Exception('Payment Failed!');
         }
         /* Only send the email when marking as paid. */
         if ($paid) {
             $fee = Fee::getFee($fee_id);
             $workitem = new WorkItem($fee['worklist_id']);
             $summary = $workitem->getSummary();
             $fee_user = User::find($fee['user_id']);
             $subject = "Worklist.net paid you " . $fee['amount'] . " for " . $summary;
             $body = "Your Fee was marked paid.<br/>" . "Job <a href='" . SERVER_URL . $fee['worklist_id'] . "'>#" . $fee['worklist_id'] . ': ' . $summary . '</a><br/>' . "Fee Description : " . nl2br($fee['desc']) . "<br/>" . "Paid Notes : " . nl2br($notes) . "<br/><br/>" . "Contact the job Designer with any questions<br/><br/>Worklist.net<br/>";
             if (!Utils::send_email($fee_user->getUsername(), $subject, $body)) {
                 error_log("FeeController::setPaid: Utils::send_email failed");
             }
         }
         return $this->setOutput(array('success' => true, 'notes' => 'Payment has been saved!'));
     } catch (Exception $e) {
         return $this->setOutput(array('success' => false, 'notes' => $e->getMessage()));
     }
 }
示例#5
0
 public static function getSums()
 {
     $sum = array();
     if (Session::uid()) {
         $r = mysql_query("SELECT SUM(`amount`) AS `sum_amount` FROM `" . FEES . "` WHERE `user_id` = {$_SESSION['userid']} AND\n                              `worklist_id` IN (SELECT `id` FROM `" . WORKLIST . "` WHERE `status` = 'Done') AND YEAR(DATE) = YEAR(NOW()) AND\n                               MONTH(`date`) = MONTH(NOW()) AND withdrawn != 1;") or exit(mysql_error());
         $sum['month'] = mysql_fetch_object($r)->sum_amount;
         if (is_numeric($sum['month'])) {
             $sum['month'] = money_format('%i', $sum['month']);
         } else {
             $sum['month'] = '0.00';
         }
         $r = mysql_query("SELECT SUM(`amount`) AS `sum_amount` FROM `" . FEES . "` WHERE `user_id` = {$_SESSION['userid']} AND\n                              `worklist_id` IN (SELECT `id` FROM `" . WORKLIST . "` WHERE `status` = 'Done') AND YEAR(DATE) = YEAR(NOW()) AND\n                               WEEK(`date`) = WEEK(NOW()) AND withdrawn != 1;") or exit(mysql_error());
         $sum['week'] = mysql_fetch_object($r)->sum_amount;
         if (is_numeric($sum['week'])) {
             $sum['week'] = money_format('%i', $sum['week']);
         } else {
             $sum['week'] = '0.00';
         }
     } else {
         $sum['month'] = '0.00';
         $sum['week'] = '0.00';
     }
     return $sum;
 }
示例#6
0
 /**
  * Used on github authorization between projects and users (see github.js)
  * Code moved from the old /GitHub.php file
  */
 public function connect()
 {
     $GitHub = new User(Session::uid());
     $workitem = new WorkItem();
     $workitem->loadById((int) $_GET['job']);
     $projectId = $workitem->getProjectId();
     $project = new Project($projectId);
     $connectResponse = $GitHub->processConnectResponse($project);
     if (!$connectResponse['error']) {
         if ($GitHub->storeCredentials($connectResponse['data']['access_token'], $project->getGithubId())) {
             $journal_message = sprintf("%s has been validated for project ##%s##", $GitHub->getNickname(), $project->getName());
             Utils::systemNotification($journal_message);
             Utils::redirect('./' . $workitem->getId());
         } else {
             // Something went wrong updating the users details, close this window and
             // display a proper error message to the user
             $message = 'Something went wrong and we could not complete the authorization process with GitHub. Please try again.';
         }
     } else {
         // We have an error on the response, close this window and display an error message
         // to the user
         $message = 'We received an error when trying to complete the authorization process with GitHub. Please notify a member of the O-Team for assistance.';
     }
     echo $message;
 }
示例#7
0
 public function deleteCodeReviewer($codeReviewer_id)
 {
     try {
         $team_id = $this->codeReviewersGitHubTeamId();
         if (!$team_id) {
             return false;
         }
         $user = User::find(Session::uid());
         $token = $user->authTokenForGitHubId(GITHUB_OAUTH2_CLIENT_ID);
         $client = new Github\Client(new Github\HttpClient\CachedHttpClient(array('cache_dir' => TEMP_DIR . DIRECTORY_SEPARATOR . 'github')));
         $client->authenticate($token, '', Github\Client::AUTH_URL_TOKEN);
         $user = User::find($codeReviewer_id);
         $gh_user = $user->getGitHubUserDetails($this);
         $nickname = $gh_user['data']['login'];
         $ret = $client->api('organizations')->teams()->removeMember($team_id, $nickname);
         return true;
     } catch (Exception $e) {
         return false;
     }
 }
示例#8
0
 public static function checkLogin()
 {
     if (!Session::uid()) {
         $_SESSION = array();
         session_destroy();
         if (!empty($_POST)) {
             $request_ip = $_SERVER['REMOTE_ADDR'];
             $request_uri = $_SERVER['REQUEST_URI'];
             error_log('Possible hack attempt from ' . $request_ip . ' on: ' . $request_uri);
             error_log(json_encode($_REQUEST));
             die('You are not authorized to post to this URL. Click ' . '<a href="' . SERVER_URL . '">here</a> to go to the main page. ' . "\n");
         }
         Utils::redirect('./github/login?expired=1&redir=' . urlencode($_SERVER['REQUEST_URI']));
         exit;
     }
 }
示例#9
0
 public function close($id)
 {
     try {
         $user = User::find(Session::uid());
         if (!$user->getId()) {
             throw new Exception('You have to be logged in to access user info!');
         }
         $budget_id = (int) $id;
         $budget = new Budget();
         if (!$budget->loadById($budget_id)) {
             throw new Exception('Invalid budget id');
         }
         if ($budget->active != 1) {
             throw new Exception('This budget is already closed.');
         }
         if ($user->getId() != $budget->receiver_id && $budget->giver_id != $user->getId()) {
             throw new Exception('Not enough rights');
         }
         $budgetGiver = new User();
         if (!$budgetGiver->findUserById($budget->giver_id)) {
             throw new Exception('Invalid giver id.');
         }
         $budgetReceiver = new User();
         if (!$budgetReceiver->findUserById($budget->receiver_id)) {
             throw new Exception('Invalid receiver id.');
         }
         // all the child budgets are closed ?
         $childrenNotClosed = $budget->getChildrenNotClosed($budget->id);
         if ($childrenNotClosed != 0) {
             throw new Exception("This budget has one or more sub-allocated budget that are still active. " . "You may not close out this budget until the other budgets are closed out.");
         }
         // all the budgeted jobs are paid ?
         $feeAmountNotPaid = $this->getSumOfFeeNotPaidByBudget($budget->id);
         if ($feeAmountNotPaid !== null) {
             throw new Exception('Some fees are not paid.');
         }
         $remainingFunds = $budget->getRemainingFunds();
         if ($remainingFunds >= 0) {
             $budget->original_amount = $budget->amount;
             $budget->amount = $budget->original_amount - $remainingFunds;
             $budget->active = 0;
             $budgetReceiver->updateBudget(-$remainingFunds, $budget->id, false);
             $this->closeOutBudgetSource($remainingFunds, $budget, $budgetReceiver, $budgetGiver);
             if (!$budget->save('id')) {
                 throw new Exception('Error in update budget.');
             }
         } else {
             if ($user->getId() == $budget->receiver_id) {
                 throw new Exception('Your budget is spent. Please contact the grantor (' . $budgetGiver->getNickname() . ') for additional funds.');
             }
             $budget->original_amount = $budget->amount;
             $budget->amount = $budget->original_amount - $remainingFunds;
             $budget->active = 0;
             $budgetReceiver->updateBudget(-$remainingFunds, $budget->id, false);
             $this->closeOutBudgetSource($remainingFunds, $budget, $budgetReceiver, $budgetGiver);
             if (!$budget->save('id')) {
                 throw new Exception('Error in update budget.');
             }
         }
         $this->setOutput(array('success' => true, 'message' => 'Budget closed'));
     } catch (Exception $e) {
         return $this->setOutput(array('success' => false, 'message' => $e->getMessage()));
     }
 }
示例#10
0
function pingTask()
{
    Utils::checkLogin();
    // Get sender Nickname
    $id = Session::uid();
    $user = User::find($id);
    $nickname = $user->getNickname();
    $email = $user->getUsername();
    $msg = $_REQUEST['msg'];
    $send_cc = isset($_REQUEST['cc']) ? (int) $_REQUEST['cc'] : false;
    // Get Receiver Info
    $receiver = User::find(intval($_REQUEST['userid']));
    $receiver_nick = $receiver->getNickname();
    $receiver_email = $receiver->getUsername();
    $mail_subject = $nickname . " sent you a message on Worklist";
    $mail_msg = "<p><a href='" . WORKLIST_URL . 'user/' . $id . "'>" . $nickname . "</a>";
    $mail_msg .= " sent you a message: ";
    $mail_msg .= "</p><p>----------<br/>" . nl2br($msg) . "<br />----------</p><p>You can reply via email to " . $email . "</p>";
    $headers = array('X-tag' => 'ping', 'From' => NOREPLY_SENDER, 'Reply-To' => '"' . $nickname . '" <' . $email . '>');
    if ($send_cc) {
        $headers['Cc'] = '"' . $nickname . '" <' . $email . '>';
    }
    if (!Utils::send_email($receiver_email, $mail_subject, $mail_msg, '', $headers)) {
        error_log("pingtask.php:!id: Utils::send_email failed");
    }
    echo json_encode(array());
}
示例#11
0
 /**
  *  This function notifies selected recipients about updates of workitems
  * except for currently logged in user
  *
  * @param Array $options - Array with options:
  * type - type of notification to send out
  * workitem - workitem object with updated data
  * recipients - array of recipients of the message ('creator', 'runner', 'mechanic')
  * emails - send message directly to list of emails (array) -
  * if 'emails' is passed - 'recipients' option is ignored
  * @param Array $data - Array with additional data that needs to be passed on
  * @param boolean $includeSelf - force user receive email from self generated action
  * example: 'who' and 'comment' - if we send notification about new comment
  */
 public static function workitemNotify($options, $data = null, $includeSelf = true)
 {
     $recipients = isset($options['recipients']) ? $options['recipients'] : null;
     $emails = isset($options['emails']) ? $options['emails'] : array();
     $workitem = $options['workitem'];
     $current_user = User::find(Session::uid());
     if (isset($options['project_name'])) {
         $project_name = $options['project_name'];
     } else {
         try {
             $project = new Project();
             $project->loadById($workitem->getProjectId());
             $project_name = $project->getName();
         } catch (Exception $e) {
             error_log($e->getMessage() . " Workitem: #" . $workitem->getId() . " " . " has an invalid project id:" . $workitem->getProjectId());
             $project_name = "";
         }
     }
     $revision = isset($options['revision']) ? $options['revision'] : null;
     $itemId = $workitem->getId();
     $itemLink = '<a href="' . WORKLIST_URL . $itemId . '">#' . $itemId . '</a>';
     $itemTitle = '#' . $itemId . ' (' . $workitem->getSummary() . ')';
     $itemTitleWithProject = '#' . $itemId . ': ' . $project_name . ': (' . $workitem->getSummary() . ')';
     $itemLinkTitle = '<a href="' . WORKLIST_URL . $itemId . '">#' . $itemId . ' - ' . $workitem->getSummary() . '</a>';
     $body = '';
     $subject = '#' . $itemId . ' ' . html_entity_decode($workitem->getSummary(), ENT_QUOTES);
     $from_address = '<noreply-' . $project_name . '@worklist.net>';
     $headers = array('From' => '"' . $project_name . '-' . strtolower($workitem->getStatus()) . '" ' . $from_address);
     switch ($options['type']) {
         case 'comment':
             $headers['From'] = '"' . $project_name . '-comment" ' . $from_address;
             $headers['Reply-To'] = '"' . $_SESSION['nickname'] . '" <' . $_SESSION['username'] . '>';
             $commentUrl = WORKLIST_URL . $workitem->getId() . '#comment-' . $data['comment-id'];
             $commentLink = ' <a href="' . $commentUrl . '">commented</a> ';
             $body .= $data['who'] . $commentLink . ' on ' . $itemLink . ':<br>' . nl2br($data['comment']) . '<br /><br />';
             if ($current_user->getSelf_notif()) {
                 array_push($emails, $current_user->getUsername());
             }
             break;
         case 'fee_added':
             if ($workitem->getStatus() != 'Draft') {
                 $headers['From'] = '"' . $project_name . '-fee added" ' . $from_address;
                 $body = 'New fee was added to the item ' . $itemLink . '.<br>' . 'Who: ' . $data['fee_adder'] . '<br/>' . 'Amount: ' . $data['fee_amount'] . '<br/>' . '<div>Fee Notes:<br/> ' . nl2br(stripslashes($data['fee_desc'])) . '</div><br/><br/>' . 'Project: ' . $project_name . '<br/>' . 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
                 if ($workitem->getRunner() != '') {
                     $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
                 }
                 if ($workitem->getMechanic() != '') {
                     $body .= 'Developer: ' . $workitem->getMechanic()->getNickname() . '<br /><br />';
                 }
                 $body .= 'Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /><br />' . 'You can view the job <a href="' . WORKLIST_URL . $itemId . '">here</a>.' . '<br /><br />' . '<a href="' . SERVER_URL . '">www.worklist.net</a>';
             }
             break;
         case 'fee_deleted':
             if ($workitem->getStatus() != 'Draft') {
                 $headers['From'] = '"' . $project_name . '-fee deleted" ' . $from_address;
                 $body = "<p>Your fee has been deleted by: " . $_SESSION['nickname'] . "<br/><br/>";
                 $body .= "If you think this has been done in error, please contact the job Designer.</p>";
                 $body .= 'Project: ' . $project_name . '<br />' . 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
                 if ($workitem->getRunner() != '') {
                     $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
                 }
                 if ($workitem->getMechanic() != '') {
                     $body .= 'Developer: ' . $workitem->getMechanic()->getNickname() . '<br /><br />';
                 }
                 $body .= 'Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /><br />' . 'You can view the job <a href="' . WORKLIST_URL . $itemId . '">here</a>.' . '<br /><br />' . '<a href="' . SERVER_URL . '">www.worklist.net</a>';
             }
             break;
         case 'tip_added':
             $headers['From'] = '"' . $project_name . '-tip added" ' . $from_address;
             $body = $data['tip_adder'] . ' tipped you $' . $data['tip_amount'] . ' on job ' . $itemLink . ' for:<br><br>' . $data['tip_desc'] . '<br><br>Yay!' . '<br /><br />' . 'Project: ' . $project_name . '<br />' . 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
             if ($workitem->getRunner() != '') {
                 $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
             }
             if ($workitem->getMechanic() != '') {
                 $body .= 'Developer: ' . $workitem->getMechanic()->getNickname() . '<br /><br />';
             }
             $body .= 'Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /><br />' . 'You can view the job <a href="' . WORKLIST_URL . $itemId . '">here</a>.' . '<br /><br />' . '<a href="' . SERVER_URL . '">www.worklist.net</a>';
             break;
         case 'bid_accepted':
             $headers['From'] = '"' . $project_name . '-bid accepted" ' . $from_address;
             $body = 'Your bid was accepted for ' . $itemLink . '<br/><br />' . 'If this job requires you to create code, please read through and then follow our coding ' . 'standards which are found <a href="https://github.com/highfidelity/hifi/wiki/Coding-Standard">here</a>.<br/><br/>' . 'Promised by: ' . $_SESSION['nickname'] . '<br /><br />' . 'Project: ' . $project_name . '<br />' . 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
             if ($workitem->getRunner() != '') {
                 $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
             }
             if ($workitem->getMechanic() != '') {
                 $body .= 'Developer: ' . $workitem->getMechanic()->getNickname() . '<br /><br />';
             }
             $body .= 'Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /><br />' . 'The job can be viewed <a href="' . WORKLIST_URL . $itemId . '">here</a><br /><br />';
             // render the github branch-created-sub template if necessary
             if (!empty($data) && array_key_exists('branch_name', $data)) {
                 $template = 'branch-created-sub';
                 include APP_PATH . '/email/en.php';
                 $replacedTemplate = !empty($data) ? Utils::templateReplace($emailTemplates[$template], $data) : $emailTemplates[$template];
                 $body .= $replacedTemplate['body'];
             }
             $body .= '<br /><a href="' . SERVER_URL . '">www.worklist.net</a>';
             break;
         case 'bid_placed':
             $projectId = $workitem->getProjectId();
             $jobsInfo = $options['jobsInfo'];
             $lastThreeJobs = $jobsInfo['joblist'];
             $workItemUrl = '<a href="' . WORKLIST_URL;
             //create the last three jobs and link them to those Jobs.
             foreach ($lastThreeJobs as $row) {
                 $jobs .= $workItemUrl;
                 $jobs .= $row['id'] . '">#' . $row['id'] . '</a>' . ' - ' . $row['summary'] . '<br /><br />';
             }
             //if no Jobs then display 'None'
             if (!$jobs) {
                 $jobs = 'None <br />';
             }
             //now get total jobs and total jobs and create links
             $totalJobs = $workItemUrl;
             $totalJobs .= $workitem->getId() . '?action=view&userinfotoshow=' . $_SESSION['userid'] . '">' . $options['totalJobs'] . ' jobs in total</a><br />';
             $totalActiveJobs = $workItemUrl;
             $totalActiveJobs .= $workitem->getId() . '?action=view&userinfotoshow=' . $_SESSION['userid'] . '">' . $options['activeJobs'] . ' jobs currently active</a>';
             $urlAcceptBid = $workItemUrl;
             $urlAcceptBid .= $itemId . '?bid_id=' . $data['bid_id'] . '&action=view_bid">Accept ' . $_SESSION['nickname'] . '\'s bid</a>';
             $body .= $urlAcceptBid;
             $bidder_address = '<' . $_SESSION['username'] . '>';
             $headers['From'] = '"' . $project_name . '-new bid" ' . $bidder_address;
             $body = ' New bid from <a href="' . SERVER_URL . 'user/' . $_SESSION['userid'] . '">' . $_SESSION['nickname'] . '</a> on: <br />' . $itemLink . ' ' . $workitem->getSummary() . '<br />' . '----------------------------------------------------------------<br /><br />' . 'Amount: $' . number_format($data['bid_amount'], 2) . '<br />' . 'Functioning in: ' . $data['done_in'] . '<br />' . '----<br />' . 'Notes: ' . '<br />' . ' ' . nl2br(stripslashes($data['notes'])) . '<br />' . '----<br />' . $urlAcceptBid . ' / reply to this email to ask questions or <a href="https://gitter.im/highfidelity/worklist">chat via Gitter</a><br /><br />' . '----------------------------------------------------------------<br />' . '<a href="' . SERVER_URL . 'user/' . $_SESSION['userid'] . '">' . $_SESSION['nickname'] . '\'s profile</a> / ' . $totalActiveJobs . ' / ' . $totalJobs . '<br />' . '----------------------------------------------------------------';
             break;
         case 'bid_updated':
             $projectId = $workitem->getProjectId();
             $jobsInfo = $options['jobsInfo'];
             $lastThreeJobs = $jobsInfo['joblist'];
             $workItemUrl = '<a href="' . WORKLIST_URL;
             //create the last three jobs and link them to those Jobs.
             foreach ($lastThreeJobs as $row) {
                 $jobs .= $workItemUrl;
                 $jobs .= $row['id'] . '">#' . $row['id'] . '</a>' . ' - ' . $row['summary'] . '<br /><br />';
             }
             //if no Jobs then display 'None'
             if (!$jobs) {
                 $jobs = 'None <br />';
             }
             //now get total jobs and total jobs and create link
             $totalJobs = $workItemUrl;
             $totalJobs .= $workitem->getId() . '?action=view&userinfotoshow=' . $_SESSION['userid'] . '">' . $options['totalJobs'] . ' jobs in total</a><br />';
             $totalActiveJobs = $workItemUrl;
             $totalActiveJobs .= $workitem->getId() . '?action=view&userinfotoshow=' . $_SESSION['userid'] . '">' . $options['activeJobs'] . ' jobs currently active</a>';
             $urlAcceptBid = $workItemUrl;
             $urlAcceptBid .= $itemId . '?bid_id=' . $data['bid_id'] . '&action=view_bid">Accept ' . $_SESSION['nickname'] . '\'s bid</a>';
             $body .= $urlAcceptBid;
             $bidder_address = '<' . $_SESSION['username'] . '>';
             $headers['From'] = '"' . $project_name . '-bid updated" ' . $bidder_address;
             $body = 'Bid updated by <a href="' . SERVER_URL . 'user/' . $_SESSION['userid'] . '">' . $_SESSION['nickname'] . '</a> on: <br />' . $itemLink . ' ' . $workitem->getSummary() . '<br />' . '----------------------------------------------------------------<br /><br />' . 'Amount: $' . number_format($data['bid_amount'], 2) . '<br />' . 'Functioning in: ' . $data['done_in'] . '<br />' . '----<br />' . 'Notes: ' . '<br />' . ' ' . nl2br(stripslashes($data['notes'])) . '<br />' . '----<br />' . $urlAcceptBid . ' / reply to this email to ask questions or <a href="https://gitter.im/highfidelity/worklist">chat via Gitter</a><br /><br />' . '----------------------------------------------------------------<br />' . '<a href="' . SERVER_URL . 'user/' . $_SESSION['userid'] . '">' . $_SESSION['nickname'] . '\'s profile</a> / ' . $totalActiveJobs . ' / ' . $totalJobs . '<br />' . '----------------------------------------------------------------';
             break;
         case 'bid_discarded':
             $headers['From'] = '"' . $project_name . '-bid not accepted" ' . $from_address;
             $body = "<p>Hello " . $data['who'] . ",</p>";
             $body .= "<p>Thanks for adding your bid to <a href='" . WORKLIST_URL . $itemId . "'>#" . $itemId . "</a> '" . $workitem->getSummary() . "'. This job has just been filled by another developer.</br></p>";
             $body .= "There is lots of work to be done so please keep checking the <a href='" . SERVER_URL . "'>worklist</a> and bid on another job soon!</p>";
             $body .= "<p>Hope to see you in the Worklist soon. :)</p>";
             break;
         case 'modified':
             if ($workitem->getStatus() != 'Draft') {
                 $from_changes = "";
                 if (!empty($options['status_change']) && $workitem->getStatus() == 'QA Ready') {
                     $status_change = '-' . strtolower($workitem->getStatus());
                     $headers['From'] = '"' . $project_name . $status_change . '" ' . $from_address;
                     $body = $_SESSION['nickname'] . ' set ' . $itemLink . ' to QA Ready.<br /><br />' . 'Check out the work: ' . $workitem->getSandbox() . '<br /><br />' . 'Checkout the branch created for this job: git checkout ' . $workitem->getSandbox() . ' .<br /><br />' . '<a href="' . WORKLIST_URL . $itemId . '">Leave a comment on the Job</a>';
                 } else {
                     if (!empty($options['status_change'])) {
                         $from_changes = $options['status_change'];
                     }
                     if (isset($options['job_changes'])) {
                         if (count($options['job_changes']) > 0) {
                             $from_changes .= $options['job_changes'][0];
                             if (count($options['job_changes']) > 1) {
                                 $from_changes .= ' +other changes';
                             }
                         }
                     }
                     if (!empty($from_changes)) {
                         $headers['From'] = '"' . $project_name . $from_changes . '" ' . $from_address;
                     } else {
                         $status_change = '-' . strtolower($workitem->getStatus());
                         $headers['From'] = '"' . $project_name . $status_change . '" ' . $from_address;
                     }
                     $body = $_SESSION['nickname'] . ' updated item ' . $itemLink . '<br>' . $data['changes'] . '<br /><br />' . 'Project: ' . $project_name . '<br />' . 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
                     if ($workitem->getRunner() != '') {
                         $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
                     }
                     if ($workitem->getMechanic() != '') {
                         $body .= 'Developer: ' . $workitem->getMechanic()->getNickname() . '<br /><br />';
                     }
                     $body .= 'Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /><br />' . 'You can view the job <a href="' . WORKLIST_URL . $itemId . '">here</a>.' . '<br /><br />' . '<a href="' . SERVER_URL . '">www.worklist.net</a>';
                 }
             }
             break;
         case 'new_bidding':
             $urlPlacebid = '<a href="' . WORKLIST_URL . $itemId . '?placeBid">Submit a bid</a>';
             $body = "Now accepting bids: <br />" . $itemLink . ' ' . $workitem->getSummary() . '<br />' . '----------------------------------------------------------------<br />' . 'Project: ' . '<a href="' . SERVER_URL . $project_name . '">' . $project_name . '</a>' . ' / Creator: ' . '<a href="' . SERVER_URL . 'user/' . $workitem->getCreator()->getNickname() . '">' . $workitem->getCreator()->getNickname() . '<a>';
             if ($workitem->getRunner() != '') {
                 $body .= ' / Designer: ' . '<a href="' . SERVER_URL . 'user/' . $workitem->getRunner()->getNickname() . '">' . $workitem->getCreator()->getNickname() . '<a> <br />' . '----------------------------------------------------------------<br />';
             }
             $body .= 'Notes:<br /> ' . nl2br(stripslashes($workitem->getNotes())) . '<br />' . '----------------------------------------------------------------<br />' . '<a href="' . WORKLIST_URL . $itemId . '">View the job</a>' . ' / ' . $urlPlacebid;
             break;
         case 'new_qa':
             $body = $_SESSION['nickname'] . ' set ' . $itemLink . ' to QA Ready.<br /><br />' . 'Check out the work: ' . $workitem->getSandbox() . '<br /><br />' . 'Checkout the branch created for this job: git checkout ' . $workitem->getSandbox() . ' .<br /><br />' . '<a href="' . WORKLIST_URL . $itemId . '">Leave a comment on the Job</a>';
             break;
         case 'new_review':
             $body = "Now ready for a code review: " . $itemLinkTitle . ' <br /><br />';
             break;
         case 'suggested':
             $body = 'Summary: ' . $itemLink . '<br /><br />' . 'Project: ' . $project_name . '<br />' . 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
             if ($workitem->getRunner() != '') {
                 $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
             }
             if ($workitem->getMechanic() != '') {
                 $body .= 'Developer: ' . $workitem->getMechanic()->getNickname() . '<br /><br />';
             }
             $body .= 'Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /><br />' . 'You can view the job <a href="' . WORKLIST_URL . $itemId . '">here</a>.' . '<br /><br />' . '<a href="' . SERVER_URL . '">www.worklist.net</a>';
             break;
         case 'code-review-completed':
             $headers['From'] = '"' . $project_name . '-review complete" ' . $from_address;
             $body = '<p>Hello,</p>';
             $body .= '<p>The code review on task ' . $itemLink . ' has been completed by ' . $_SESSION['nickname'] . '</p>';
             $body .= '<br>';
             $body .= '<p>Project: ' . $project_name . '<br />';
             $body .= 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
             $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
             $body .= 'Developer: ' . $workitem->getMechanic()->getNickname() . '</p>';
             $body .= '<p>Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /></p>';
             $body .= '<p>You can view the job <a href="' . WORKLIST_URL . $itemId . '">here</a>.' . '<br /></p>';
             $body .= '<p><a href="' . SERVER_URL . '">www.worklist.net</a></p>';
             break;
         case 'expired_bid':
             $headers['From'] = '"' . $project_name . '-expired bid" ' . $from_address;
             $body = "<p>Job " . $itemLink . "<br />";
             $body .= "Your Bid on #" . $itemId . " has expired and this task is still available for Bidding.</p>";
             $body .= "<p>Bidder: " . $data['bidder_nickname'] . "<br />";
             $body .= "Bid Amount : \$" . $data['bid_amount'] . "</p>";
             $body .= '<p>Project: ' . $project_name . '<br />';
             $body .= 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
             if ($workitem->getRunnerId()) {
                 $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
             }
             $body .= '<p>Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /></p>';
             $body .= '<p>You can view the job ';
             $body .= '<a href="' . WORKLIST_URL . $itemId . '">here</a>.<br /></p>';
             $body .= '<p><a href="' . SERVER_URL . '">www.worklist.net</a></p>';
             break;
         case 'auto-pass':
             $headers['From'] = '"' . $project_name . "- Auto PASSED" . '" ' . $from_address;
             if (isset($data['prev_status']) && $data['prev_status'] == 'Bidding') {
                 $headers['From'] = '"' . $project_name . "- BIDDING Item Auto PASSED" . '" ' . $from_address;
                 $body = "Otto has triggered an auto-PASS for job #" . $itemId . ". You may reactivate this job by updating the status or contacting an admin." . '<br/><br/>';
             } else {
                 $body = "Otto has triggered an auto-PASS for your suggested job. You may reactivate this job by updating the status or contacting an admin." . '<br/><br/>';
             }
             $body .= "Summary: " . $itemLink . ": " . $workitem->getSummary() . '<br/>' . 'Project: ' . $project_name . '<br />' . 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />' . 'Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /><br />' . 'You can view the job <a href="' . WORKLIST_URL . $itemId . '">here</a>.' . '<br /><br />' . '<a href="' . SERVER_URL . '">www.worklist.net</a>';
             break;
         case 'virus-found':
             $headers['From'] = '"' . $project_name . '-upload error" ' . $from_address;
             $body = '<p>Hello, <br /><br /> The file ' . $options['file_name'] . ' (' . $options['file_title'] . ') ' . 'that you uploaded for this workitem was scanned and found to be containing a virus and will be quarantined. <br /><br />' . 'Please upload a clean copy of the file.</p>';
             $body .= '<p>Project: ' . $project_name . '<br />';
             $body .= 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
             if ($workitem->getRunnerId()) {
                 $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
             }
             $body .= '<p>Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /></p>';
             $body .= '<p>You can view the job ';
             $body .= '<a href="' . WORKLIST_URL . $itemId . '">here</a>.<br /></p>';
             $body .= '<p><a href="' . SERVER_URL . '">www.worklist.net</a></p>';
             break;
         case 'virus-error':
             $headers['From'] = '"' . $project_name . '-upload error" ' . $from_address;
             $body = '<p>Hello, <br /><br /> The file ' . $options['file_name'] . ' (' . $options['file_title'] . ') ' . 'that you uploaded for this workitem caused an unknown error during scanning. <br /><br />' . 'Please upload a clean copy of the file.</p>';
             $body .= '<p>Project: ' . $project_name . '<br />';
             $body .= 'Creator: ' . $workitem->getCreator()->getNickname() . '<br />';
             if ($workitem->getRunnerId()) {
                 $body .= 'Designer: ' . $workitem->getRunner()->getNickname() . '<br />';
             }
             $body .= '<p>Notes:<br/> ' . nl2br($workitem->getNotes()) . '<br /></p>';
             $body .= '<p>You can view the job ';
             $body .= '<a href="' . WORKLIST_URL . $itemId . '">here</a>.<br /></p>';
             $body .= '<p><a href="' . SERVER_URL . '">www.worklist.net</a></p>';
             break;
         case 'change-designer':
             $headers['From'] = '"' . $project_name . '-designer reassigned" ' . $from_address;
             $body = "<p>Hi there,</p>";
             $body .= "<p>I just wanted to let you know that the Job #" . $workitem->getId() . " (" . $workitem->getSummary() . ") has been reassigned to Designer " . $data['runner_nickname'] . ".</p>";
             $body .= "<p>See you in the Worklist!</p>";
             break;
     }
     if ($recipients) {
         foreach ($recipients as $recipient) {
             /**
              *  If there is need to get a new list of users
              *  just add a get[IDENTIFIER]Id function to
              *  workitem.class.php that returns a single user id
              *  or an array with user ids */
             $method = 'get' . ucfirst($recipient) . 'Id';
             $recipientUsers = $workitem->{$method}();
             if (!is_array($recipientUsers)) {
                 $recipientUsers = array($recipientUsers);
             }
             foreach ($recipientUsers as $recipientUser) {
                 if ($recipientUser > 0) {
                     //Does the recipient exists
                     $rUser = new User();
                     $rUser->findUserById($recipientUser);
                     $sendNotification = ($workitem->isInternal() ? $rUser->isInternal() : true) && ($options['type'] == 'comment' && $rUser->getId() == Session::uid() ? $rUser->getSelf_notif() : true);
                     if ($sendNotification) {
                         if ($username = $rUser->getUsername()) {
                             array_push($emails, $username);
                         }
                     }
                 }
             }
         }
     }
     $emails = array_unique($emails);
     if (count($emails) > 0) {
         foreach ($emails as $email) {
             // Small tweak for mails to followers on bid acceptance
             if ($options['type'] == 'bid_accepted' && strcmp($email, $workitem->getMechanic()->getUsername())) {
                 $body = str_replace('Your', $workitem->getMechanic()->getNickname() . "'s", $body);
             }
             if (!Utils::send_email($email, $subject, $body, null, $headers)) {
                 error_log("Notification:workitem: Utils::send_email failed " . json_encode(error_get_last()));
             }
         }
     }
 }
示例#12
0
 public function listForJob($job_id)
 {
     try {
         $files = File::fetchAllFilesForWorkitem($job_id);
         $user = User::find(Session::uid());
         if (!$user->getId()) {
             throw new Exception('Not enough rights');
         }
         $job = WorkItem::getById($job_id);
         $data = array();
         foreach ($files as $file) {
             if (!File::isAllowed($file->getStatus(), $user) || !$file->getIs_scanned()) {
                 continue;
             }
             $fileUrl = $file->getUrl();
             $iconUrl = $file->getUrl();
             $userInvolved = $user->getId() == $file->getUserid() || $user->getId() == $job->getCreatorId() || $user->getId() == $job->getMechanicId() || $user->getId() == $job->getRunnerId();
             $icon = File::getIconFromMime($file->getMime());
             $data[] = array('fileid' => $file->getId(), 'url' => $fileUrl, 'can_delete' => $user->isRunner() || $user->isPayer() || $userInvolved, 'title' => $file->getTitle(), 'description' => $file->getDescription());
         }
         return $this->setOutput(array('success' => true, 'data' => $data));
     } catch (Exception $e) {
         return $this->setOutput(array('success' => false, 'message' => $e->getMessage()));
     }
 }
示例#13
0
 public function run()
 {
     Utils::checkLogin();
     $userId = Session::uid();
     $user = new User();
     if ($userId) {
         $user->findUserById($userId);
     }
     $this->write('user', $user);
     $userSystem = new UserSystemModel();
     $this->write('userSystems', $userSystem->getUserSystemsWithPlaceholder($userId));
     $msg = "";
     $company = "";
     $saveArgs = array();
     $messages = array();
     $errors = 0;
     $error = new Error();
     $settings_link = SECURE_SERVER_URL . "settings";
     $worklist_link = SECURE_SERVER_URL . "jobs";
     $returned_json = array();
     // process updates to user's settings
     if (isset($_POST['save']) && $_POST['save']) {
         $bidding_notif = $_POST['bidding_notif'];
         if ($bidding_notif != $user->getBidding_notif()) {
             $saveArgs['bidding_notif'] = 1;
         }
         $review_notif = $_POST['review_notif'];
         if ($review_notif != $user->getReview_notif()) {
             $saveArgs['review_notif'] = 1;
         }
         $self_notif = $_POST['self_notif'];
         if ($self_notif != $user->getSelf_notif()) {
             $saveArgs['self_notif'] = 1;
         }
         if (isset($_POST['timezone'])) {
             $timezone = mysql_real_escape_string(trim($_POST['timezone']));
             $saveArgs['timezone'] = 0;
         }
         $country = trim($_POST['country']);
         if ($country != $user->getCountry()) {
             $messages[] = "Your country has been updated.";
             $saveArgs['country'] = 1;
         }
         if ($user->getTimezone() != $_POST['timezone']) {
             $messages[] = "Your timezone has been updated.";
         }
         $about = isset($_POST['about']) ? strip_tags(substr($_POST['about'], 0, 150)) : "";
         if ($about != $user->getAbout()) {
             $saveArgs['about'] = 1;
             $messages[] = "Your personal information (about) has been updated.";
         }
         $userSystem->storeUsersSystemsSettings($userId, $_POST['system_id'], $_POST['system_operating_systems'], $_POST['system_hardware'], $_POST['system_delete']);
         $paypal = 0;
         $paypal_email = '';
         // defaulting to paypal at this stage
         $payway = 'paypal';
         $paypal = 1;
         $paypal_email = isset($_POST['paypal_email']) ? mysql_real_escape_string($_POST['paypal_email']) : "";
         if ($paypal_email != $user->getPaypal_email()) {
             $saveArgs = array_merge($saveArgs, array('paypal' => 0, 'paypal_email' => 0, 'payway' => 1));
             $messages[] = "Your payment information has been updated.";
         }
         if (!$user->getW9_accepted() && $user->getCountry() == 'US') {
             $w9_accepted = 'NOW()';
             $saveArgs['w9_accepted'] = 0;
         }
         $paypalPrevious = $user->getPaypal_email();
         // user deleted paypal email, deactivate
         if (empty($paypal_email)) {
             $user->setPaypal_verified(false);
             $user->setPaypal_email('');
             $user->save();
             // user changed paypal address
         } else {
             if ($paypalPrevious != $paypal_email) {
                 $paypal_hash = md5(date('r', time()));
                 // generate email
                 $subject = "Your payment details have changed";
                 $link = SECURE_SERVER_URL . "confirmation?pp=" . $paypal_hash . "&ppstr=" . base64_encode($paypal_email);
                 $body = '<p>Dear ' . $user->getNickname() . ',</p>';
                 $body .= '<p>Please confirm your payment email address to activate payments on your account and enable you to start placing bids in the <a href="' . $worklist_link . '">Worklist</a>.</p>';
                 $body .= '<p><a href="' . $link . '">Click here to confirm your payment address</a></p>';
                 $plain = 'Dear ' . $user->getNickname() . ',' . "\n\n";
                 $plain .= 'Please confirm your payment email address to activate payments on your accounts and enable you to start placing bids in the Worklist.' . "\n\n";
                 $plain .= $link . "\n\n";
                 $confirm_txt = "An email containing a confirmation link was sent to your payment email address. Please click on that link to verify your payment email address and activate your account.";
                 if (!Utils::send_email($paypal_email, $subject, $body, $plain)) {
                     error_log("SettingsController: Utils::send_email failed");
                     $confirm_txt = 'There was an issue sending email. Please try again or notify ' . SUPPORT_EMAIL;
                 }
                 $user->setPaypal_verified(false);
                 $user->setPaypal_hash($paypal_hash);
                 $user->setPaypal_email($paypal_email);
                 $user->save();
             }
         }
         // do we have data to update?
         if (!empty($saveArgs)) {
             $sql = "UPDATE `" . USERS . "` SET ";
             foreach ($saveArgs as $arg => $esc) {
                 if ($esc) {
                     ${$arg} = mysql_real_escape_string(htmlspecialchars(${$arg}));
                 }
                 if (is_int(${$arg}) || $arg == "w9_accepted" && ${$arg} == 'NOW()') {
                     $sql .= "`{$arg}` = " . ${$arg} . ",";
                 } else {
                     $sql .= "`{$arg}` = '" . ${$arg} . "',";
                 }
             }
             $sql = rtrim($sql, ',');
             $sql .= " WHERE id = {$_SESSION['userid']}";
             $res = mysql_query($sql);
             if (!$res) {
                 error_log("Error in saving settings: " . mysql_error() . ':' . $sql);
                 die("Error in saving settings. ");
             }
             // Email user
             if (!empty($messages)) {
                 $to = $_SESSION['username'];
                 $subject = "Settings";
                 $body = '<p>Congratulations!</p>' . '<p>You have successfully updated your settings with Worklist: <ul>';
                 foreach ($messages as $msg) {
                     $body .= '<li>' . $msg . '</li>';
                 }
                 $body .= '</ul>' . '<p><br/>You can view your settings <a href=' . $settings_link . '>here</a></p>' . '<p><a href=' . $worklist_link . '>www.worklist.net</a></p>';
                 if (!Utils::send_email($to, $subject, $body)) {
                     error_log("SettingsController: Utils::send_email failed");
                 }
                 $msg = "Account updated successfully!";
             }
             if (isset($_POST['timezone'])) {
                 $_SESSION['timezone'] = trim($_POST['timezone']);
             }
             if (isset($confirm_txt) && !empty($confirm_txt)) {
                 echo $confirm_txt;
                 exit;
             }
             $this->view = null;
             // reset session data
             $user->findUserById($userId);
             $id = $user->getId();
             $username = $user->getUsername();
             $nickname = $user->getNickname();
             Utils::setUserSession($user->getId(), $user->getUsername(), $user->getNickname(), $user->getIs_admin());
             $returned_json['user_systems'] = $userSystem->getUserSystemsJSON($userId);
             echo json_encode($returned_json);
             // exit on ajax post - if we experience issues with a blank settings page, need to look at the ajax submit functions
             die;
         }
     }
     // getting userInfo to prepopulate fields
     $userInfo = array();
     $qry = "SELECT * FROM " . USERS . " WHERE id='" . $_SESSION['userid'] . "'";
     $rs = mysql_query($qry);
     if ($rs) {
         $userInfo = mysql_fetch_array($rs);
     }
     $userInfo['avatar'] = $user->getAvatar();
     $this->write('userInfo', $userInfo);
     parent::run();
 }
示例#14
0
 public function run()
 {
     //send non-payers back to the reports page.
     if (empty($_SESSION['is_payer'])) {
         $this->view = null;
         Utils::redirect("./reports");
     }
     $is_runner = !empty($_SESSION['is_runner']) ? 1 : 0;
     $is_payer = !empty($_SESSION['is_payer']) ? 1 : 0;
     $userId = Session::uid();
     $payer_id = $userId;
     // set default fund to worklist
     $fund_id = 3;
     if (isset($_REQUEST['fund_id'])) {
         $fund_id = mysql_real_escape_string($_REQUEST['fund_id']);
         // clear POST if this was just a fund change
         if (!isset($_REQUEST['action'])) {
             unset($_POST);
         }
     }
     //open db connection
     $db = @mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die('I cannot connect to the database because: ' . mysql_error());
     $db = @mysql_select_db(DB_NAME);
     // get a list of projects so we can display the project name in table
     $sql_get_fund_projects_array = "\n            SELECT\n                project_id, name\n            FROM\n                " . PROJECTS . "\n            WHERE\n                fund_id = " . $fund_id;
     // sql sub-query for limiting fees to specific fund
     $sql_get_fund_projects = "\n            SELECT\n                project_id\n            FROM\n                " . PROJECTS . "\n            WHERE\n                fund_id = " . $fund_id;
     if ($fund_id == 0) {
         $sql_get_fund_projects = '0';
     }
     $fund_projects = array();
     $fund_projects[0] = 'none';
     $fund_projects_query = mysql_query($sql_get_fund_projects_array);
     while ($project = mysql_fetch_array($fund_projects_query)) {
         $fund_projects[$project['project_id']] = $project['name'];
     }
     $this->sql_get_fee_totals = "\n            SELECT\n                sum(f.amount) AS total_amount,\n                u.id AS mechanic_id,\n                u.nickname AS mechanic_nick,\n                u.paypal_email AS mechanic_paypal_email,\n                wl.summary AS worklist_item, f.bonus AS bonus, 'BONUS' AS bonus_desc\n            FROM\n                (" . FEES . " f LEFT JOIN " . USERS . " u ON f.user_id = u.id)\n                LEFT JOIN " . WORKLIST . " wl ON f.worklist_id = wl.id\n            WHERE\n                wl.status = 'Done'\n                AND f.paid = '0'\n                AND f.withdrawn = '0'\n                AND f.amount > 0\n                AND u.paypal_verified = '1'\n                AND u.has_W2 = 0\n                AND wl.project_id IN (" . $sql_get_fund_projects . ")\n            GROUP BY f.user_id\n            ";
     $this->sql_get_bonus_totals = false;
     // only pull bonuses for if worklist fund chosen - temporary hardcoding
     // until we determine further solution
     if ($fund_id == 3) {
         $this->sql_get_bonus_totals = "\n                SELECT\n                    sum(b.amount) AS total_amount,\n                    b.user_id AS mechanic_id,\n                    b.desc AS worklist_item,\n                    u.nickname AS mechanic_nick,\n                    u.paypal_email AS mechanic_paypal_email\n                FROM\n                    " . FEES . " b\n                    LEFT JOIN " . USERS . " u on u.id = b.user_id\n                WHERE\n                    b.paid = 0\n                    AND b.withdrawn = 0\n                    AND u.paypal_verified = '1' \n                    AND b.bonus = 1\n                    AND u.has_W2 = 0\n               GROUP BY b.user_id\n                ";
     }
     $action = isset($_POST["action"]) ? $_POST["action"] : '';
     // Initialize empty arrays if no fees or bonuses were selected
     if (!isset($_POST['payfee'])) {
         $_POST['payfee'] = array();
     }
     if (!isset($_POST['paybonus'])) {
         $_POST['paybonus'] = array();
     }
     $pp_message = $httpParsedResponseAr = $alert_msg = $message = "";
     //Check action - should be confirm, pay or not set
     switch ($action) {
         case 'confirm':
             //$fees_csv = implode(',', $_POST["payfee"]);
             //pull list of payees from db based on the time span
             $payee_totals = $this->getUserTotalsArray();
             break;
         case 'pay':
             //collect confirmed payees and run paypal transaction
             //include_once("../paypal-password.php");
             if ($this->checkAdmin($_POST['password']) == '1') {
                 error_log("Made it Admin!");
                 if (empty($_POST['pp_api_username']) || empty($_POST['pp_api_password']) || empty($_POST['pp_api_signature'])) {
                     $alert_msg = "You need to provide all credentials!";
                     break;
                 }
                 //Get fee information for paypal transaction
                 $num_fees = count($_POST["payfee"]);
                 $fee_id_csv = implode(',', $_POST["payfee"]);
                 $fees_info_sql = 'SELECT
                         f.id AS fee_id,
                         f.amount AS amount,
                         f.worklist_id AS worklist_id,
                         u.id AS mechanic_id,
                         u.nickname AS mechanic_nick,
                         u.paypal_email AS mechanic_paypal_email,
                         wl.summary AS worklist_item  
                     FROM
                         (' . FEES . ' f LEFT JOIN ' . USERS . ' u ON f.user_id = u.id)
                         LEFT JOIN ' . WORKLIST . ' wl ON f.worklist_id = wl.id
                     WHERE
                         f.id in (' . $fee_id_csv . ')';
                 $fees_info_results = mysql_query($fees_info_sql);
                 $num_bonuses = count($_POST["paybonus"]);
                 $bonus_id_csv = $num_bonuses ? implode(',', $_POST["paybonus"]) : 0;
                 $bonus_info_sql = '
                     SELECT
                         b.id AS fee_id,
                         b.amount AS amount,
                         "BONUS" AS worklist_id,
                         b.user_id AS mechanic_id,
                         u.nickname AS mechanic_nick,
                         u.paypal_email AS mechanic_paypal_email,
                         b.desc AS worklist_item
                     FROM
                         ' . FEES . ' b
                         LEFT JOIN ' . USERS . ' u on u.id = b.user_id
                     WHERE
                         b.id in (' . $bonus_id_csv . ') and b.bonus = 1
                     ';
                 $bonus_info_results = mysql_query($bonus_info_sql) or error_log("bonussql failed: " . mysql_error() . "\n{$bonus_info_sql}");
                 // Set request-specific fields.
                 $emailSubject = urlencode('You\'ve got money!');
                 $receiverType = urlencode('EmailAddress');
                 // TODO Other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD') ?
                 $currency = urlencode('USD');
                 // Add request-specific fields to the request string.
                 $nvpStr = "&EMAILSUBJECT={$emailSubject}&RECEIVERTYPE={$receiverType}&CURRENCYCODE={$currency}";
                 //build payment data array
                 $message .= "<pre>";
                 $receiversArray = array();
                 $totalFees = 0;
                 //log data
                 if (mysql_num_rows($fees_info_results)) {
                     $message .= "Fees:\n";
                     while ($fees_data = mysql_fetch_array($fees_info_results)) {
                         $receiversArray[] = array('receiverEmail' => $fees_data["mechanic_paypal_email"], 'amount' => $fees_data["amount"], 'uniqueID' => $fees_data["fee_id"], 'note' => 'Worklist #' . $fees_data["worklist_id"] . ' - ' . $fees_data["worklist_item"]);
                         $totalFees = $totalFees + $fees_data["amount"];
                         $message .= "    " . $fees_data['mechanic_paypal_email'] . " - \$" . $fees_data['amount'] . "\n";
                     }
                 }
                 if (mysql_num_rows($bonus_info_results) > 0) {
                     $message .= "Bonuses:\n";
                     while ($fees_data = mysql_fetch_array($bonus_info_results)) {
                         $receiversArray[] = array('receiverEmail' => $fees_data["mechanic_paypal_email"], 'amount' => $fees_data["amount"], 'uniqueID' => $fees_data["fee_id"], 'note' => $fees_data["worklist_id"] . ' - ' . $fees_data["worklist_item"]);
                         $totalFees = $totalFees + $fees_data["amount"];
                         $message .= "    " . $fees_data['mechanic_paypal_email'] . " - \$" . $fees_data['amount'] . "\n";
                     }
                 }
                 $message .= "</pre>";
                 //build nvp string
                 foreach ($receiversArray as $i => $receiverData) {
                     $receiverEmail = urlencode($receiverData['receiverEmail']);
                     $amount = urlencode($receiverData['amount']);
                     $uniqueID = urlencode($receiverData['uniqueID']);
                     $note = urlencode($receiverData['note']);
                     $nvpStr .= "&L_EMAIL{$i}={$receiverEmail}&L_Amt{$i}={$amount}&L_UNIQUEID{$i}={$uniqueID}&L_NOTE{$i}={$note}";
                 }
                 // Execute the API operation; see the PPHttpPost function
                 $httpParsedResponseAr = $this->PPHttpPost($nvpStr, $_POST);
                 #$httpParsedResponseAr = array("ACK" => "SUCCESS");
                 if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
                     error_log('masspay success!');
                     $pp_message = '<p>MassPay Completed Successfully! - $' . $totalFees . ' Paid.</p>';
                     if (isset($_GET["debug"])) {
                         $pp_message .= '<p><pre>' . print_r($httpParsedResponseAr, true) . '</pre></p>';
                     }
                     //$fee_sql_update = "UPDATE ".FEES." SET paid=1, paid_date='".date("Y-m-d H:i:s")."' WHERE id in (".$fees_csv.")";
                     //$update_fees_paid = mysql_query($fee_sql_update);
                     $summaryData = Fee::markPaidByList(explode(',', $fee_id_csv), $user_paid = 0, $paid_notes = '', $paid = 1, $fund_id);
                     if ($bonus_id_csv) {
                         Bonus::markPaidByList(explode(',', $bonus_id_csv), $user_paid = 0, $paid = 1, false, $fund_id);
                     }
                 } else {
                     $alert_msg = "MassPay Failure";
                     $pp_message = '<p>MassPay failed:</p><p><pre>' . print_r($httpParsedResponseAr, true) . '</pre></p>';
                     if (!Utils::send_email(FINANCE_EMAIL, 'Masspay Fail', $pp_message)) {
                         error_log("view-payments:MassPayFailure: Utils::send_email failed");
                     }
                 }
             } else {
                 $error_msg = 'Invalid MassPay Authentication<br />';
                 $error_msg .= 'IP: ' . $_SERVER['REMOTE_ADDR'] . '<br />';
                 $error_msg .= 'UserID: ' . $userId;
                 if (!Utils::send_email(FINANCE_EMAIL, "Masspay Invalid Auth Attempt", $error_msg)) {
                     error_log("view-payments:MassPayAuth: Utils::send_email failed");
                 }
                 $alert_msg = "Invalid Authentication";
             }
             break;
         default:
             //pull list of payees from db based on the time span
             $payee_totals = $this->getUserTotalsArray();
             break;
     }
     $this->write('fund_id', $fund_id);
     $this->write('message', $message);
     $this->write('pp_message', $pp_message);
     $this->write('alert_msg', $alert_msg);
     $this->write('payee_totals', $payee_totals);
     $this->write('fund_projects', $fund_projects);
     $this->write('sql_get_fund_projects', $sql_get_fund_projects);
     $this->write('input', array('action' => isset($_POST['action']) ? $_POST['action'] : '', 'order' => isset($_GET["order"]) ? 'order=' . $_GET["order"] : ''));
     parent::run();
 }
示例#15
0
 public function sendLove($to)
 {
     $this->view = null;
     try {
         if (!Session::uid()) {
             throw new Exception('Must be logged in to Send Love!');
         }
         $from = User::find(Session::uid());
         $to = User::find($to);
         if (!$to->getId()) {
             throw new Exception('Not a valid user');
         }
         $love_message = $_POST['love_message'];
         if (empty($love_message)) {
             throw new Exception('Message field is mandatory');
         }
         if (!$from->sendLove($to, $love_message)) {
             throw new Exception('Could not send love');
         }
         $from_nickname = $from->getNickname();
         $message = $_POST['love_message'];
         Utils::sendTemplateEmail($to->getUsername(), 'love-received', array('from_nickname' => $from_nickname, 'message' => $message));
         echo json_encode(array('success' => true, 'message' => 'Love sent'));
     } catch (Exception $e) {
         echo json_encode(array('success' => false, 'message' => $e->getMessage()));
     }
 }
示例#16
0
define('USER_NAME', 'REMOTE_USER');
$tpl =& initFastTemplate();
$cache = new Cache();
$ses = new Session(true);
$tpl->assign('MESSAGE', $ses->msg());
if ($ses->url()) {
    $target_url = $ses->url();
} else {
    $target_url = '/';
}
if (isset($_POST['USERNAME']) || isset($_SERVER[USER_NAME])) {
    $ses->dispose('uid');
    $usr = new User5(isset($_POST['USERNAME']) ? $_POST['USERNAME'] : $_SERVER[USER_NAME]);
    if ($usr->count > 0) {
        if (isset($_SERVER[USER_NAME]) || $_POST['PASS'] && strlen($_POST['PASS']) > 0 && $usr->checkPass($_POST['PASS'])) {
            $ses->uid($usr->samaccountname);
            $ses->login($usr->samaccountname);
            $ses->valueOf('cn', $usr->cn);
            $tar = array();
            if ($usr->directreports) {
                $tar = $usr->fullName2account($usr->directreports);
            } else {
                $tar[] = $usr->samaccountname;
            }
            $ses->valueOf('filter.targetusers', $tar);
        } else {
            $ses->msg('В доступе отказано: неверное имя пользователя или пароль.');
            $target_url = LOGIN_URL;
        }
    } else {
        $ses->msg('В доступе отказано: неверное имя пользователя или пароль.');
示例#17
0
 public function removeCodeReviewer($id)
 {
     $this->view = null;
     try {
         $data = array();
         $project = Project::find($id);
         if (!$project->getProjectId()) {
             throw new Exception('Not a project in our system');
         }
         $request_user = User::find(Session::uid());
         if (!$project->isCodeReviewAdmin($request_user)) {
             throw new Exception('Not enough rights');
         }
         $codeReviewers = array_slice(func_get_args(), 1);
         $deleted_codeReviewers = array();
         foreach ($codeReviewers as $codeReviewer) {
             if ($project->deleteCodeReviewer($codeReviewer)) {
                 $deleted_codeReviewers[] = $codeReviewer;
                 $user = User::find($codeReviewer);
                 $founder = User::find($project->getOwnerId());
                 $founderUrl = SECURE_SERVER_URL . 'user/' . $founder->getId();
                 $data = array('nickname' => $user->getNickname(), 'projectName' => $project->getName(), 'projectUrl' => Project::getProjectUrl($project->getProjectId()), 'projectFounder' => $founder->getNickname(), 'projectFounderUrl' => $founderUrl);
                 if (!Utils::sendTemplateEmail($user->getUsername(), 'project-codereview-removed', $data)) {
                     error_log("ProjectController::removeCodeReviewer: Utils::send_email to user failed");
                 }
             }
         }
         echo json_encode(array('success' => true, 'data' => array('deleted_codereviewers' => $deleted_codeReviewers)));
     } catch (Exception $e) {
         $error = $e->getMessage();
         echo json_encode(array('success' => false, 'data' => $error));
     }
 }
示例#18
0
 /**
  * @param $gitHubId
  * @return bool if user has authorized the app with github, false otherwise
  */
 public function isGithub_connected($gitHubId = GITHUB_OAUTH2_CLIENT_ID)
 {
     $userId = Session::uid();
     if ($userId == 0) {
         return false;
     }
     $sql = "SELECT COUNT(*) AS count FROM `" . USERS_AUTH_TOKENS . "`\n                WHERE user_id = " . (int) $userId . " AND github_id = '" . mysql_real_escape_string($gitHubId) . "'";
     $result = mysql_query($sql);
     if ($result && mysql_num_rows($result) > 0) {
         $row = mysql_fetch_assoc($result);
         return (int) $row['count'] > 0;
     } else {
         return false;
     }
 }
示例#19
0
 public static function searchStats($query = null, $conds = array(), $subConds = array())
 {
     $userId = Session::uid();
     if (count($subConds)) {
         $subQuery = ' `w`.`id` IN (
             SELECT `sub_w`.`id`
             FROM `' . WORKLIST . '` `sub_w`
               LEFT JOIN `' . COMMENTS . '` AS `sub_com`
                 ON `sub_w`.`id` = `sub_com`.`worklist_id`
               LEFT JOIN `' . FEES . '` AS `sub_f`
                 ON `sub_w`.`id` = `sub_f`.`worklist_id`
                   AND `sub_f`.`withdrawn` = 0
             WHERE ' . implode(' AND ', $subConds) . '
         )';
         $conds[] = $subQuery;
     }
     $whereConds = count($conds) ? implode(' AND ', $conds) : '1';
     $sql = "\n            SELECT\n              `proj`.`name` AS `project`,\n              `status`,\n              COUNT(*) AS `jobsCount`\n            FROM `" . WORKLIST . "` AS `w`\n              INNER JOIN `" . PROJECTS . "` AS `proj`\n                ON    `w`.`project_id` = `proj`.`project_id`\n                  AND `proj`.`internal` = 1\n                  AND `proj`.`active` = 1\n            WHERE {$whereConds}\n            GROUP BY `w`.`project_id`, `w`.`status`\n            ORDER BY `w`.`project_id` DESC";
     $results = array();
     $resultQuery = mysql_query($sql) or error_log('getworklist mysql error: ' . mysql_error());
     while ($resultQuery && ($row = mysql_fetch_assoc($resultQuery))) {
         array_push($results, $row);
     }
     return array("search_stats" => $results);
 }
示例#20
0
 public function __construct()
 {
     $this->user_id = Session::uid();
 }
示例#21
0
 public function activeUsers()
 {
     $users = User::getUserList(Session::uid(), 1, 0, true);
     $ret = array();
     $ret[] = array('id' => 0, 'nickname' => 'None', 'selected' => true);
     foreach ($users as $user) {
         $ret[] = array('id' => $user->getId(), 'nickname' => $user->getNickname(), 'selected' => false);
     }
     return $ret;
 }
示例#22
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();
 }