예제 #1
0
 public static function share()
 {
     if (self::$instance == null) {
         self::$instance = new self();
     }
     return self::$instance;
 }
예제 #2
0
 public function testPost()
 {
     $failureAffects = "Affects all post requests sent from Login. Login works but is unable to " . "return any reply to the calling apps as well as to notify other apps(new user, user update, user delete)";
     ob_start();
     CURLHandler::Post('http://www.google.com', array('q' => 'belfabriek'));
     $result = ob_get_contents();
     ob_end_clean();
     $this->assertContains('The request method <code>POST</code>', $result, $failureAffects);
 }
예제 #3
0
 /**
  * [getDES get请求 放回数据DES加密接口]
  * @param {String} $api 必须传,api名 用于获取相应配置
  * @param {String} $act 必须传,请求的api接口
  * @param {Array} $para 请求参数
  * @return {Json} 请求返回数据
  */
 function getDES($api, $act, $para)
 {
     $apiconfig = getC($api);
     $url = @$apiconfig['url'];
     $token = @$apiconfig['apitoken'];
     $para = self::getPara($para);
     $url = $url . "/" . $act . "?" . $para . "&apitoken=" . $token;
     $res = CURLHandler::share()->query($url);
     $res = MyDes::share()->decode($res, @$apiconfig['DES_KEY']);
     $res = json_decode($res);
     return $res;
 }
예제 #4
0
 public static function allAvailableRepositories()
 {
     // 1. Read the config file. Find a link to WebSVN page
     $web_svn_url = self::_webSvnUrl();
     // 2. Retrieve the content of WebSVN front page
     ob_start();
     echo CURLHandler::Get($web_svn_url);
     $html = ob_get_contents();
     ob_end_clean();
     // 3. form the regex pattern. We are searching the html for lines like this:
     // '<a href="listing.php?repname=admin&amp;">admin</a>'. Resulting matches are dumped into 'project' array.
     $repoLinkFragment = preg_quote(self::_repoLinkFragment());
     $regexp = "<a\\s[^>]*href=[\"']" . $repoLinkFragment . "\\b[^>]*>(?P<project>.*)<\\/a>";
     return preg_match_all("/{$regexp}/siU", $html, $matches) ? $matches['project'] : array();
 }
예제 #5
0
 /**
  * 多条短信用 ',' 分隔 
  * @param type $phones
  * @param type $content
  */
 public function send($phones, $content)
 {
     if (!ereg("^.*\$", $phones)) {
         return false;
     }
     if (strlen($phones) < 3) {
         return false;
     }
     $key = getC("SMS_KEY");
     $sucretKey = getC("SMS_SUCRET");
     $url = "http://sms.bechtech.cn/Api/send/data/json?accesskey={$key}&secretkey={$sucretKey}&mobile={$phones}&content=" . urlencode($content);
     //my_log($url);
     if (CURLHandler::share()->query($url) === FALSE) {
         return false;
     }
     return true;
 }
예제 #6
0
파일: api.php 프로젝트: highfidelity/love
function sendloveToAll()
{
    if (empty($_REQUEST['from']) || empty($_REQUEST['why'])) {
        respond(array('success' => false, 'message' => SL_BAD_CALL));
    }
    $query = 'SELECT `nickname` FROM `' . USERS . '` WHERE `nickname` != "' . mysql_real_escape_string($_REQUEST['from']) . '" AND `company_confirm` != 0;';
    if (!($result = mysql_query($query))) {
        respond(array('success' => false, 'message' => SL_DB_FAILURE));
    } else {
        while ($row = mysql_fetch_assoc($result)) {
            $array = array('action' => 'sendlovemsg', 'api_key' => API_KEY, 'caller' => 'admin', 'from' => (string) $_REQUEST['from'], 'to' => (string) $row['nickname'], 'why' => (string) smart_strip_tags($_REQUEST['why']));
            CURLHandler::Post(SERVER_URL . 'api.php', $array, false, true);
        }
        respond(array('success' => true, 'message' => 'Love has been sent!'));
    }
    respond(array('success' => false, 'message' => 'An error occured'));
}
예제 #7
0
 /**
  * Delete controller function
  *
  * Deletes the user with userid.
  * Verifies that the user is authenticated.
  *
  * @return json|xml True on success otherwise false
  */
 public function delete()
 {
     try {
         $error_flag = false;
         $message = "";
         $user = new LoveUser();
         if (!$user->loadUserFromSession()) {
             $error_flag = true;
             $message[] = "Unable to located the user using the current session";
         } else {
             if (!$user->authenticate($_REQUEST["password"])) {
                 $error_flag = true;
                 $message[] = "Invalid password";
             } else {
                 if (!$user->delete()) {
                     $error_flag = true;
                     $message[] = "Delete failed";
                 } else {
                     $message[] = "Delete successful";
                     $user->logout();
                 }
             }
         }
         if ($error_flag) {
             echo json_encode(array("error" => 1, "message" => $message));
             exit(0);
         } else {
             $repost = $this->request->getRepostPage();
             if (isset($repost)) {
                 CURLHandler::doRequest("POST", $repost, $_REQUEST);
             }
             echo json_encode(array("error" => 1, "message" => $message));
             exit(0);
         }
     } catch (Exception $e) {
         $msg = 'An error occured while updating:' . "\n";
         $msg .= "\n" . ' ' . $e->getMessage();
         if (defined('APPLICATION_ENV') && APPLICATION_ENV == 'development') {
             $msg .= "\n\nFile: " . $e->getFile();
             $msg .= "\nLine: " . $e->getLine();
             $msg .= "\n" . $e->getTraceAsString();
         } else {
             if (defined('APPLICATION_ENV') && APPLICATION_ENV == 'testing') {
                 $msg .= "<br /><br />File: " . $e->getFile();
                 $msg .= "<br />Line: " . $e->getLine();
                 $msg .= "<br />" . $e->getTraceAsString();
             }
         }
         echo $msg;
         exit;
     }
 }
