Example #1
0
function getVendors( )
{
global $db;

$query = "select * from Vendors";

if (!$result = $db->sql_query($query))
	{
	RestLog("Error 16522 in query: $query\n".$db->sql_error());
	RestUtils::sendResponse(500, "16522 - There was a problem attempting to locate the PO"); //Internal Server Error
	return false;
	}

$i = 0;
while ( $row = $db->sql_fetchrow( $result ) )
	{
	$vendors[$i]['VendorID'] 	= $row['VendorID'];
	$vendors[$i]['VendorName']	= $row['VendorName'];
	$i++;
	}



RestLog("Successful Request\n");
//08.10.2012 naj - return code 200 OK.
RestUtils::sendResponse(200,json_encode( stripHTML( $vendors ) ));
return true;
}
Example #2
0
 protected function download()
 {
     $filename = $this->fileURL;
     $this->localFile = null;
     if (file_exists($filename)) {
         // local file
         $this->localFile = $this->fileURL;
     } else {
         // might be remote file
         // try to download
         // check if remote location exists
         if (RestUtils::url_exists($this->fileURL)) {
             $tmpName = tempnam(sys_get_temp_dir(), 'smafe_');
             $tmpFilename = $tmpName . '_' . basename($this->fileURL);
             $success = copy($this->fileURL, $tmpFilename);
             if ($success) {
                 $this->localFile = $tmpFilename;
                 //log the file download and create a local urlinfo file
                 MyLog::printWithDuration("Downloaded URL: {$this->fileURL} to Local File: {$this->localFile}");
                 $handle = fopen($tmpName, "w");
                 fwrite($handle, "local     : {$this->localFile}\n");
                 fwrite($handle, "url       : {$this->fileURL}\n");
                 fwrite($handle, "ext key   : {$this->external_key}\n");
                 fwrite($handle, "collection: {$this->collection}\n");
                 fclose($handle);
             }
         }
     }
 }
Example #3
0
 public function executeApi(sfWebRequest $request)
 {
     $data = RestUtils::processRequest();
     $res = "";
     $code = 200;
     try {
         switch ($data->getMethod()) {
             case 'get':
                 $method = $request->getParameter('method');
                 $res = $this->{$method}($data);
                 break;
             case 'post':
                 //parse_str(file_get_contents('php://input'), $put_vars);
                 $method = "post_" . $request->getParameter('method', 'review');
                 $res = $this->{$method}($data);
                 break;
         }
     } catch (BadRequestException $e) {
         $res = $e->getMessage();
         $code = 400;
     } catch (Exception $e) {
         $res = $e->getMessage();
         $code = 500;
     }
     RestUtils::sendResponse($code, json_encode($res), 'application/json');
 }
Example #4
0
    public static function sendResponse($status = 200, $body = '', $content_type = 'text/html', $file_err = '')
    {
        $status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status);
        // set the status
        header($status_header);
        // set the content type
        header('Content-type: ' . $content_type);
        // pages with body are easy
        if ($body != '') {
            // send the body
            echo $body;
            exit;
        } else {
            // create some body messages
            switch ($status) {
                case 401:
                    $message = 'You must be authorized.';
                    break;
                case 404:
                    $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
                    break;
                case 500:
                    $message = 'The server encountered an error processing your request.';
                    break;
                case 501:
                    $message = 'The requested method is not implemented.';
                    break;
                case 'Fail':
                    $message = $file_err;
                    break;
                case 'auth_error':
                    $message = 'Try another login.';
                    break;
            }
            // servers don't always have a signature turned on (this is an apache directive "ServerSignature On")
            $signature = $_SERVER['SERVER_SIGNATURE'] == '' ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
            // this mybe templatized ...
            $body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
					<html>
					<head>
						<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
						<title>' . $status . ' ' . RestUtils::getStatusCodeMessage($status) . '</title>
					</head>
					<body>
						<h1>' . RestUtils::getStatusCodeMessage($status) . '</h1>
						<p>' . $message . '</p>
						<hr />
						<address>' . $signature . '</address>
					</body>
					</html>';
            echo $body;
            exit;
        }
    }
Example #5
0
 function query($sql)
 {
     $q = mysql_query($sql);
     //die('SQL: '.$sql.'<br/>Error: '.mysql_error());
     if (!$q) {
         RestUtils::error(500, mysql_error() . "\n" . $sql);
     }
     //			die(mysql_error()."\n".$sql);
     //			throw new Exception('SQL: '.$sql.'<br/>Error: '.mysql_error());
     return $q;
 }
    public static function sendResponse($status = 200, $body = '', $content_type = 'text/html')
    {
        $status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status);
        // set the status
        header($status_header);
        // set the content type
        header('Content-type: ' . $content_type);
        // pages with body are easy
        if ($body != '') {
            // send the body
            echo $body;
            exit;
        } else {
            // create some body messages
            $message = '';
            // this is purely optional, but makes the pages a little nicer to read
            // for your users.  Since you won't likely send a lot of different status codes,
            // this also shouldn't be too ponderous to maintain
            switch ($status) {
                case 401:
                    $message = 'You must be authorized to view this page.';
                    break;
                case 404:
                    $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
                    break;
                case 500:
                    $message = 'The server encountered an error processing your request.';
                    break;
                case 501:
                    $message = 'The requested method is not implemented.';
                    break;
            }
            // servers don't always have a signature turned on (this is an apache directive "ServerSignature On")
            $signature = $_SERVER['SERVER_SIGNATURE'] == '' ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
            // this should be templatized in a real-world solution
            $body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">  
						<html>  
							<head>  
								<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  
								<title>' . $status . ' ' . RestUtils::getStatusCodeMessage($status) . '</title>  
							</head>  
							<body>  
								<h1>' . RestUtils::getStatusCodeMessage($status) . '</h1>  
								<p>' . Hello . '<p>
								<p>' . $message . '</p>  
								<hr />  
								<address>' . $signature . '</address>  
							</body>  
						</html>';
            echo $body;
            exit;
        }
    }
Example #7
0
function getItemInfo($vars, $responsetype)
{
    global $db;
    $ar = $vars;
    if (empty($ar) || !isset($ar['VendorID']) || !isset($ar['ItemNumber'])) {
        RestLog("16584 - Insufficient data provided for creating order \n" . print_r($vars, true) . "\n");
        RestUtils::sendResponse(400, "16584 - Insufficient data provided");
        //Internal Server Error
        return false;
    }
    //now we grab inventory records for the requested item and build up our package to return
    //to the dealer
    //08.28.2015 ghh -  added weight field
    $query = "select Items.ItemID, Items.MSRP, NLA, CloseOut,\n\t\t\t\tPriceCode, Cost, MAP, Category, \n\t\t\t\tManufItemNumber, ManufName, SupersessionID, Weight\n\t\t\t\tfrom Items\n\t\t\t\twhere \n\t\t\t\tItemNumber='{$ar['ItemNumber']}' and\n\t\t\t\tVendorID={$ar['VendorID']}";
    if (!($result = $db->sql_query($query))) {
        RestLog("Error 16585 in query: {$query}\n" . $db->sql_error());
        RestUtils::sendResponse(500, "16585 - There was a problem getting item information.");
        //Internal Server Error
        return false;
    }
    $row = $db->sql_fetchrow($result);
    $item['OrigManufName'] = $row['ManufName'];
    $item['OrigManufNumber'] = $row['ManufItemNumber'];
    $item['NLA'] = $row['NLA'];
    $item['CloseOut'] = $row['CloseOut'];
    $item['MSRP'] = $row['MSRP'];
    $item['Category'] = $row['Category'];
    $item['MAP'] = $row['MAP'];
    $item['Weight'] = $row['Weight'];
    //08.28.2015 ghh -
    if ($row['ItemID'] > 0) {
        $item['Cost'] = getItemCost($row['ItemID'], $ar['DealerID'], $row['PriceCode'], $row['Cost'], $row['MSRP']);
    }
    //08.25.2015 ghh -  if BSV asked for full detail then we're also going to send back
    //images data and other items of interest
    if ($row['SupersessionID'] > 0) {
        $query = "select ItemNumber from Items where ItemID={$row['SupersessionID']}";
        if (!($tmpresult = $db->sql_query($query))) {
            RestLog("Error 16586 in query: {$query}\n" . $db->sql_error());
            RestUtils::sendResponse(500, "16586 - There was a problem retrieving the supersession number");
            //Internal Server Error
            return false;
        }
        $tmprow = $db->sql_fetchrow($tmpresult);
        $item['SupersessionNumber'] = $tmprow['ItemNumber'];
    }
    RestLog("Successful Request\n");
    //08.10.2012 naj - return code 200 OK.
    RestUtils::sendResponse(200, json_encode(stripHTML($item)));
    return true;
}
Example #8
0
function send($data, $send_data)
{
    //dependiendo de si nuestro cliente quiere json o xml se lo enviaremos de una forma u otra.
    //echo $data->getHttpAccept();
    RestUtils::sendResponse(200, json_encode($send_data), 'application/json');
    /*if($data->getHttpAccept() == 'json'){
    			RestUtils::sendResponse(200, json_encode($send_data),'application/json');
    		}/*else if($data->getHttpAccept() == 'xml'){
    			// Usamos el serializador de xml de PEAR
    			$options = array ('indent' => ' ','addDecl' => false,'rootName' => $fc->getAction(), XML_SERIALIZER_OPTION_RETURN_RESULT => true);
    			$serializer = new XML_Serializer($options);
    			RestUtils::sendResponse(200, $serializer->serialize($send_data),'application/xml');
    		}//*/
}
Example #9
0
 public function action_preview_syllabus()
 {
     return false;
     # This needs to be revamped, but the coding for previews is still usable.
     $rest = new RestServer();
     $request = RestUtils::processRequest();
     $required = array("filename", "dept");
     $keys = array_keys($request);
     if (count(array_intersect($required, $keys)) != count($required)) {
         return RestUtils::sendResponse(308);
     }
     if (isset($_REQUEST["filename"], $_REQUEST["dept"])) {
         $width = isset($_REQUEST["w"]) ? $_REQUEST["w"] : 600;
         $height = isset($_REQUEST["h"]) ? $_REQUEST["h"] : 300;
         $dept = $_REQUEST["dept"];
         $filename = $_REQUEST["filename"];
         $user = Yii::app()->user->getState("_user");
         if (!$user->has_permission($dept)) {
             return print "You do not have permission to view this syllabus.";
         }
         $file = "C:/archive/" . $dept . "/" . $filename;
         $pathinfo = pathinfo($file);
         if ($pathinfo["extension"] == "pdf") {
             return print '<embed src="http://compass.colorado.edu/archive/' . $dept . '/' . $filename . '#view=FitH" width="' . $width . 'px" height="' . $height . 'px"/>';
         } elseif ($pathinfo["extension"] == "doc" or $pathinfo["extension"] == "docx") {
             return print '<iframe src="//docs.google.com/viewer?url=http%3A%2F%2Fcompass.colorado.edu%2Farchive%2F' . $dept . '%2F' . $filename . '&embedded=true" width="' . $width . 'px" height="' . $height . '" style="border: none;"></iframe>';
         } elseif ($pathinfo["extension"] == "txt" or $pathinfo["extension"] == "html") {
             return print file_get_contents($file);
         }
         return print "";
     }
     $syllabus = new SyllabusObj(@$_REQUEST["sid"]);
     if (!$syllabus->loaded) {
         return print "Could not load syllabus with id: " . $_REQUEST["sid"];
     }
     $class = new ClassObj($syllabus->classid);
     if (!$syllabus->loaded) {
         return print "Could not load class with id: " . $syllabus->classid;
     }
     $width = isset($_REQUEST["w"]) ? $_REQUEST["w"] - 50 : 600;
     $height = isset($_REQUEST["h"]) ? $_REQUEST["h"] - 70 : 300;
     if ($syllabus->type == "pdf") {
         return print '<embed src="http://compass.colorado.edu/archive/' . $class->course->prefix . '/' . $syllabus->filename . '#view=FitH" width="' . $width . 'px" height="' . $height . 'px"/>';
     } elseif ($syllabus->type == "doc" or $syllabus->type == "docx") {
         return print '<iframe src="//docs.google.com/viewer?url=http%3A%2F%2Fcompass.colorado.edu%2Farchive%2F' . $class->course->prefix . '%2F' . $syllabus->filename . '&embedded=true" width="' . $width . 'px" height="' . $height . '" style="border: none;"></iframe>';
     }
     return print "";
 }
Example #10
0
 public function actionFBLookup()
 {
     $rest = new RestServer();
     $request = RestUtils::processRequest();
     $required = array("q");
     $keys = array_keys($request);
     if (count(array_intersect($required, $keys)) != count($required)) {
         return RestUtils::sendResponse(308);
     }
     # The Directory we're connecting with is the Active Directory for the Campus
     # (not to be confused with this application's name)
     $ldap = new ADAuth("directory");
     $ldap->bind_anon();
     $info = $ldap->lookup_user($request["q"]);
     if ($info["count"] == 0) {
         return print json_encode(array());
     }
     return print json_encode(array($request["attribute"] => @$info[0][$request["attribute"]][0]));
 }
Example #11
0
    public static function sendResponse($status = 200, $body = '', $content_type = 'text/html')
    {
        $status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status);
        header($status_header);
        header('Content-type: ' . $content_type);
        if ($body != '') {
            echo $body;
            exit;
        } else {
            $message = '';
            switch ($status) {
                case 401:
                    $message = 'You must be authorized to view this page.';
                    break;
                case 404:
                    $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
                    break;
                case 500:
                    $message = 'The server encountered an error processing your request.';
                    break;
                case 501:
                    $message = 'The requested method is not implemented.';
                    break;
            }
            // servers don't always have a signature turned on (this is an apache directive "ServerSignature On")
            $signature = $_SERVER['SERVER_SIGNATURE'] == '' ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
            $body = '<!doctype html>
				<html>
				<head>
				<title>' . $status . ' ' . RestUtils::getStatusCodeMessage($status) . '</title>
				</head>
				<body>
				<h1>' . RestUtils::getStatusCodeMessage($status) . '</h1>
				<p>' . $message . '</p>
				<hr/>
				<address>' . $signature . '</address>
				</body>
				</html>';
            echo $body;
            exit;
        }
    }