예제 #8
0
 public function tryToAuthenticateUser()
 {
     $username = isset($_REQUEST["username"]) ? trim($_REQUEST["username"]) : "";
     $password = isset($_REQUEST["password"]) ? $_REQUEST["password"] : "";
     if (empty($username)) {
         $this->getError()->setError("Username cannot be empty.");
     } else {
         if (empty($password)) {
             $this->getError()->setError("Password cannot be empty.");
         } else {
             $params = array("username" => $username, "password" => $password, "action" => "login");
             ob_start();
             // send the request
             CURLHandler::Post(SERVER_URL . 'loginApi.php', $params, false, true);
             $result = ob_get_contents();
             ob_end_clean();
             $ret = json_decode($result);
             if ($ret->error == 1) {
                 $this->getError()->setError($ret->message);
                 return $this->getError()->getErrorFlag();
             } else {
                 $id = $ret->userid;
                 $username = $ret->username;
                 $nickname = $ret->nickname;
                 $_SESSION["userid"] = $id;
                 $_SESSION["username"] = $username;
                 $_SESSION["nickname"] = $nickname;
                 // notifying other applications
                 $response = new Response();
                 $login = new Login();
                 $login->setResponse($response);
                 $login->notify($id, session_id());
                 return false;
             }
         }
     }
     return $this->getError()->getErrorFlag();
 }
예제 #9
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 <*****@*****.**>';
         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;
     }
 }
예제 #10
0
 public function notify($user_id, $session_id)
 {
     $token = uniqid();
     $this->saveToken($token);
     $this->params["userid"] = $user_id;
     $this->params["sessionid"] = $session_id;
     $this->params["token"] = $token;
     ob_start();
     // send the request
     CURLHandler::Post(LOGIN_APP_URL . 'notify', $this->params, false, true);
     $result = ob_get_contents();
     ob_end_clean();
     $result = json_decode($result);
     if ($result->error == 1) {
         $this->getResponse()->getError()->setError($result->message);
     } else {
         if ($this->checkToken($result->token) && $token == $result->token) {
             $this->updateToken($result->token);
             $this->getResponse()->addParams($result);
         } else {
             $this->getResponse()->getError()->setError("Invalid Token aka Malicious attempt.");
         }
     }
 }