Example #12
0
public static function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status);
// set the status
header($status_header);
// set the content type
header('Content-type: ' . $content_type);
// set the location header if the status is 201
if ($status == '201')
	header('Location: '.$_SERVER['REQUEST_URI'].'/'.$body);
// pages with body are easy
if($body != '')
	{
	// send the body
	header('Content-Length: '.strlen($body));
	echo $body;
	exit;
	}
// we need to create the body if none is passed
else
	{
	// servers don't always have a signature turned on (this is an apache directive "ServerSignature On")
	$signature = $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'];

	// this should be templatized in a real-world solution
	$body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
					<html>
						<head>
							<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
							<title>' . $status . ' ' . RestUtils::getStatusCodeMessage($status) . '</title>
						</head>
						<body>
							<h1>' . RestUtils::getStatusCodeMessage($status) . '</h1>
							<address>' . $signature . '</address>
						</body>
					</html>';

	header('Content-Length: '.strlen($body));
	echo $body;
	exit;
	}
}
Example #13
0
 protected function download()
 {
     $filename = $this->fileURL;
     $this->localFile = null;
     if (file_exists($filename)) {
         // local file
         $this->localFile = $this->fileURL;
     } else {
         // might be remote file
         // try to download
         // check if remote location exists
         if (RestUtils::url_exists($this->fileURL)) {
             $tmpFilename = tempnam(sys_get_temp_dir(), 'smafe_') . '_' . basename($this->fileURL);
             $success = copy($this->fileURL, $tmpFilename);
             if ($success) {
                 $this->localFile = $tmpFilename;
             }
         }
     }
 }
Example #14
0
 public static function sendResponse($status = 200, $body = '', $content_type = 'text/html')
 {
     $status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status);
     // establecemos status
     header($status_header);
     // el tipo de contenido
     header('Content-type: ' . $content_type);
     // mostramos exclusivamente el cuerpo si está creado
     if ($body != '') {
         echo $body;
         exit;
     } else {
         // en caso de que el cuerpo del mensaje sea vacio, necesitaremos construirlo
         // creamos la variable
         $message = '';
         // Esta parte es opcional pero quedara mas presentable a los usuarios
         switch ($status) {
             case 401:
                 $message = 'Debes estar autorizado para ver esta pagina.';
                 break;
             case 404:
                 $message = 'La URL solicitada ' . $_SERVER['REQUEST_URI'] . ' noexiste.';
                 break;
             case 500:
                 $message = 'Se ha encontrado un error al procesar la peticion.';
                 break;
             case 501:
                 $message = 'El metodo solicitado no esta implementado.';
                 break;
         }
         // A veces la firma del servidor no esta activa (es la directiva apache "ServerSignature On")
         $signature = $_SERVER['SERVER_SIGNATURE'] == '' ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . 'Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
         // Lo suyo es que esta parte este en una plantilla
         $body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>' . $status . ' ' . RestUtils::getStatusCodeMessage($status) . '</title></head><body><h1>' . RestUtils::getStatusCodeMessage($status) . '</h1><p>' . $message . '</p><hr /><address>' . $signature . '</address></body></html>';
         echo $body;
         exit;
     }
 }
Example #15
0
 /**
  * Throw exception.
  *
  * @param integer $httpCode
  * @throws \Exception
  */
 private function throwException($httpCode)
 {
     if (null === $httpCode) {
         throw new \Exception('Something went wrong. StausCode is null.');
     } else {
         $errorResponseBody = json_decode($this->getResponseBody(), true);
         $errorMessage = RestUtils::getStatusCodeMessage($httpCode) . '. ';
         if (is_array($errorResponseBody)) {
             if (array_key_exists('error', $errorResponseBody)) {
                 $errorMessage .= $errorResponseBody['error'] . '.';
             } else {
                 if (array_key_exists('errors', $errorResponseBody)) {
                     $errorMessage .= is_array($errorResponseBody['errors']) ? implode('. ', array_map('ucfirst', $errorResponseBody['errors'])) : $errorResponseBody['errors'];
                     $errorMessage .= '.';
                 }
             }
         }
         throw new \Exception($errorMessage, $httpCode);
     }
 }
Example #16
0
 public static function processAPICall($calledMethod, $data)
 {
     $valid = API::validateCall();
     if (!$valid) {
         $returnedData = null;
         $statusCode = 401;
     } else {
         switch ($calledMethod) {
             case 'lookup':
                 if (isset($data->getData()->q)) {
                     $returnedData = API::lookup($data->getData()->q, "api");
                     $statusCode = 200;
                 } else {
                     // bad request, lacking query
                     $returnedData = null;
                     $statusCode = 400;
                 }
                 break;
             case 'search':
                 if (isset($data->getData()->q) && isset($data->getData()->platform) && isset($data->getData()->type)) {
                     if (isset($data->getData()->limit)) {
                         $limit = $data->getData()->limit;
                     } else {
                         $limit = 999;
                     }
                     $returnedData = API::search($data->getData()->q, $data->getData()->platform, $data->getData()->type, $limit);
                     if ($returnedData == null) {
                         $returnedData = null;
                         $statusCode = 204;
                     } else {
                         if ($returnedData == -42) {
                             $returnedData = null;
                             $statusCode = 406;
                         } else {
                             $statusCode = 200;
                         }
                     }
                 } else {
                     // bad request, lacking query
                     $returnedData = null;
                     $statusCode = 400;
                 }
                 break;
             case 'aggregate':
                 if (isset($data->getData()->q) && isset($data->getData()->type)) {
                     if (isset($data->getData()->limit)) {
                         $limit = $data->getData()->limit;
                     } else {
                         $limit = 999;
                     }
                     if (isset($data->getData()->platforms)) {
                         $platforms = explode(',', $data->getData()->platforms);
                     } else {
                         $platforms = null;
                     }
                     $returnedData = API::aggregate($data->getData()->q, $data->getData()->type, $platforms, $limit);
                     $statusCode = 200;
                 } else {
                     // bad request, lacking query
                     $returnedData = null;
                     $statusCode = 400;
                 }
                 break;
             default:
                 // Method name is not good
                 $returnedData = null;
                 $statusCode = 501;
                 break;
         }
     }
     RestUtils::sendResponse($statusCode, $returnedData, $data->getHttpAccept(), true, null);
     // true = api mode, null = no key for json
 }