예제 #11
0
function checkRemovableProjects()
{
    $report_message = '';
    $db = new Database();
    $sql_projects = "\n        SELECT p.project_id, p.name, u.nickname, p.creation_date\n        FROM " . PROJECTS . " AS p\n        LEFT JOIN " . USERS . " AS u ON u.id=p.owner_id\n        WHERE p.project_id NOT IN (SELECT DISTINCT w1.project_id\n        FROM " . WORKLIST . " AS w1)\n          AND p.creation_date < DATE_SUB(NOW(), INTERVAL 180 DAY)";
    $result = $db->query($sql_projects);
    while ($row = mysql_fetch_assoc($result)) {
        // send email
        $data = array('owner' => $row['nickname'], 'projectUrl' => Project::getProjectUrl($row['project_id']), 'projectName' => $row['name'], 'creation_date' => date('Y-m-d', strtotime($row['creation_date'])));
        if (Utils::sendTemplateEmail($row['contact_info'], 'project-removed', $data)) {
            $report_message .= ' <p> Ok email---';
        } else {
            $report_message .= ' <p> Failed email -';
        }
        $report_message .= ' Project (' . $row['project_id'] . ')- <a href="' . Project::getProjectUrl($row['project_id']) . '">' . $row['name'] . '</a> -- Created: ' . $row['creation_date'] . '</p>';
        // Remove projects dependencies
        // Remove project users
        $report_message .= '<p> Users removed for project id ' . $row['project_id'] . ':</p>';
        $sql_get_project_users = "SELECT * FROM " . PROJECT_USERS . " WHERE project_id = " . $row['project_id'];
        $result_temp = $db->query($sql_get_project_users);
        while ($row_temp = mysql_fetch_assoc($result_temp)) {
            $report_message .= dump_row_values($row_temp);
        }
        $sql_remove_project_users = "DELETE FROM " . PROJECT_USERS . " WHERE project_id = " . $row['project_id'];
        $db->query($sql_remove_project_users);
        // Remove project runners
        $report_message .= '<p> Designers removed for project id ' . $row['project_id'] . ':</p>';
        $sql_get_project_runners = "SELECT * FROM " . PROJECT_RUNNERS . " WHERE project_id = " . $row['project_id'];
        $result_temp = $db->query($sql_get_project_runners);
        while ($row_temp = mysql_fetch_assoc($result_temp)) {
            $report_message .= dump_row_values($row_temp);
        }
        $sql_remove_project_runners = "DELETE FROM " . PROJECT_RUNNERS . " WHERE project_id = " . $row['project_id'];
        $db->query($sql_remove_project_runners);
        // Remove project roles
        $report_message .= '<p> Roles removed for project id ' . $row['project_id'] . ':</p>';
        $sql_get_project_roles = "SELECT * FROM " . ROLES . " WHERE project_id = " . $row['project_id'];
        $result_temp = $db->query($sql_get_project_roles);
        while ($row_temp = mysql_fetch_assoc($result_temp)) {
            $report_message .= dump_row_values($row_temp);
        }
        $sql_remove_project_roles = "DELETE FROM " . ROLES . " WHERE project_id = " . $row['project_id'];
        $db->query($sql_remove_project_roles);
        $url = TOWER_API_URL;
        $fields = array('action' => 'staging_cleanup', 'name' => $row['name']);
        $result = CURLHandler::Post($url, $fields);
        // Remove project
        $report_message .= '<p> Project id ' . $row['project_id'] . ' removed </p>';
        $sql_get_project = "SELECT * FROM " . PROJECTS . " WHERE project_id = " . $row['project_id'];
        $result_temp = $db->query($sql_get_project);
        while ($row_temp = mysql_fetch_assoc($result_temp)) {
            $report_message .= dump_row_values($row_temp);
        }
        $sql_remove_project = "DELETE FROM " . PROJECTS . " WHERE project_id = " . $row['project_id'];
        $db->query($sql_remove_project);
    }
    // Send report to ops if any project was set as inactive
    if ($report_message != '') {
        $headers['From'] = DEFAULT_SENDER;
        $subject = "Removed Projects Report";
        $body = $report_message;
        if (!Utils::send_email(OPS_EMAIL, $subject, $body, null, $headers)) {
            error_log('checkActiveProjects cron: Failed to send email report');
        }
    }
}
예제 #12
0
 public function tryToAuthenticateUser()
 {
     $username = isset($_REQUEST["username"]) ? trim($_REQUEST["username"]) : "";
     $password = isset($_REQUEST["password"]) ? $_REQUEST["password"] : "";
     if (empty($username)) {
         $this->getError()->setError("Username cannot be empty.");
     } else {
         if (empty($password)) {
             $this->getError()->setError("Password cannot be empty.");
         } else {
             $params = array("username" => $username, "password" => $password, "action" => "login");
             ob_start();
             // send the request
             CURLHandler::Post(SERVER_URL . 'loginApi.php', $params, false, true);
             $result = ob_get_contents();
             ob_end_clean();
             $ret = json_decode($result);
             if ($ret->error == 1) {
                 if (($key = array_search('User is deactivated.', $ret->message)) !== false) {
                     $ret->message[$key] = 'You need to be confirmed!<br /><a href="#" id="ping_admin">Ping the administrator ...</a>';
                 }
                 $this->getError()->setError($ret->message);
                 return $this->getError()->getErrorFlag();
             } else {
                 $id = $ret->userid;
                 $username = $ret->username;
                 $nickname = $ret->nickname;
                 $admin = $ret->admin;
                 Utils::setUserSession($id, $username, $nickname, $admin);
                 // notifying other applications
                 $response = new Response();
                 $login = new Login();
                 $login->setResponse($response);
                 $login->notify($id, session_id());
                 return false;
             }
         }
     }
     return $this->getError()->getErrorFlag();
 }
예제 #13
0
 public function sendHipchat_notification($message, $message_format = 'html', $notify = 0)
 {
     $success = true;
     $room_id = 0;
     $token = $this->getHipchatNotificationToken();
     $url = HIPCHAT_API_AUTH_URL . $token;
     $response = CURLHandler::Get($url, array());
     $response = json_decode($response);
     if (count($response->rooms)) {
         foreach ($response->rooms as $key => $room) {
             if ($room->name == trim($this->getHipchatRoom())) {
                 $room_id = $room->room_id;
                 break;
             }
         }
         if ($room_id > 0) {
             $url = HIPCHAT_API_MESSAGE_URL . $token;
             $fields = array('room_id' => $room_id, 'from' => 'Worklist.net', 'message' => $message, 'message_format' => $message_format, 'notify' => $notify, 'color' => $this->getHipchatColor());
             $result = CURLHandler::Post($url, $fields);
             $result = json_decode($result);
             if ($result->status != 'sent') {
                 $success = false;
                 $body = "Failed to send message: " . $message;
             }
         } else {
             $success = false;
             $body = "Failed to find room " . $this->getHipchatRoom() . ".";
         }
     } else {
         $success = false;
         $body = "Failed to authenticate to hipchat.";
     }
     if ($success == false) {
         $email = $this->getContactInfo();
         $subject = "HipChat Notification Failed";
         if (!Utils::send_email($email, $subject, $body, $body, array('Cc' => OPS_EMAIL))) {
             error_log("project-class.php: sendHipchat_notification : Utils::send_email failed");
         }
     }
 }
예제 #14
0
<?php