Example #17
0
 public function AddLogEntryFromJSON($oJson, $bCheckUserId = true)
 {
     $sText = isset($oJson->message) ? $oJson->message : '';
     if (isset($oJson->user_id)) {
         if (!UserRights::IsAdministrator()) {
             throw new Exception("Only administrators can set the user id", RestResult::UNAUTHORIZED);
         }
         if ($bCheckUserId && $oJson->user_id != 0) {
             try {
                 $oUser = RestUtils::FindObjectFromKey('User', $oJson->user_id);
             } catch (Exception $e) {
                 throw new Exception('user_id: ' . $e->getMessage(), $e->getCode());
             }
             $iUserId = $oUser->GetKey();
             $sOnBehalfOf = $oUser->GetFriendlyName();
         } else {
             $iUserId = $oJson->user_id;
             $sOnBehalfOf = $oJson->user_login;
         }
     } else {
         $iUserId = UserRights::GetUserId();
         $sOnBehalfOf = UserRights::GetUserFriendlyName();
     }
     if (isset($oJson->date)) {
         $oDate = new DateTime($oJson->date);
         $iDate = (int) $oDate->format('U');
     } else {
         $iDate = time();
     }
     $sDate = date(Dict::S('UI:CaseLog:DateFormat'), $iDate);
     $sSeparator = sprintf(CASELOG_SEPARATOR, $sDate, $sOnBehalfOf, $iUserId);
     $iSepLength = strlen($sSeparator);
     $iTextlength = strlen($sText);
     $this->m_sLog = $sSeparator . $sText . $this->m_sLog;
     // Latest entry printed first
     $this->m_aIndex[] = array('user_name' => $sOnBehalfOf, 'user_id' => $iUserId, 'date' => $iDate, 'text_length' => $iTextlength, 'separator_length' => $iSepLength);
     $this->m_bModified = true;
 }
Example #18
0
 public function retrieveContacts($data)
 {
     // Get the ID of the user from the autentication data
     $userID = RestUtils::authentication();
     if (!$userID) {
         RestUtils::error(401, "Authentication Error");
     }
     $result = array();
     $sql = "SELECT n_nebulacontacts.contactUsername AS contactUsername,\n\t\t\t\t\t\tn_nebulauser.username AS username,\n\t\t\t\t\t\t n_nebulauser.status AS userStatus,\n\t\t\t\t\t\t n_groupcontact.groupID as groupID\n\t\t\t\t\t\t FROM n_nebulacontacts\n\t\t\t\t\t\tLEFT JOIN n_nebulauser\n\t\t\t\t\t\t ON n_nebulauser.id = n_nebulacontacts.contactID\n\t\t\t\t\t\t LEFT JOIN n_groupcontact\n\t\t\t\t\t\t ON n_groupcontact.userContactID = n_nebulacontacts.contactID\n\t\t\t\t\t\t WHERE n_nebulacontacts.userID = {$userID}";
     $ind = $this->nebulaDB->query($sql);
     $status = 200;
     while ($ris = mysql_fetch_assoc($ind)) {
         $result[] = $ris;
     }
     return new Response($status, $result);
 }
Example #19
0
            break;
        case "list":
        default:
            $resultatGlobal = searchPodcast(false);
            break;
    }
} catch (Exception $e) {
    // En cas d'erreur précédemment, on affiche un message et on arrête tout
    die('Erreur : ' . $e->getMessage());
}
switch ($data->getMethod()) {
    case 'get':
        RestUtils::sendResponse(200, json_encode($resultatGlobal, JSON_HEX_APOS), 'application/json');
        break;
    case 'post':
        RestUtils::sendResponse(200, json_encode($resultatGlobal, JSON_HEX_APOS), 'application/json');
        break;
    default:
        break;
}
function get_json($date)
{
    $file_day = "../../OK/" . $date . "/config.txt";
    if (file_exists($file_day)) {
        return json_decode(file_get_contents($file_day));
    } else {
        return null;
    }
}
function simplify_strings($string)
{
Example #20
0
function report($report = '')
{
    RestUtils::sendResponse(500, $report);
    exit;
}
Example #21
0
<?php

include_once './common.php';
include_once S_ROOT . './source/class_rest.php';
$rest = RestUtils::processRequest();
$request_vars = $rest->getRequestVars();
$data = $rest->getData();
$method = $rest->getMethod();
$token_id = $request_vars[0];
$query = $_SGLOBAL['db']->query('select * from ' . tname('wz_token') . ' where id="' . $token_id . '"');
$token = $_SGLOBAL['db']->fetch_array($query);
if (!$token) {
    echo 'wrong site';
    exit;
}
$_WZ = $token;
$query = $_SGLOBAL['db']->query('select * from ' . tname('wz_module') . ' where id=' . $token['mid']);
$module = $_SGLOBAL['db']->fetch_array($query);
if (!$module['id']) {
    echo 'wrong module';
    exit;
}
$query = $_SGLOBAL['db']->query('select op_uid from ' . tname('open_member_weixin') . ' where id=' . $token['op_wxid'] . ' and state=1');
$weixin = $_SGLOBAL['db']->fetch_array($query);
if (!$weixin) {
    echo 'wrong wx';
    exit;
}
//获取特定微笑微信用户的模板设置信息
$module['profile'] = $_SGLOBAL['db']->getall('select * from ' . tname('wz_module_profile') . ' where op_uid=' . $weixin['op_uid'] . ' and module_id=' . $token['mid']);
$module['module_template'] = $_SGLOBAL['db']->getone('select value from ' . tname('wz_weixin_setting') . ' where op_wxid=' . $token['op_wxid'] . ' and mid=' . $token['mid'] . ' and var="template"');
Example #22
0
                                    $from = date("Y.m.d", strtotime($params['rangeFrom']));
                                    $to = date("Y.m.d H-i-s", mktime(23, 59, 59, date("m", strtotime($params['rangeFrom'])), date("d", strtotime($params['rangeFrom'])), date("Y", strtotime($params['rangeFrom']))));
                                    //echo $to;
                                    RestUtils::sendResponse(200, json_encode(getSessionsInRange($from, $to)), 'application/json');
                                } else {
                                    RestUtils::sendResponse(400);
                                }
                            }
                        }
                    } else {
                        RestUtils::sendResponse(400);
                    }
                }
            }
        } else {
            RestUtils::sendResponse(400);
        }
        //
        break;
}
//returns 1, 0, or -1
// engaged, vacant, error
function getBogState()
{
    $query = "SELECT * FROM boglog.session WHERE end_time IS NULL ORDER BY start_time DESC LIMIT 1";
    mysql_query($query);
    return strval(mysql_affected_rows());
}
//returns success boolean
function disengage()
{
Example #23
0
            } else {
                $itemType = 'track';
            }
        }
        // Default to track search
    } else {
        $itemType = 'track';
        // Default to track search
    }
    if (!isset($_GET['limit'])) {
        $_GET['limit'] = 999;
    }
    $retour = API::search($_GET['query'], intval($_GET['id']), $itemType, $_GET['limit']);
    // $retour = 0 : no result
    // $retour = null : platform Timeout
    if ($retour === null) {
        $status = 204;
    } else {
        $status = 200;
    }
    if (isset($_GET['json_key'])) {
        $json_key = $_GET['json_key'];
    } else {
        $json_key = null;
    }
    RestUtils::sendResponse($status, $retour, "json", false, $json_key);
    // false = not api mode
} else {
    RestUtils::sendResponse(404, null, "json", false, $json_key);
    // false = not api mode
}
Example #24
0
  private static function authenticate() {
    // figure out if we need to challenge the user
    if(empty($_SERVER['PHP_AUTH_DIGEST']))
    {
      header('HTTP/1.1 401 Unauthorized');
      header('WWW-Authenticate: Digest realm="' . AUTH_REALM . '",qop="auth",nonce="' . uniqid() . '",opaque="' . md5(AUTH_REALM) . '"');

      // show the error if they hit cancel
      die(RestControllerLib::error(401, true));
    }

    // now, analayze the PHP_AUTH_DIGEST var
    if(!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || $auth_username != $data['username'])
    {
      // show the error due to bad auth
      die(RestUtils::sendResponse(401));
    }

    // so far, everything's good, let's now check the response a bit more...
    $A1 = md5($data['username'] . ':' . AUTH_REALM . ':' . $auth_pass);
    $A2 = md5($_SERVER['REQUEST_METHOD'] . ':' . $data['uri']);
    $valid_response = md5($A1 . ':' . $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $A2);

    // last check..
    if($data['response'] != $valid_response)
    {
      die(RestUtils::sendResponse(401));
    }
  }
Example #25
0
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    $report = "Error Number: {$errno}<br/>\n\tError: {$errstr}<br/>\n\tFile: {$errfile}<br/>\n\tLine: {$errline}";
    RestUtils::error(500, $report);
}
Example #26
0
                        $pNEG = $pNEG / $pTotal;
                        $pNEU = $pNEU / $pTotal;
                        $pPOS = $pPOS / $pTotal;
                    }
                    // No need to hit the DB again
                    $lab = "NEG";
                    $score = $pNEG;
                    if ($pNEU > $score) {
                        $lab = "NEU";
                        $score = $pNEU;
                    }
                    if ($pPOS > $score) {
                        $lab = "POS";
                    }
                    $probs = array('NEG' => $pNEG, 'NEU' => $pNEU, 'POS' => $pPOS);
                    $res = array('likelihood' => $probs, 'label' => $lab);
                    RestUtils::sendResponse(200, json_encode($res), 'application/json');
                } else {
                    RestUtils::sendResponse(400);
                }
                break;
            default:
                // incorrect method
                RestUtils::sendResponse(400);
        }
    } else {
        RestUtils::sendResponse(401);
    }
} else {
    RestUtils::sendResponse(401);
}
Example #27
0
 public function distanceFromContact()
 {
     $userID = RestUtils::authentication();
     if (!$userID) {
         RestUtils::error(401, "Authentication Error");
     }
     $OK = 200;
     $EMPT = 201;
     $ERRO = 500;
     $query = "SELECT distance, username\n\t\t      FROM n_usertouser INNER JOIN n_nebulauser\n\t\t      WHERE ((n_usertouser.contactID = n_nebulauser.id\n\t\t      AND ownerID = {$userID}))\n\t\t      AND distance !=0";
     $execQuery = $this->nebulaDB->query($query);
     if (mysql_num_rows($execQuery) < 0) {
         return new Response($ERROR, "Impossible to retrieve contacts distance");
     }
     if (mysql_num_rows($execQuery) == 0) {
         return new Response($EMPT, "No contacts to retrieve distance from");
     }
     $result = array();
     while ($ind = mysql_fetch_assoc($execQuery)) {
         /*	if($ind['distance']<0.010){
         		    if(!isset($result['0.010']))
         			$result['0.010'] = 0;
         		    $result['0.010'] += 1;
         		}
         		else 
         		*/
         if ($ind['distance'] < 0.02) {
             if (!isset($result['0.020'])) {
                 $result['0.020'] = 0;
             }
             $result['0.020'] += 1;
         } else {
             if ($ind['distance'] < 0.05) {
                 if (!isset($result['0.050'])) {
                     $result['0.050'] = 0;
                 }
                 $result['0.050'] += 1;
             } else {
                 if ($ind['distance'] < 0.1) {
                     if (!isset($result['0.100'])) {
                         $result['0.100'] = 0;
                     }
                     $result['0.100'] += 1;
                 } else {
                     if ($ind['distance'] < 0.25) {
                         if (!isset($result['0.250'])) {
                             $result['0.250'] = 0;
                         }
                         $result['0.250'] += 1;
                     } else {
                         if ($ind['distance'] < 0.5) {
                             if (!isset($result['0.500'])) {
                                 $result['0.500'] = 0;
                             }
                             $result['0.500'] += 1;
                         } else {
                             if ($ind['distance'] < 1) {
                                 if (!isset($result['1'])) {
                                     $result['1'] = 0;
                                 }
                                 $result['1'] += 1;
                             } else {
                                 if ($ind['distance'] < 2) {
                                     if (!isset($result['2'])) {
                                         $result['2'] = 0;
                                     }
                                     $result['2'] += 1;
                                 } else {
                                     if ($ind['distance'] < 5) {
                                         if (!isset($result['5'])) {
                                             $result['5'] = 0;
                                         }
                                         $result['5'] += 1;
                                     } else {
                                         if ($ind['distance'] < 10) {
                                             if (!isset($result['10'])) {
                                                 $result['10'] = 0;
                                             }
                                             $result['10'] += 1;
                                         } else {
                                             if ($ind['distance'] < 20) {
                                                 if (!isset($result['20'])) {
                                                     $result['20'] = 0;
                                                 }
                                                 $result['20'] += 1;
                                             } elseif ($ind['distance'] < 50) {
                                                 if (!isset($result['50'])) {
                                                     $result['50'] = 0;
                                                 }
                                                 $result['50'] += 1;
                                             } else {
                                                 if ($ind['distance'] < 100) {
                                                     if (!isset($result['100'])) {
                                                         $result['100'] = 0;
                                                     }
                                                     $result['100'] += 1;
                                                 } else {
                                                     if ($ind['distance'] < 250) {
                                                         if (!isset($result['250'])) {
                                                             $result['250'] = 0;
                                                         }
                                                         $result['250'] += 1;
                                                     } else {
                                                         if ($ind['distance'] < 500) {
                                                             if (!isset($result['500'])) {
                                                                 $result['500'] = 0;
                                                             }
                                                             $result['500'] += 1;
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return new Response($OK, $result);
 }
Example #28
0
function sendOrder($vars, $responsetype)
{
    global $db;
    $ar = json_decode($vars['Data']['Data'], true, 5);
    if (empty($ar) || !isset($ar['PONumber']) || !isset($ar['Status']) || empty($ar['Items']) && empty($ar['Units'])) {
        RestLog("16521 - Insufficient data provided for creating order \n" . print_r($vars, true) . "\n");
        RestUtils::sendResponse(400, "16521 - Insufficient data provided");
        //Internal Server Error
        return false;
    }
    //08.21.2015 ghh -  before we get started we need to see if the current dealer
    //already has a PO in the system matching what they are now sending.  If so we're
    //going to be updating it if its pending or if it hasn't been pulled by the primary
    //vendor system yet.
    $query = "select POID, Status from PurchaseOrders where PONumber='{$ar['PONumber']}' and\n\t\t\t\tDealerID={$vars['DealerID']}";
    if (!($result = $db->sql_query($query))) {
        RestLog("Error 16522 in query: {$query}\n" . $db->sql_error());
        RestUtils::sendResponse(500, "16522 - There was a problem attempting to locate the PO");
        //Internal Server Error
        return false;
    }
    //if we have no purchase order at all then we're going to be inserting a new one
    if ($db->sql_numrows($result) == 0) {
        $shiptofields = '';
        $shiptovals = '';
        if ($ar['ShipToAddress1'] != '') {
            $shiptofields = "ShipToFirstName, ShipToLastName, ShipToCompany,\n\t\t\t\t\t\t\t\tShipToAddress1, ShipToAddress2, ShipToCity, ShipToState,\n\t\t\t\t\t\t\t\tShipToZip, ShipToCountry, ShipToPhone, ShipToEmail,";
            if ($ar['ShipToFirstName'] == '') {
                $shiptovals = "'',";
            } else {
                $shiptovals = "'{$ar['ShipToFirstName']}',";
            }
            if ($ar['ShipToLastName'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToLastName']}',";
            }
            if ($ar['ShipToCompany'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToCompany']}',";
            }
            if ($ar['ShipToAddress1'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToAddress1']}',";
            }
            if ($ar['ShipToAddress2'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToAddress2']}',";
            }
            if ($ar['ShipToCity'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToCity']}',";
            }
            if ($ar['ShipToState'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToState']}',";
            }
            if ($ar['ShipToZip'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToZip']}',";
            }
            if ($ar['ShipToCountry'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToCountry']}',";
            }
            if ($ar['ShipToPhone'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToPhone']}',";
            }
            if ($ar['ShipToEmail'] == '') {
                $shiptovals .= "'',";
            } else {
                $shiptovals .= "'{$ar['ShipToEmail']}',";
            }
            if ($ar['PaymentMethod'] == '') {
                $shiptovals .= "1,";
            } else {
                $shiptovals .= "'{$ar['PaymentMethod']}',";
            }
            if ($ar['ShipMethod'] == '') {
                $shiptovals .= "1,";
            } else {
                $shiptovals .= "'{$ar['ShipMethod']}',";
            }
        }
        $query = "insert into PurchaseOrders (Status, DealerID, BSVKeyID, PONumber,\n\t\t\t\tDateCreated, {$shiptofields} LastFour,OrderType) values \n\t\t\t\t( {$ar['Status']}, {$vars['DealerID']}, {$vars['BSVKeyID']}, '{$ar['PONumber']}', now(),\n\t\t\t\t{$shiptovals} '{$ar['LastFour']}',{$ar['OrderType']} )\n\t\t\t\t";
    } else {
        //if we do have a purchase order we need to determine if its ok to update it or not
        //and return error if its not.
        $row = $db->sql_fetchrow($result);
        $poid = $row['POID'];
        //08.21.2015 ghh -  if the status is greater than 2 it means the supplier has already
        //started pulling the order and we can no longer update it.  In this case we're going
        //to die and return error
        if ($row['Status'] > 2) {
            RestLog("Purchase has already been pulled by supplier {$ar['PONumber']}\n");
            RestUtils::sendResponse(409, "Order has already been pulled by supplier");
            //Internal Server Error
            return false;
        }
        //if we reach here then it must be ok to update the purchase order data so will build the
        //query here
        $query = "update PurchaseOrders set ";
        if ($ar['ShipToAddress1'] != '') {
            if ($ar['ShipToFirstName'] != '') {
                $query1 .= "ShipToFirstName='{$ar['ShipToFirstName']}',";
            }
            if ($ar['ShipToLastName'] != '') {
                $query1 .= "ShipToLastName='{$ar['ShipToLastName']}',";
            }
            if ($ar['ShipToCompany'] != '') {
                $query1 .= "ShipToCompany='{$ar['ShipToCompany']}',";
            }
            if ($ar['ShipToAddress1'] != '') {
                $query1 .= "ShipToAddress1='{$ar['ShipToAddress1']}',";
            }
            if ($ar['ShipToAddress2'] != '') {
                $query1 .= "ShipToAddress2='{$ar['ShipToAddress2']}',";
            }
            if ($ar['ShipToCity'] != '') {
                $query1 .= "ShipToCity='{$ar['ShipToCity']}',";
            }
            if ($ar['ShipToState'] != '') {
                $query1 .= "ShipToState='{$ar['ShipToState']}',";
            }
            if ($ar['ShipToZip'] != '') {
                $query1 .= "ShipToZip='{$ar['ShipToZip']}',";
            }
            if ($ar['ShipToCountry'] != '') {
                $query1 .= "ShipToCountry='{$ar['ShipToCountry']}',";
            }
            if ($ar['ShipToPhone'] != '') {
                $query1 .= "ShipToPhone='{$ar['ShipToPhone']}',";
            }
            if ($ar['ShipToEmail'] != '') {
                $query1 .= "ShipToEmail='{$ar['ShipToEmail']}',";
            }
        }
        if ($ar['PaymentMethod'] != '') {
            $query1 .= "PaymentMethod={$ar['PaymentMethod']},";
        }
        if ($ar['LastFour'] != '') {
            $query1 .= "LastFour='{$ar['LastFour']}',";
        }
        if ($ar['ShipMethod'] != '') {
            $query1 .= "ShipMethod='{$ar['ShipMethod']}',";
        }
        //if we are actually updating the PO then we're also going ot update the
        //poreceiveddate
        if ($query1 != '') {
            $query1 .= " DateLastModified=now() ";
            $query .= "{$query1} where DealerID={$vars['DealerID']} and PONumber='{$ar['PONumber']}'";
        } else {
            $query = '';
        }
    }
    //08.21.2015 ghh -  now we execute either of the two queries above to update or insert
    //the purchase order itself.
    if ($query != '') {
        if (!($result = $db->sql_query($query))) {
            RestLog("Error 16523 in query: {$query}\n" . $db->sql_error());
            RestUtils::sendResponse(500, "16523 - There was a problem attempting to insert/update the PO");
            return false;
        }
    }
    //if we don't already have a poid then we must have done an insert so we'll grab it now
    if (!$poid > 0) {
        $poid = $db->sql_nextid($result);
    }
    ####################################################PARTS###########################################
    //now that the purchase order has been updated we'll next start taking a look
    //at the items and units arrays
    //08.21.2015 rch -  we need to loop through each item that is passed in and evaluate whether or not
    //we are inserting the po or updating the po
    $i = 0;
    foreach ($ar['Items'] as $value => $key) {
        //08.21.2015 rch -  first we need to see if the item is already on the order
        $query = "select POItemID, Quantity \n\t\t\t\t\tfrom PurchaseOrderItems\n\t\t\t\t\twhere POID='{$poid}' and ItemNumber = '{$key['ItemNumber']}'\n\t\t\t\t\tand VendorID = '{$key['VendorID']}'";
        if (!($result = $db->sql_query($query))) {
            RestLog("Error 16524 in query: {$query}\n" . $db->sql_error());
            RestUtils::sendResponse(500, "16524 - There was an error locating purchase order items");
            return false;
        }
        //08.21.2015 rch -  we want to make sure that we have a partnumber and vendorid
        //before attempting to insert.
        if ($key['ItemNumber'] != '' && $key['VendorID'] != '') {
            //08.21.2015 ghh -  before we bother inserting the item we're going to first grab some
            //details from items so we can build up our response.
            $query = "select ItemID, NLA, CloseOut, PriceCode, Category, SupersessionID, \n\t\t\t\t\tMSRP, Cost\n\t\t\t\t\tfrom\n\t\t\t\t\tItems where ItemNumber='{$key['ItemNumber']}' and VendorID={$key['VendorID']}";
            if (!($itemresult = $db->sql_query($query))) {
                RestLog("Error 16526 in query: {$query}\n" . $db->sql_error());
                RestUtils::sendResponse(500, "16526 - There was an error locating the order item");
                return false;
            }
            $itemrow = $db->sql_fetchrow($itemresult);
            if ($db->sql_numrows($itemresult) == 0) {
                RestLog("Error 16545 The ItemNumber or VendorID you sent are not valid");
                RestUtils::sendResponse(500, "16545 - The Item Number or VendorID passed are invalid");
                return false;
            }
            //now lets see if we can calculate the cost for the current dealer
            $cost = getItemCost($itemrow['ItemID'], $vars['DealerID'], $itemrow['PriceCode'], $itemrow['Cost'], $itemrow['MSRP']);
        } else {
            RestLog("{$row['PONumber']} is missing a vendor id\n");
            RestUtils::sendResponse(409, "{$key['ItemNumber']} is missing a vendor id");
            return false;
        }
        //08.21.2015 rch -  if we enter here,the partnumber does not exist on the po
        if ($db->sql_numrows($result) == 0) {
            //08.21.2015 ghh -  make sure the non required fields have a value
            if ($key['FillStatus'] == '') {
                $key['FillStatus'] = 0;
            }
            if ($key['OrderType'] == '') {
                $key['OrderType'] = 2;
            }
            $query = "insert into PurchaseOrderItems (POItemID,POID,ItemNumber,Quantity,\n\t\t\t\t\t FillStatus,ItemID,VendorID) values ( '','{$poid}','{$key['ItemNumber']}',{$key['Qty']},\n\t\t\t\t\t {$key['FillStatus']},{$itemrow['ItemID']}, {$key['VendorID']})";
        } else {
            //08.21.2015 rch -  if we enter here,the item is already in the table and just needs to be
            //updated
            $row = $db->sql_fetchrow($result);
            //08.21.2015 rch -  here we are updating the purchase order items table
            $query = "update PurchaseOrderItems set ";
            if ($key['Qty'] != '') {
                $query1 = "Quantity={$key['Qty']}";
            }
            if ($query1 != '') {
                $query .= "{$query1} where POItemID={$row['POItemID']}";
            } else {
                $query = '';
            }
        }
        //08.21.2015 rch -  now we need to execute the query
        if ($query != '') {
            if (!($result = $db->sql_query($query))) {
                RestLog("Error 16525 in query: {$query}\n" . $db->sql_error());
                RestUtils::sendResponse(500, "16525 - There was a problem attempting to insert/update the PO");
                //Internal Server Error
                return false;
            }
            //08.24.2015 ghh - update the PO with the current time for last modified date
            $query = "update PurchaseOrders set DateLastModified=now() where POID = {$poid}";
            if (!($result = $db->sql_query($query))) {
                RestLog("Error 16548 in query: {$query}\n" . $db->sql_error());
                RestUtils::sendResponse(500, "16548 - There was a problem updating the last modified date");
                //Internal Server Error
                return false;
            }
        }
        //08.21.2015 ghh -  now we need to figure out what our current inventory is
        //minus any items already on orders so that we pass back a fairly reasonable
        //backorder response
        $query = "select (ifnull(sum(p1.Quantity), 0) - ifnull(sum(p2.QtyShipped),0)) as qty  \n\t\t\t\t\tfrom PurchaseOrderItems p1 \n\t\t\t\t\tleft outer join PurchaseOrderShipped p2 on p1.POItemID=p2.POItemID \n\t\t\t\t\twhere ItemID={$itemrow['ItemID']}";
        if (!($qtyresult = $db->sql_query($query))) {
            RestLog("Error 16529 in query: {$query}\n" . $db->sql_error());
            RestUtils::sendResponse(500, "16529 - There was an error getting total on order");
            return false;
        }
        $qtyrow = $db->sql_fetchrow($qtyresult);
        $qtyonorder = $qtyrow['qty'];
        $query = "select sum( Qty ) as Qty from ItemStock where ItemID={$itemrow['ItemID']}";
        if (!($qtyresult = $db->sql_query($query))) {
            RestLog("Error 16530 in query: {$query}\n" . $db->sql_error());
            RestUtils::sendResponse(500, "16530 - There was an error getting total stock qty");
            return false;
        }
        $qtyrow = $db->sql_fetchrow($qtyresult);
        $qtyinstock = $qtyrow['Qty'];
        //08.21.2015 ghh -  now we have all of our return information and have updated or
        //inserted into the items list for the purchase order so we only need to build our
        //response now.
        $items[$i]['VendorID'] = $key['VendorID'];
        $items[$i]['ItemNumber'] = $key['ItemNumber'];
        $items[$i]['Superseded'] = $itemrow['SupersessionID'];
        $items[$i]['NLA'] = $itemrow['NLA'];
        $items[$i]['Closeout'] = $itemrow['CloseOut'];
        $items[$i]['MSRP'] = $itemrow['MSRP'];
        $items[$i]['Cost'] = $cost;
        if ($qtyinstock - $qtyonorder < 0) {
            $items[$i]['BackorderQty'] = abs($qtyinstock - $qtyonorder);
        } else {
            $items[$i]['BackorderQty'] = 0;
        }
        $i++;
    }
    $rst['PONumber'] = $ar['PONumber'];
    $rst['InternalID'] = $poid;
    $rst['DealerKey'] = $vars['DealerKey'];
    $rst['Items'] = $items;
    ########################################UNITS###################################
    //08.25.2015 ghh -  this section deals with unit purchase orders
    $i = 0;
    foreach ($ar['Units'] as $value => $key) {
        $key['ModelNumberNoFormat'] = preg_replace('/[^a-zA-Z0-9]/', '', $key['ModelNumber']);
        //strip formatting.
        //08.21.2015 rch -  first we need to see if the item is already on the order
        $query = "select POUnitID\n\t\t\t\t\tfrom PurchaseOrderUnits\n\t\t\t\t\twhere POID='{$poid}' and ModelNumber = '{$key['ModelNumber']}'\n\t\t\t\t\tand VendorID = '{$key['VendorID']}'";
        if (!($result = $db->sql_query($query))) {
            RestLog("Error 16549 in query: {$query}\n" . $db->sql_error());
            RestUtils::sendResponse(500, "16549 - There was an error locating purchase order unit");
            return false;
        }
        //08.21.2015 rch -  we want to make sure that we have a partnumber and vendorid
        //before attempting to insert.
        if ($key['ModelNumberNoFormat'] != '' && $key['VendorID'] != '') {
            if (isset($key['Year'])) {
                $year = $key['Year'];
            } else {
                $year = 0;
            }
            //08.21.2015 ghh -  before we bother inserting the item we're going to first grab some
            //details from items so we can build up our response.
            $query = "select ModelID, NLA, CloseOut, Cost, OrderCode \n\t\t\t\t\tMSRP from UnitModel \n\t\t\t\t\twhere ModelNumberNoFormat='{$key['ModelNumberNoFormat']}' and VendorID={$key['VendorID']}\n\t\t\t\t\tand Year={$year}";
            if (!($unitresult = $db->sql_query($query))) {
                RestLog("Error 16560 in query: {$query}\n" . $db->sql_error());
                RestUtils::sendResponse(500, "16560 - There was an error locating the order model");
                return false;
            }
            $unitrow = $db->sql_fetchrow($unitresult);
            if ($db->sql_numrows($unitresult) == 0) {
                RestLog("Error 16561 The Unit Model you sent is not valid");
                RestUtils::sendResponse(500, "16561 - The Model Number or VendorID passed are invalid");
                return false;
            }
            //now lets see if we can calculate the cost for the current dealer
            $cost = getUnitCost($unitrow['ModelID'], $vars['DealerID'], $unitrow['Cost']);
        } else {
            RestLog("Error 16563 {$row['PONumber']} is missing a vendor id\n");
            RestUtils::sendResponse(409, "Error 16563 {$key['ModelNumber']} is missing a vendor id");
            return false;
        }
        //08.25.2015 ghh -  if we have less line items on the PO than the qty we need then
        //we're going to insert a few more rows until they match.
        if ($db->sql_numrows($result) < $key['Qty']) {
            for ($i = 0; $i < $key['Qty'] - $db->sql_numrows($result); $i++) {
                $query = "insert into PurchaseOrderUnits (POID,ModelNumber,\n\t\t\t\t\t ModelID,OrderCode,Year, Colors, VendorID, Cost) values \n\t\t\t\t\t ( '{$poid}','{$key['ModelNumber']}',{$unitrow['ModelID']},'{$unitrow['OrderCode']}',\n\t\t\t\t\t {$year},'{$key['Colors']}', {$key['VendorID']}, '{$cost}')";
                if (!($tmpresult = $db->sql_query($query))) {
                    RestLog("Error 16564 in query: {$query}\n" . $db->sql_error());
                    RestUtils::sendResponse(500, "16564 - There was an error trying to add the unit to the order");
                    return false;
                }
            }
            //08.25.2015 ghh - update the PO with the current time for last modified date
            $query = "update PurchaseOrders set DateLastModified=now() where POID = {$poid}";
            if (!($result = $db->sql_query($query))) {
                RestLog("Error 16565 in query: {$query}\n" . $db->sql_error());
                RestUtils::sendResponse(500, "16565 - There was a problem updating the last modified date");
                //Internal Server Error
                return false;
            }
        } else {
            if ($db->sql_numrows($result) > $key['Qty']) {
                $qtytoremove = $db->sql_numrows($result) - $key['Qty'];
                $query = "select POUnitID from PurchaseOrderUnits where POID={$poid}\n\t\t\t\t\t\tand ModelID={$unitrow['ModelID']} limit {$qtytoremove}";
                if (!($tmpresult = $db->sql_query($query))) {
                    RestLog("Error 16566 in query: {$query}\n" . $db->sql_error());
                    RestUtils::sendResponse(500, "16566 - There was a problem deleting changed models");
                    //Internal Server Error
                    return false;
                }
                while ($tmprow = $db->sql_fetchrow($tmpresult)) {
                    $query = "delete from PurchaseOrderUnits where POUnitID={$tmprow['POUnitID']}";
                    if (!($tmp2result = $db->sql_query($query))) {
                        RestLog("Error 16567 in query: {$query}\n" . $db->sql_error());
                        RestUtils::sendResponse(500, "16567 - There was a problem deleting changed models");
                        //Internal Server Error
                        return false;
                    }
                }
                //08.25.2015 ghh - update the PO with the current time for last modified date
                $query = "update PurchaseOrders set DateLastModified=now() where POID = {$poid}";
                if (!($result = $db->sql_query($query))) {
                    RestLog("Error 16568 in query: {$query}\n" . $db->sql_error());
                    RestUtils::sendResponse(500, "16568 - There was a problem updating the last modified date");
                    //Internal Server Error
                    return false;
                }
            }
        }
        //08.25.2015 ghh -  first lets grab total qty for the current model
        $query = "select sum(Qty) as Qty from UnitModelStock where ModelID={$unitrow['ModelID']}";
        if (!($qtyresult = $db->sql_query($query))) {
            RestLog("Error 16570 in query: {$query}\n" . $db->sql_error());
            RestUtils::sendResponse(500, "16570 - There was an error getting total instock");
            return false;
        }
        $tmprow = $db->sql_fetchrow($qtyresult);
        $stockqty = $tmprow['Qty'];
        $query = "select count(POUnitID) as Qty from PurchaseOrderUnits \n\t\t\t\twhere ModelID={$unitrow['ModelID']} and SerialVin is null";
        if (!($qtyresult = $db->sql_query($query))) {
            RestLog("Error 16571 in query: {$query}\n" . $db->sql_error());
            RestUtils::sendResponse(500, "16571 - There was an error getting total instock");
            return false;
        }
        $tmprow = $db->sql_fetchrow($qtyresult);
        $orderqty = $tmprow['Qty'];
        //08.21.2015 ghh -  now we have all of our return information and have updated or
        //inserted into the items list for the purchase order so we only need to build our
        //response now.
        $units[$i]['VendorID'] = $key['VendorID'];
        $units[$i]['ModelNumber'] = $key['ModelNumber'];
        $units[$i]['NLA'] = $unitrow['NLA'];
        $units[$i]['Closeout'] = $unitrow['CloseOut'];
        $units[$i]['MSRP'] = $unitrow['MSRP'];
        $units[$i]['Cost'] = $cost;
        if ($stockqty - $onorderqty < 0) {
            $units[$i]['BackorderQty'] = abs($stockqty - $onorderqty);
        } else {
            $units[$i]['BackorderQty'] = 0;
        }
        $i++;
    }
    $rst['Units'] = $units;
    RestLog("Successful Request\n");
    //08.10.2012 naj - return code 200 OK.
    RestUtils::sendResponse(200, json_encode(stripHTML($rst)));
    return true;
}
Example #29
0
 public static function error($status = '500', $body = '')
 {
     //DEBUG Mode
     RestUtils::sendResponse($status, $body, $type = 'text/html');
     //Production Mode
     //RestUtils::sendResponse(500);
     exit;
 }
Example #30
0
<?php
include 'tagger/conf.php';
include 'rest/RestUtils.inc.php';
include 'access/iplog.php';

$controller = RestUtils::processRequest();

?>