//  Copyright (c) 2010, LoveMachine Inc.
//  All Rights Reserved.
//  http://www.lovemachineinc.com
require_once 'class/frontend.class.php';
$front = Frontend::getInstance();
$msg = '';
if (!empty($_POST['submit'])) {
    if (!empty($_POST['password'])) {
        $vars = array('username' => $_POST['username'], 'token' => $_POST['token'], 'password' => $_POST['password']);
        // send the request
        ob_start();
        CURLHandler::Post(LOGIN_APP_URL . 'changepassword', $vars);
        $result = json_decode(ob_get_contents());
        ob_end_clean();
        if ($result->success == true) {
            sendTemplateEmail($_POST['username'], 'changed_pass', array('app_name' => APP_NAME));
            header('Location: login.php');
        } else {
            $msg = 'The link to reset your password has expired or is invalid. <a href="forgot.php">Please try again.</a>';
        }
    } else {
        $msg = "Please enter a password!";
    }
}
if (empty($_REQUEST['token'])) {
    // no required information specified, redirect user
    header('Location: login.php');
}
?>
예제 #15
0
while ($result->fetch()) {
    $split_instance = explode('.', $_domain, 2);
    $query = " SELECT data FROM " . $cupid_config['db_name'] . "." . $cupid_config['db_conf'] . " WHERE domain='{$_domain}' AND config_key='API_KEY' ;";
    $result2 = $mysqli->prepare($query) or error_log("unable to select db: {$query}\n" . $mysqli->error);
    $result2->execute();
    $result2->store_result();
    if ($result2->num_rows == 0) {
        continue;
    }
    // build array of domains
    $result2->bind_result($_api);
    $result2->fetch();
    $vars = array('action' => 'newSignupsReportData', 'api_key' => $_api);
    $url = 'https://' . $split_instance[0] . '.sendlove.us/love/api.php';
    ob_start();
    CURLHandler::Post($url, $vars);
    $CURLresult = json_decode(ob_get_contents());
    ob_end_clean();
    ?>
<tr id="inst_<?php 
    echo $_domain;
    ?>
">
<td class="created"><?php 
    echo $_created;
    ?>
</td>
<td class="company"><?php 
    echo $split_instance[0];
    ?>
</td>
예제 #16
0
function testCURL()
{
    $content = CURLHandler::share()->query("http://www.zsgjs.com");
    my_log($content);
}
예제 #17
0
function sendCCPayment($domain, $databaseName, $fname, $lname, $company, $ref_ids, $email, $phone, $street, $city, $state, $zip, $country, $card_type, $card_number, $cvv, $exp_date, $total, $sub_amt, $can_contact, $ip, $lm_type, $lm_description, $lm_user_id)
{
    //collect confirmed payees and run paypal transaction
    // Set request-specific fields.
    $currency = 'USD';
    // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
    //build nvp string
    $nvp = '';
    $nvp .= '&PAYMENTACTION=Sale';
    $nvp .= '&IPADDRESS=' . urlencode($ip);
    $nvp .= '&AMT=' . urlencode($total);
    $nvp .= '&CURRENCYCODE=' . urlencode($currency);
    $nvp .= '&CREDITCARDTYPE=' . urlencode($card_type);
    $nvp .= '&ACCT=' . urlencode($card_number);
    $nvp .= '&EXPDATE=' . urlencode($exp_date);
    $nvp .= '&CVV2=' . urlencode($cvv);
    $nvp .= '&FIRSTNAME=' . urlencode($fname);
    $nvp .= '&LASTNAME=' . urlencode($lname);
    $nvp .= '&STREET=' . urlencode($street);
    $nvp .= '&CITY=' . urlencode($city);
    $nvp .= '&STATE=' . urlencode($state);
    $nvp .= '&ZIP=' . urlencode($zip);
    $nvp .= '&COUNTRYCODE=' . urlencode($country);
    // store customer data if required, return customer_id for payment
    $cust = storeCustomerData($domain, $fname, $lname, $company, $ref_ids, $email, $phone, $street, $city, $state, $zip, $country, $can_contact);
    if (isset($cust["error"])) {
        return array('error' => "Buyer", 'errorMsg' => "Error in Buyer Creation: " . $cust["error"]);
    } else {
        $cust = $cust['customer_id'];
    }
    $buyer = storeBuyerData($cust, $fname, $lname, $company, $email, $phone, $street, $city, $state, $zip, $country);
    if (isset($ret["error"])) {
        return array('error' => "Buyer", 'errorMsg' => "Error in Buyer Creation: " . $ret["error"]);
    }
    $buyer_id = $buyer["buyer_id"];
    //  $instance = getInstanceNameFromDomain($domain);
    $instance = $databaseName;
    if ($instance == "") {
        return array('error' => "Invalid domain", 'errorMsg' => "Invalid domain: " . $domain);
    }
    $ret = changeCampaignStatus($ref_ids, "R", $instance);
    if (isset($ret["error"])) {
        return array('error' => "Recognition", 'errorMsg' => "Error in Recognition Period Update (R): " . $ret["error"]);
    }
    // Execute the API operation; see the PPHttpPost function in the paypal-functions.php file.
    $PPResponseAr = PPHttpPost('DoDirectPayment', $nvp);
    $warningMsg = "";
    if (isset($PPResponseAr["ACK"])) {
        $transactionID = "";
        if (isset($PPResponseAr["TRANSACTIONID"])) {
            $transactionID = $PPResponseAr["TRANSACTIONID"];
        }
        $longMessage = "";
        if (isset($PPResponseAr["L_LONGMESSAGE0"])) {
            $longMessage = urldecode($PPResponseAr["L_LONGMESSAGE0"]);
        }
        $save = storePaymentData($cust, $card_type, $PPResponseAr["ACK"], $total, $sub_amt, $transactionID, $ip, $lm_type, $domain, $ref_ids, $lm_description, $lm_user_id, $buyer_id, $longMessage);
        if (isset($save['error'])) {
            $payment = -1;
            $warningMsg .= '<p>Warning: ' . $save['error'] . "</p>";
        } else {
            $payment = $save['payment_id'];
        }
    }
    if (isset($PPResponseAr["ACK"]) && ("SUCCESS" == strtoupper($PPResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($PPResponseAr["ACK"]))) {
        $ret = changeCampaignStatus($ref_ids, "Y", $instance);
        if (isset($ret["error"])) {
            $warningMsg .= "<p>Warning: Error in Recognition Period Update (Y), " . $ret["error"] . "</p>";
        }
        $invoice = 1000000 + intval($payment);
        $invoice = $cust . '' . $invoice;
        //payment posted
        /**
         *   $PPResponseAr["TIMESTAMP"] 
         *   $PPResponseAr["CORRELATIONID"]
         *   $PPResponseAr["ACK"]
         *   $PPResponseAr["VERSION"] 
         *   $PPResponseAr["BUILD"]
         *   $PPResponseAr["AMT"]
         *   $PPResponseAr["CURRENCYCODE"] 
         *   $PPResponseAr["AVSCODE"] //X 
         *   $PPResponseAr["CVV2MATCH"]  //M
         *   $PPResponseAr["TRANSACTIONID"]
         */
        $name = $fname . ' ' . $lname;
        success_notify($name, $email, $company, $street, $city, $state, $zip, $country, $phone, $lm_description, $total, $invoice, $PPResponseAr["TRANSACTIONID"]);
        $messJournal = "A payment has been made for a Recognition Period!";
        if ("SUCCESSWITHWARNING" == strtoupper($PPResponseAr["ACK"])) {
            $messJournal .= " Warning in Paypal transaction.";
        }
        // Make a notice in journal
        $data = array('user' => JOURNAL_API_USER, 'pwd' => sha1(JOURNAL_API_PWD), 'message' => $messJournal);
        ob_start();
        $res = CURLHandler::Post(JOURNAL_API_URL, $data);
        ob_end_clean();
        $ret = array('success' => strtoupper($PPResponseAr["ACK"]), 'transactionID' => $PPResponseAr["TRANSACTIONID"], 'warning' => $warningMsg);
    } else {
        // We are not in an asynchronous process so put back the campaign in card
        $ret = changeCampaignStatus($ref_ids, "C", $instance);
        if (isset($ret["error"])) {
            $warningMsg .= "<p>Warning: Error in Recognition Period Update (N), " . $ret["error"] . "</p>";
        }
        if (isset($PPResponseAr["L_SEVERITYCODE0"])) {
            $errorMsg = $PPResponseAr["ACK"] . ", " . $PPResponseAr["L_SEVERITYCODE0"] . ': ' . urldecode($PPResponseAr["L_SHORTMESSAGE0"]) . ' (' . $PPResponseAr["L_ERRORCODE0"] . ') - ' . urldecode($PPResponseAr["L_LONGMESSAGE0"]) . $warningMsg;
        } else {
            $errorMsg = $PPResponseAr["ACK"] . ", " . $PPResponseAr["errorMsg"] . $warningMsg;
        }
        fail_notify($fname . ' ' . $lname, $email, $company, $street, $city, $state, $zip, $country, $phone, $lm_description, $total, $errorMsg);
        if (isset($PPResponseAr["L_SEVERITYCODE0"])) {
            $ret = array('error' => $PPResponseAr["L_ERRORCODE0"], 'errorMsg' => $errorMsg);
        } else {
            $ret = array('error' => $PPResponseAr["ACK"], 'errorMsg' => $errorMsg);
        }
    }
    return $ret;
}
예제 #18
0
 /**
  * Async wrapper to Notification::statusNotify to avoid big delays
  * on massive notifications.
  *
  * @param object $workitem instance of a Workitem class
  */
 function massStatusNotify($workitem)
 {
     return CURLHandler::Post(SERVER_URL . 'api.php', array('action' => 'sendNotifications', 'api_key' => API_KEY, 'command' => 'statusNotify', 'workitem' => $workitem->getId()), false, false, true);
 }
예제 #19
0
<?php

//  Copyright (c) 2009, LoveMachine Inc.
//  All Rights Reserved.
//  http://www.lovemachineinc.com
require_once "class/frontend.class.php";
require_once "send_email.php";
$front = Frontend::getInstance();
if (!empty($_POST['username'])) {
    ob_start();
    // send the request
    CURLHandler::Post(LOGIN_APP_URL . 'resettoken', array('username' => $_POST['username'], 'app' => 'lovemachine', 'key' => API_KEY));
    $result = ob_get_contents();
    ob_end_clean();
    $result = json_decode($result);
    if ($result->success == true) {
        $resetUrl = SECURE_SERVER_URL . 'resetpass.php?un=' . base64_encode($_POST['username']) . '&token=' . $result->token;
        $resetUrl = '<a href="' . $resetUrl . '" title="Password Recovery">' . $resetUrl . '</a>';
        sendTemplateEmail($_POST['username'], 'recovery', array('url' => $resetUrl));
        $msg = '<p class="LV_valid">Login information will be sent if the email address ' . $_POST['username'] . ' is registered.</p>';
    } else {
        $msg = '<p class="LV_invalid">Sorry, unable to send password reset information. Try again or contact an administrator.</p>';
    }
}
/*********************************** HTML layout begins here  *************************************/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SendLove | Reset Password</title>
예제 #20
0
 public function notifyOfUpdate($calling_app, $user_id, $user_data)
 {
     global $regApps;
     // push notification of logged in user to each of registered apps
     // except of calling app
     foreach ($regApps as $app => $info) {
         if (!$info or empty($info['endpoint']) or empty($info['key']) or empty($info['listenUpdate']) or $calling_app == $app) {
             continue;
         }
         // setting request variables
         $vars = array('action' => 'updateuser', 'user_id' => $user_id, 'api_key' => $info['key']);
         foreach ($user_data as $key => $value) {
             $vars["user_data"][$key] = $value;
         }
         ob_start();
         // send the request
         CURLHandler::Post($info['endpoint'], $vars);
         $result = ob_get_contents();
         ob_end_clean();
     }
     return true;
 }
예제 #21
0
파일: api.php 프로젝트: highfidelity/love
function newInstance($silent = false)
{
    //gj([X.X.X] - sanitize input, register patterns globally for readability and consistency. email, adword, instance, etc)
    if (empty($_REQUEST['domain'])) {
        respond(array('success' => false, 'message' => 'domain is required'));
    } else {
        $domain = preg_replace("/[^a-zA-Z0-9\\-\\.]/", "", $_REQUEST['domain']);
    }
    if (empty($_REQUEST['email'])) {
        respond(array('success' => false, 'message' => 'email is required'));
    } else {
        $email = $_REQUEST['email'];
        $email = preg_replace("/[^a-zA-Z0-9\\@\\-\\.]/", "", $_REQUEST['email']);
    }
    if (empty($_REQUEST['first_name'])) {
        respond(array('success' => false, 'message' => 'first_name is required'));
    } else {
        $first_name = $_REQUEST['first_name'];
        $first_name = preg_replace("/[^a-zA-Z0-9]/", "", $_REQUEST['first_name']);
    }
    if (empty($_REQUEST['uuid'])) {
        respond(array('success' => false, 'message' => 'uuid is required'));
    } else {
        $uuid = $_REQUEST['uuid'];
        $uuid = preg_replace("/[^a-fA-F0-9\\-\\.]/", "", $_REQUEST['uuid']);
    }
    if (empty($_REQUEST['db_name'])) {
        respond(array('success' => false, 'message' => 'db_name is required'));
    } else {
        $db_name = $_REQUEST['db_name'];
        $db_name = preg_replace("/[^a-zA-Z0-9\\_]/", "", $_REQUEST['db_name']);
    }
    if (empty($_REQUEST['instance_api_key'])) {
        respond(array('success' => false, 'message' => 'instance_api_key is required'));
    } else {
        $instance_api_key = preg_replace("/[^a-fA-F0-9\\-]/", "", $_REQUEST['instance_api_key']);
    }
    if (empty($_REQUEST['source'])) {
        $source = "Other";
    } else {
        $source = preg_replace("/[^a-zA-Z0-9\\-\\_\\ \\.]/", "", $_REQUEST['source']);
    }
    if (empty($_REQUEST['adwords'])) {
        $adwords = 'null';
    } else {
        $adwords = preg_replace("/[^a-zA-Z0-9\\-\\_\\ \\.]/", "", $_REQUEST['adwords']);
    }
    $sql = "INSERT INTO " . CUSTOMERS . " SET uuid='{$uuid}', instance_api_key='{$instance_api_key}', created=NOW(), domain='{$domain}', contact_email='{$email}', contact_first_name='{$first_name}', employee_count=1, recur_date = DATE_ADD(now(), INTERVAL +1 MONTH), source='{$source}', keywords='{$adwords}', db_name='{$db_name}'";
    #echo $sql;
    error_log("salesNewInstance  sql: " . $sql);
    $result = mysql_query($sql) or error_log('salesNI.error: ' . mysql_error());
    if (mysql_affected_rows() == 0) {
        respond(array('success' => false, 'message' => SL_DB_FAILURE));
    } else {
        if ($silent !== true) {
            if ($silent != true) {
                error_log("salesNewInstance  announce: " . JOURNAL_API_URL);
                // Make notice in journal
                $data = array('user' => JOURNAL_API_USER, 'pwd' => sha1(JOURNAL_API_PWD), 'message' => "A new LoveMachine " . $silent . " tenant has just moved in!");
                $journal_rsp = CURLHandler::Post(JOURNAL_API_URL, $data);
            }
            error_log("salesNewInstance  respond: " . json_encode(array('journal_rsp' => $journal_rsp, 'data' => $data)));
            respond(array('success' => true, 'message' => 'entry added'));
        }
    }
}
예제 #22
0
 /**
  * Email sending wrapper
  */
 public static function send_email($to, $subject, $html, $plain = null, $headers = array())
 {
     //Validate arguments
     $html = str_replace(array('\\n\\r', '\\r\\n', '\\n', '\\r'), '<br/>', $html);
     if (empty($to) || empty($subject) || (empty($html) && empty($plain) || !is_array($headers))) {
         error_log("attempted to send an empty or misconfigured message");
         return false;
     }
     $nameAndAddressRegex = '/(.*)<(.*)>/';
     $toIncludesNameAndAddress = preg_match($nameAndAddressRegex, $to, $toDetails);
     if ($toIncludesNameAndAddress) {
         $toName = $toDetails[1];
         $toAddress = $toDetails[2];
     } else {
         $toName = $to;
         $toAddress = $to;
     }
     // If no 'From' address specified, use default
     if (empty($headers['From'])) {
         $fromName = DEFAULT_SENDER_NAME;
         $fromAddress = DEFAULT_SENDER;
     } else {
         $fromIncludesNameAndAddress = preg_match($nameAndAddressRegex, $headers['From'], $fromDetails);
         if ($fromIncludesNameAndAddress) {
             $fromName = str_replace('"', '', $fromDetails[1]);
             $fromAddress = str_replace(' ', '-', $fromDetails[2]);
         } else {
             $fromName = $headers['From'];
             $fromAddress = str_replace(' ', '-', $headers['From']);
         }
     }
     if (!empty($html)) {
         if (empty($plain)) {
             $h2t = new Html2Text(html_entity_decode($html, ENT_QUOTES), 75);
             $plain = $h2t->convert();
         }
     } else {
         if (empty($plain)) {
             // if both HTML & Plain bodies are empty, don't send mail
             return false;
         }
     }
     $curl = new CURLHandler();
     $postArray = array('from' => $fromAddress, 'fromname' => $fromName, 'to' => $toAddress, 'toname' => $toName, 'subject' => $subject, 'html' => $html, 'text' => $plain, 'api_user' => SENDGRID_API_USER, 'api_key' => SENDGRID_API_KEY);
     if (!empty($headers['Reply-To'])) {
         $replyToIncludesNameAndAddress = preg_match($nameAndAddressRegex, $headers['Reply-To'], $replyToDetails);
         if ($replyToIncludesNameAndAddress) {
             $postArray['replyto'] = str_replace(' ', '-', $replyToDetails[2]);
         } else {
             $postArray['replyto'] = $headers['Reply-To'];
         }
     }
     // check for copy, using bcc since cc is not present in Sendgrid api
     if (!empty($headers['Cc'])) {
         $ccIncludesNameAndAddress = preg_match($nameAndAddressRegex, $headers['Cc'], $ccDetails);
         if ($ccIncludesNameAndAddress) {
             $postArray['bcc'] = str_replace(' ', '-', $ccDetails[2]);
         } else {
             $postArray['bcc'] = $headers['Cc'];
         }
     }
     try {
         $result = json_decode(CURLHandler::Post(SENDGRID_API_URL, $postArray));
         if ($result->message == 'error') {
             throw new Exception(implode('; ', $result->errors));
         }
     } catch (Exception $e) {
         error_log("[ERROR] Unable to send message through SendGrid API - Exception: " . $e->getMessage());
         return false;
     }
     return true;
 }
예제 #23
0
$front = Frontend::getInstance();
include_once "db_connect.php";
include_once "autoload.php";
if (!defined('LOVE_TABS_DISABLED')) {
    define('LOVE_TABS_DISABLED', false);
}
if (!$front->isUserLoggedIn()) {
    $front->getUser()->askUserToAuthenticate();
}
// check for new user
if (isset($_SESSION['new_user']) && $_SESSION['new_user']) {
    $id = $_SESSION['userid'];
    $token = uniqid();
    ob_start();
    // send the request
    CURLHandler::Post(LOGIN_APP_URL . 'pushadminuser', array('app' => SERVICE_NAME, 'key' => API_KEY, 'id' => $id, 'token' => $token), false, true);
    $result = ob_get_contents();
    ob_end_clean();
    $result = json_decode($result);
    if ($result->error != 0) {
        error_log('settings.php: ' . json_encode($result));
        die(json_encode(array('error' => 1, 'message' => $result['message'])));
    } else {
        // turn off new user flag
        $_SESSION['new_user'] = '';
        // reload settings page
        header('Location: settings.php');
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
예제 #24
0
     }
 }
 if ($updateNickname || $updatePassword) {
     $params = array('action' => 'update', 'user_data' => array('userid' => $_SESSION['userid']));
     if ($updateNickname) {
         $params['user_data']['nickname'] = $_REQUEST['nickname'];
     }
     if ($updatePassword) {
         $params['user_data']['newpassword'] = $_REQUEST['newpassword'];
         $params['user_data']['oldpassword'] = $_REQUEST['oldpassword'];
         $messages[] = "Your password has been updated.";
     }
     $params['sid'] = session_id();
     ob_start();
     // send the request
     CURLHandler::Post(SERVER_URL . 'loginApi.php', $params, false, true);
     $result = ob_get_contents();
     ob_end_clean();
     $result = json_decode($result);
     if ($result->error == false) {
         // only update nickname if necessary
         if ($updateNickname) {
             $sql = "UPDATE " . USERS . " SET nickname='" . mysql_real_escape_string($nickname) . "' WHERE id ='" . $_SESSION['userid'] . "'";
             mysql_query($sql);
             $_SESSION['nickname'] = $nickname;
             $messages[] = "Your nickname is now '{$nickname}'.";
         }
     } else {
         die(json_encode($result));
     }
 }