--- /dev/null
+**openSRF**
+==================================
+openSRF is a message passing architecture. We have many message passing systems today. While browsing a bit over the internet I came across some, a few listed here *http://en.wikipedia.org/wiki/Message_passing#Message_passing_systems*. So why do we have this new message passing thing? It is basically to interact with **Evergreen, an open source Integrated Library System (ILS)**.
+
+While a complete guide to openSRF can be found at *http://journal.code4lib.org/articles/3284*, here is a quick intro to openSRF.
+>The Open Service Request Framework (or OpenSRF, pronounced “open surf”) is an inter-application message passing architecture built on XMPP (aka “jabber”). The Evergreen open source library system is built on an OpenSRF architecture to support loosely coupled individual components communicating over an OpenSRF messaging bus. This article introduces OpenSRF, demonstrates how to build OpenSRF services through simple code examples, explains the technical foundations on which OpenSRF is built, and evaluates OpenSRF’s value in the context of Evergreen. Part 1 of a 2 part article in this issue.
+
+ By Dan Scott
+
+
+Imagine an application architecture in which 10 lines of Perl or Python, using the data types native to each language, are enough to implement a method that can then be deployed and invoked seamlessly across hundreds of servers. You have just imagined developing with OpenSRF – it is truly that simple. Under the covers, of course, the OpenSRF language bindings do an incredible amount of work on behalf of the developer. An OpenSRF application consists of one or more OpenSRF services that expose methods: for example, the opensrf.simple-text demonstration service exposes the opensrf.simple-text.split() and opensrf.simple-text.reverse() methods. Each method accepts zero or more arguments and returns zero or one results. The data types supported by OpenSRF arguments and results are typical core language data types: strings, numbers, booleans, arrays, and hashes.
+
+*(source : http://docs.evergreen-ils.org/1.6/draft/html/writing_an_opensrf_service.html)*
+
+
+Introduction
+-------------
+*(extracted from **http://journal.code4lib.org/articles/3284**)*
+
+OpenSRF is a message routing network that offers scalability and failover support for individual services and entire servers with minimal development and deployment overhead. You can use OpenSRF to build loosely-coupled applications that can be deployed on a single server or on clusters of geographically distributed servers using the same code and minimal configuration changes. Although copyright statements on some of the OpenSRF code date back to Mike Rylander’s original explorations in 2000, Evergreen was the first major application to be developed with, and to take full advantage of, the OpenSRF architecture starting in 2004. The first official release of OpenSRF was 0.1 in February 2005 (http://evergreen-ils.org/blog/?p=21), but OpenSRF’s development continues a steady pace of enhancement and refinement, with the release of 1.0.0 in October 2008 and the most recent release of 1.2.2 in February 2010.
+
+OpenSRF is a distinct break from the architectural approach used by previous library systems and has more in common with modern Web applications. The traditional “scale-up” approach to serve more transactions is to purchase a server with more CPUs and more RAM, possibly splitting the load between a Web server, a database server, and a business logic server. Evergreen, however, is built on the Open Service Request Framework (OpenSRF) architecture, which firmly embraces the “scale-out” approach of spreading transaction load over cheap commodity servers. The initial GPLS PINES hardware cluster, while certainly impressive, may have offered the misleading impression that Evergreen requires a lot of hardware to run. However, Evergreen and OpenSRF easily scale down to a single server; many Evergreen libraries run their entire library system on a single server, and most OpenSRF and Evergreen development occurs on a virtual machine running on a single laptop or desktop image.
+
+Library
+-------
+
+The working of this library is explained in *pranjal710/osrf/docs/* directory
+
+Testing
+--------
+
+There are test servers freely available, which can be used to test the code. Test servers can be found at *http://open-ils.org/dokuwiki/doku.php?id=community_servers*
+
+If you still have any questions or doubts, you are free to talk to **Evergreen, an open source Integrated Library System (ILS)** ( *IRC: #evergreen channel on the Freenode server* HomePage: *http://evergreen-ils.org/* )
\ No newline at end of file
--- /dev/null
+**OpenSRF-PHP**
+===============
+
+The PHP Binding for openSRF takes services, methods and data(also as parameter) to return a simple parsed output. The examples/ directory shows how to use the API.
+
+*In Lebbeous Fogle-Weekley's words:*
+>These PHP bindings for the OpenSRF library allow you to make requests and receive responses from OpenSRF services, such as those that comprise the Evegreen Integrated Library System (ILS).
+>
+>Examples of how to use the bindings to contact typical services for Evergreen are under the examples/ directory.
+>
+>Setting up an OpenSRF session will retrieve the fm_IDL.xml file from the targeted server, which provides that server's Interface Description Language. This essentially means class definitions that allow certain data structures to be interpreted as objects in the Object-oriented sense.
+
+
+**Requirements:** *PHP version > 5 and HTTP_Request2*
+
+
+
+**Files**
+
+**config.php**
+
+This is the main configuration page. It holds the Golbal Variable which define the full path to classfieldmapper file.
+
+
+
+**methods.php**
+
+
+*function decodeFromOpenSRF($data)*
+
+Recursively turns an already decoded json object *i.e.* The parameter $data to fieldmapper object
+
+
+*function Parse_HTTP_response($string)*
+
+$string is a string which holds the HTTP response. The function returns an array, which is the parsed HTTP response.
+
+
+*function Stdclass_To_array($ar)*
+
+This takes one parameter *i.e.* $ar. $ar can be an array or an object. It returns an array by converting the object to an associative array.
+
+
+**Fieldmapper.php**
+
+*abstract class Fieldmapper_Class*
+
+Create/overwrites a dynamic file *i.e.* Classfieldmapper.php from parsed data obtained from fm_IDL (http://hostname/reports/fm_IDL.xml). Its member functions are getter, setter and encodeforopensrf().
+
+
+*Fieldmapper_Class::function encodeForOpenSRF()*
+
+It recursively encodes an object to be send to opensrf.
+
+
+*function objectsIntoArray($arrObjData, $arrSkipIndices = array())*
+
+It takes two parameters, one as an array object and the other parameter tells which index to miss. It is a generic function to parse an xml into an array
+
+
+**FieldmapperClassAbstract.php**
+
+It is an abstract class which holds the methods that is used by the numerous class of classfieldmapper.php
+
+
+**OpenIlsSimpleRequest.php**
+
+*function Open_Ils_Simple_request($arr, $m, $s, $server)*
+
+This is one of the most important function. It takes three parameters (method, service, and an array) as parameters. The array contains data to form the HTTP header. It returns a parsed response.
+
+
+**OsrfMessage.php**
+
+This class is used in sending and retrieving messages to openSRF service. Its member functions are:
+constructor, getguid(), setguid(), toarray(),header(), send(),
+
+
+**OsrfResponse.php**
+
+This class helps to parse the HTTP response. Each instance of this class holda a HTTP respomse in its 'data' property.
+
+
+**OsrfSession.php**
+
+This is that class, whose instance is used by the examples file, and it calls other functions.
+
+
+
+**A brief overview of the functioning of openSRF-PHP API**
+============================================================
+
+*Open_Ils_Simple_request()* present in *OpenIlsSimpleRequest.php* mainly manages the process. it creates an instance of *osrfMessage Class* and then parses it through another instance of *osrfResponse Class* and its member functions.
+
+An instance of *Class osrfMessage* is used to interact with openSRF service. method, service, endpoint and param are set by the *constructor*. *setGuid()* sets the guid so that an HTTP header can be formed, and it can also help in creating a stateful session when required. With the information gathered a HTTP header is created by *function header()*. *Function toArray()* creates $data which will be used by the HTTP_REQUEST2 class. *function send()* uses HTTP_REQUEST2 to interact with openSRF. If successfull, it returns a response.
+
+HTTP response has to be parsed to get the desired result. The result is a json encoded string. For this purpose *Class osrfResponse* is present. *Function send()* initializes $data property of an instance of *Class osrfMessage*. The *function parse()* is then used to parse the generic HTTP response to get the desired output and returns it.
+
+*Open_Ils_Simple_request()* thus gets the parsed result. This functions takes four parameters which are an array, service, method and a server. The array contains the data to form the HTTP header. Depending upon the service, method and the array it gets the response. Other functions use *Open_Ils_Simple_request()* to get result *eg. function Open_Ils_login()* uses it to get an authtoken on successfull login, else it throws an exception.
+
+When multiple user use it, in other words, in case of multiple session, each of these classes and functions should have multiple instances running. To make that happen we have a topmost class: *Class osrfSession*. The example scripts diectly use *Class osrfSession* instances. The constructor sets the server and fm_IDL. Its member functions do as they are named. *function login()* checks username/password for their authenticity. *function loadFieldmapper()* returns the path to *Class classfieldmapper*, which is defined in Config.php. *function checkhost()* checks whether hostname entered is true or not and *function request()* deals with *Class osrfMessage*.
+
+The user can use all these files by just including *osrfSession.php*, as it has all other files included. He first creates an instance of *Class osrfSession* and sets hostname, which also sets fm_IDL for different servers. Now he needs to load *Class classfieldmapper* so that he can use numerous the classes present in it. Depending upon whether to used a cached file or to create a new one he sets true or false resp. . Now he has all the required files and functions to go on. He can use an instance of any class(es) from classfieldmapper.php and use *Class osrfSession* member functions to interact with openSRF services.
\ No newline at end of file
--- /dev/null
+<?php
+include ("./../../lib/OsrfSession.php");
+
+/* print_names()
+ *
+ * A simple function to print only the name field in a tree of objects
+ * where child nodes are stored in an array in the "children" field.
+ */
+function print_names($node, $depth = 0) {
+ echo str_repeat(" ", $depth) . $node->name . "\n";
+ foreach ($node->children as $child) {
+ print_names($child, $depth + 1);
+ }
+}
+
+$ses = new osrfSession("hostname"); // e.g.: localhost remembers server & loads fieldmapper.
+if ($ses->checkhost() == 200) {
+
+ try {
+ $ses->loadFieldmapper(false); //FALSE to parse fieldmapper anew and create classes no matter what. TRUE to rely on cached fieldmapper classes if found.
+ } catch (Exception $e_load_idl) {
+ echo 'Error: ', $e_load_idl->getMessage() , "\n";
+ }
+ $result = $ses->request("open-ils.actor", "open-ils.actor.org_tree.retrieve", 1)->parse();
+ if ($result) {
+ if (Is_Open_Ils_event($result)) {
+ echo "Could not place hold because of error: " . $result["desc"];
+ }
+ else {
+ echo "<pre>";
+
+ /* This would print a tree of aou objects. */
+ //print_r($result);
+
+ /* This will print only the name field of each aou object */
+ print_names($result);
+
+ echo "</pre>";
+ }
+ }
+ else echo "Errors were encountered.";
+}
+else echo "Could not locate fieldmapper. Invalid hostname!";
+?>
+
--- /dev/null
+<?php
+include ("./../../lib/OsrfSession.php");
+
+$ses = new osrfSession("localhost"); // e.g.: localhost remembers server & loads fieldmapper.
+if ($ses->checkhost() == 200) {
+
+ try {
+ $ses->loadFieldmapper(false); //FALSE to parse fieldmapper and create new fieldmapper class, TRUE for all other cases.
+ } catch (Exception $e_load_idl) {
+ echo 'Error: ', $e_load_idl->getMessage() , "\n";
+ }
+
+ $authtoken = $ses->login('username', 'password'); //// Authentication token
+
+ $hold = new ahr();
+ $hold->target = 3;
+ $hold->hold_type = "T";
+ $hold->pickup_lib = 4;
+ $hold->request_lib = 4;
+ $hold->requestor = 1;
+ $hold->usr = 1;
+
+ $result = $ses->request("open-ils.circ", "open-ils.circ.holds.create", $authtoken, $hold)->parse();
+ if ($result) {
+ /* Upon failure, result can be one OpenILS::Event object (represented
+ * an an associative array here) *or* an array of them. */
+ if (is_array($result)) {
+ if ($result[0]) {
+ foreach ($result as $r) {
+ echo "Could not place hold because of error: " . $r["desc"];
+ }
+ } else {
+ echo "Could not place hold because of error: " . $result["desc"];
+ }
+ }
+ /* Upon success, the result is a simple integer. */
+ else echo "Placed hold successfully. ID is $result.";
+ }
+ else echo "Errors were encountered.";
+}
+else echo "Could not locate fieldmapper. Invalid hostname!";
+?>
--- /dev/null
+<?php
+/**
+* opensrf-php
+*
+* PHP version 5
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+/**
+* Configuration file
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+*/
+define('PATH_TO_FIELDMAPPER', "/tmp/");
+define('PATH_TO_OSRF_PHP_LIB', "/path/to/osrf/lib/");
+?>
--- /dev/null
+<?php
+/**
+* opensrf-php
+*
+* PHP version 5
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+/**
+* Fieldmapper
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+*/
+
+/**
+* objectsIntoArray
+*
+* @param array $arrObjData array index
+*
+* @param array $arrSkipIndices array index to skip
+*
+* @return string
+*/
+function objectsIntoArray($arrObjData, $arrSkipIndices = array())
+{
+ $arrData = array();
+ if (is_object($arrObjData)) {
+ $arrObjData = get_object_vars($arrObjData);
+ }
+ if (is_array($arrObjData)) {
+ foreach ($arrObjData as $index => $value) {
+ if (is_object($value) || is_array($value)) {
+ $value = objectsIntoArray($value, $arrSkipIndices);
+ }
+ if (in_array($index, $arrSkipIndices)) {
+ continue;
+ }
+ $arrData[$index] = $value;
+ }
+ }
+ return $arrData;
+}
+
+$xmlUrl = $this->fm_IDL;
+$xmlStr = file_get_contents($xmlUrl);
+$xmlObj = simplexml_load_string($xmlStr);
+$arrXml = objectsIntoArray($xmlObj);
+$class = array();
+$field = array();
+for ($i= 0 ; $arrXml['class'][$i]['@attributes']['id'] != null ; $i++) {
+ $class[] = $arrXml['class'][$i]['@attributes']['id'];
+ $class_id = $arrXml['class'][$i]['@attributes']['id'];
+ $inner = null;
+ $field[$class_id] = array();
+ for (
+ $j= 0 ;
+ $arrXml['class'][$i]['fields']['field'][$j]['@attributes']['name'] != null ;
+ $j++
+ ) {
+ $field[$class_id][]
+ = $arrXml['class'][$i]['fields']['field'][$j]['@attributes']['name'];
+ }
+}
+/**
+* Fieldmapper
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+*/
+$myFile = PATH_TO_FIELDMAPPER."classfieldmapper-".$this->server.".php";
+$fh = fopen($myFile, 'w') or die("can't open file");
+$stringData = "<?php \n \n";
+fwrite($fh, $stringData);
+$stringData = "include (\"".
+PATH_TO_OSRF_PHP_LIB."FieldmapperClassAbstract.php\"); \n ";
+fwrite($fh, $stringData);
+for ($i=0 ; $class[$i] != null ; $i++) {
+ $id = null;
+ $stringData = "Class ".$class[$i]." extends
+ Fieldmapper_Class{\nprotected \$_properties = array(";
+ $id = $class[$i];
+ $data = null;
+ fwrite($fh, $stringData);
+ for ($j=0 ; $field[$id][$j] != null ; $j++) {
+ $data = $data.'"'.$j.'" => \''.$field[$id][$j].'\', ';
+ }
+ $stringData = substr($data, 0, -2);
+ fwrite($fh, $stringData);
+ $stringData = "); \n} \n \n";
+ fwrite($fh, $stringData);
+}
+$stringData = "?>";
+fwrite($fh, $stringData);
+fclose($fh);
+?>
--- /dev/null
+<?php
+/**
+* opensrf-php
+*
+* PHP version 5
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+/**
+* Fieldmapper_abstract_class
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+abstract class Fieldmapper_Class
+{
+ private $_values = array();
+ /**
+ * Setter Function
+ *
+ * @param string $field Array key from classfieldapper
+ *
+ * @param string $value The value to assign
+ *
+ * @return void
+ */
+ function __set($field, $value)
+ {
+ $flag = 1;
+ for ($x = 0 ; $this->_properties[$x] != null ; $x++) {
+ if ($this->_properties[$x] == $field) {
+ $this->_values[$field] = $value;
+ $flag = 2;
+ }
+ }
+ if ($flag == 1) {
+ throw new Exception(
+ 'fieldmapper class '.
+ get_called_class().' has no '.$field.' .
+ Invalid Field Parameter'
+ );
+ }
+ }
+
+ /**
+ * Getter Function
+ *
+ * @param string $field Array key from classfieldapper
+ *
+ * @return string
+ */
+ function __get($field)
+ {
+ if ($field == "_properties") {
+ return $this->$field;
+ } elseif (array_key_exists($field, $this->_values)) {
+ if (isset($this->_values[$field])) {
+ return $this->_values[$field];
+ } else {
+ return null;
+ }
+ } else {
+ throw new Exception(
+ 'fieldmapper class '.
+ get_called_class()
+ .' has no '.$field.' . Invalid Field Parameter'
+ );
+ }
+ }
+
+ /**
+ * encode for opensrf
+ *
+ * @return array
+ */
+ function encodeForOpenSRF()
+ {
+ $t = array();
+ $t['__c'] = get_called_class();
+ $t['__p'] = array();
+ for ($count = 0 ; $count < (count($this->_properties)) ; $count++) {
+ $key = $this->_properties[$count];
+ if (is_object($this->_values[$key])) {
+ $t['__p'][] = $this->_values[$key]->encodeForOpenSRF();
+ } else {
+ $t['__p'][] = $this->_values[$key];
+ }
+ }
+ return $t;
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+* opensrf-php
+*
+* PHP version 5
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+/**
+* Open_ils_simple_request
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+*/
+require 'OsrfMessage.php';
+require 'OsrfResponse.php';
+/**
+* Open_Ils_Simple_request
+*
+* @param array $arr parameters to pass to the method in an array
+*
+* @param string $m method name
+*
+* @param string $s service name
+*
+* @param string $server evergreen host
+*
+* @return string
+*/
+function Open_Ils_Simple_request($arr, $m, $s, $server)
+{
+ $endpoint = $server;
+ if ($endpoint) {
+ $a = new OsrfMessage($m, $s, $arr, $endpoint);
+ } else {
+ $a = new OsrfMessage($m, $s, $arr);
+ }
+ $response = $a->send();
+ if ($response) {
+ return $response->parse();
+ } else {
+ throw new Exception('Service Unavailable');
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+* opensrf-php
+*
+* PHP version 5
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+
+/**
+* OsrfMessage
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+class OsrfMessage
+{
+ public $ch;
+ public $guid;
+ public $method;
+ public $param = array();
+ public $to;
+ public $data;
+ public $header;
+ public $service;
+ public $curl;
+ public $server_result;
+ public $endpoint;
+ /**
+ * constructor
+ *
+ * @param string $x method name
+ *
+ * @param string $z service name
+ *
+ * @param string $y parameter
+ *
+ * @param string $u endpoint
+ *
+ * @return string
+ */
+ function __construct($x, $z, $y, $u="opensrf")
+ {
+ if (is_string($x)) {
+ $this->method = $x;
+ } elseif (is_object($x)) {
+ $this->method = $x;
+ }
+ if (is_string($z)) {
+ $this->service = $z;
+ } elseif (is_object($z)) {
+ $this->service = $z;
+ }
+ $this->param = $y;
+ $this->endpoint = $u;
+ }
+ /**
+ * setter
+ *
+ * @return void
+ */
+ function setGuid()
+ {
+ if (function_exists('com_create_guid')) {
+ return com_create_guid();
+ } else {
+ mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
+ $charid = strtoupper(md5(uniqid(rand(), true)));
+ $hyphen = chr(45);// "-"
+ $uuid = chr(123)// "{"
+ .substr($charid, 0, 8).$hyphen
+ .substr($charid, 8, 4).$hyphen
+ .substr($charid, 12, 4).$hyphen
+ .substr($charid, 16, 4).$hyphen
+ .substr($charid, 20, 12)
+ .chr(125);// "}"
+
+ }
+ $this->guid = $uuid;
+ }
+ /**
+ * getter
+ *
+ * @return int
+ */
+ function getGuid()
+ {
+ return $this->guid;
+ }
+ /**
+ * header
+ *
+ * @return string
+ */
+ function header()
+ {
+ $this->setGuid();
+ $this->header = array($this->service,
+ time(), $this->getGuid());
+ return $this->header;
+ }
+
+
+ /**
+ * toArray
+ *
+ * @param string $data json_encoded string
+ *
+ * @return string
+ */
+ function toArray($data)
+ {
+ return "osrf-msg=" . urlencode($data);
+ }
+ /**
+ * Creates object to send
+ *
+ * @param string $method The method
+ *
+ * @param array $ar Data
+ *
+ * @return string
+ */
+ function urldata($method, $ar)
+ {
+ $myobject3 = new stdClass;
+ $myobject3->method = $method;
+ $myobject3->params = $ar;
+ $myobject2 = new stdClass;
+ $myobject2->__c = 'osrfMethod';
+ $myobject2->__p = $myobject3;
+ $myobject0 = new stdClass;
+ $myobject0->threadTrace = 0;
+ $myobject0->type = 'REQUEST';
+ $myobject0->payload = $myobject2;
+ $myobject0->locale = 'en-US';
+ $myobject = new stdClass;
+ $myobject->__c = 'osrfMessage';
+ $myobject->__p = $myobject0;
+ $d = array($myobject);
+ return json_encode($d);
+ }
+ /**
+ * send
+ *
+ * @return string
+ */
+ function send()
+ {
+ include_once 'HTTP/Request2.php';
+ $endpoint = $this->endpoint;
+ $data = $this->urldata($this->method, $this->param);
+ $header = $this->header();
+ $url_post = 'http://'.$endpoint.'/osrf-http-translator';
+ $request = new HTTP_Request2();
+ $request->setUrl($url_post);
+ $request->setHeader(
+ array(
+ 'X-OpenSRF-service' => $header[0],
+ 'X-OpenSRF-xid' => $header[1],
+ 'X-OpenSRF-thread' => $header[2])
+ );
+ $request->setMethod(HTTP_Request2::METHOD_POST);
+ $request->addPostParameter("osrf-msg", $data);
+ $response = $request->send();
+ $responseBody = $response->getBody();
+ $responseHeader=$response->getHeader();
+ $returnResponse = $responseBody."\n";
+ foreach ($responseHeader as $key => $value) {
+ $returnResponse = $returnResponse.ucfirst($key).": $value\n";
+ }
+ $res = new OsrfResponse($returnResponse);
+ return $res;
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+* opensrf-php
+*
+* PHP version 5
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+/**
+* OsrfResponse
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+class OsrfResponse
+{
+ public $data;
+ public $result;
+ /**
+ * constructor
+ *
+ * @param string $dta data
+ *
+ * @return void
+ */
+ function __construct($dta)
+ {
+ $this->data = $dta;
+ }
+ /**
+ * parse
+ *
+ * @return object Result
+ */
+ function parse()
+ {
+ $first = Parse_Http_response($this->data);
+ $result = '[{"__c":'.$first[0]['[{"__c"'];
+ $result_list = array();
+ if ($result) {
+ $messages = Stdclass_to_array(json_decode($result));
+ foreach ($messages as $msg) {
+ if ($msg["__p"]["type"] == "RESULT") {
+ $result_list[] = decodeFromOpenSRF(
+ $msg["__p"]["payload"]["__p"]["content"]
+ );
+ }
+ }
+
+ if (count($result_list) == 1) {
+ return $result_list[0];
+ } else {
+ return $result_list;
+ }
+ } else {
+ print_r($this->data);
+ throw new Exception("did not get osrfMessage from network");
+ }
+
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+* opensrf-php
+*
+* PHP version 5
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+require 'Config.php';
+require_once 'OpenIlsSimpleRequest.php';
+require_once 'methods.php';
+require_once 'OsrfMessage.php';
+//require 'OpenIlsLogin.php';
+/**
+* OsrfSession
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+class OsrfSession
+{
+ public $server;
+ public $fm_IDL;
+ /**
+ * constructor
+ *
+ * @param string $u hostname
+ *
+ * @return void
+ */
+ function __construct($u="localhost")
+ {
+ $this->server = $u;
+ $this->fm_IDL = "http://".$u."/reports/fm_IDL.xml";
+ }
+ /**
+ * constructor
+ *
+ * @param string $user username
+ *
+ * @param string $pass password
+ *
+ * @return string
+ */
+ function login($user, $pass)
+ {
+ try {
+ $arr = array($username);
+ $m = 'open-ils.auth.authenticate.init';
+ $s = 'open-ils.auth';
+ try {
+ $seed = Open_Ils_Simple_request($arr, $m, $s, $server);
+ } catch (Exception $e0) {
+ echo 'Error: ', $e0->getMessage(), "\n";
+ }
+ $password = md5($seed . md5($password));
+ $arr = array(
+ "username"=>$username,
+ "password"=>$password,
+ "type"=>"opac"
+ );
+ try {
+ $response1 = Open_Ils_Simple_request(
+ array($arr),
+ $m = 'open-ils.auth.authenticate.complete',
+ $s = 'open-ils.auth',
+ $server
+ );
+ } catch (Exception $e1) {
+ echo 'Error: ', $e1->getMessage(), "\n";
+ }
+
+ $login_response = $response1;
+ if ($login_response['ilsevent']=='0') {
+ $value = $login_response['payload']['authtoken'];
+ } else {
+ throw new Exception('Login Error');
+ }
+
+ } catch (Exception $e) {
+ echo 'Error: ', $e->getMessage(), "<br />";
+ }
+ return $value;
+ }
+ /**
+ * loadFieldmapper
+ *
+ * @param string $option bool
+ *
+ * @return void
+ */
+ function loadFieldmapper($option)
+ {
+ if ($option == false) {
+ include "Fieldmapper.php";
+ }
+ if (!(file_exists(
+ PATH_TO_FIELDMAPPER."classfieldmapper-".$this->server.".php"
+ ))) {
+ throw new Exception(
+ 'Could not locate ClassFieldmapper as described in config.php.'
+ );
+ } else {
+ return include PATH_TO_FIELDMAPPER."classfieldmapper-"
+ .$this->server.".php";
+ }
+ }
+ /**
+ * checkhost
+ *
+ * @return int
+ */
+ function checkhost()
+ {
+ include_once 'HTTP/Request2.php';
+ $request = new HTTP_Request2($this->fm_IDL, HTTP_Request2::METHOD_GET);
+ $response = $request->send();
+ $retcode = $response->getStatus();
+ /** $retcode = 400 -> not found, $retcode = 200, found. **/
+ return $retcode;
+ }
+ /**
+ * request
+ *
+ * @return object
+ */
+ function request()
+ {
+ $service = func_get_arg(0);
+ $method = func_get_arg(1);
+ $arr = array();
+ $k = 2;
+ while (func_get_arg($k) !== false) {
+ $add = func_get_arg($k);
+ if (is_object($add)) {
+ $add = $add->encodeForOpenSRF();
+ }
+ $arr[] = $add;
+ $k++;
+ }
+ $msg = new OsrfMessage($method, $service, $arr, $this->server);
+ return $msg->send();
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+* opensrf-php
+*
+* PHP version 5
+*
+* @category PHP
+* @package Opensrf-php
+* @author Pranjal Prabhash <pranjal.prabhash@gmail.com>
+* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public License
+* @link https://www.github.com/pranjal710/
+*/
+/**
+* is_open_ils_event
+*
+* @param array $o response array
+*
+* @return bool
+*/
+function Is_Open_Ils_event($o)
+{
+ return is_array($o) && array_key_exists("ilsevent", $o);
+}
+/**
+* Given a data structure from OpenSRF, already json decoded, turn any
+* array structures like array('__c' => 'foo', '__p' => array(abc,123,...))
+* into fieldmapper objects.
+*
+* @param string $data A data structure
+*
+* @return object
+*/
+
+function decodeFromOpenSRF($data)
+{
+ if (!is_array($data)) {
+ return $data;
+ } else if (!isset($data['__c']) || !class_exists($data['__c'])) {
+ return array_map('decodeFromOpenSRF', $data);
+ }
+
+ $class = $data['__c'];
+ $new = new $class();
+ foreach ($data['__p'] as $i => $value) {
+ $field = $new->_properties[$i];
+ if (!$field) {
+ continue;
+ }
+ if (is_array($value)) {
+ $new->$field = decodeFromOpenSRF($value);
+ } else {
+ $new->$field = $value;
+ }
+ }
+ return $new;
+}
+/**
+* Parse a http response
+*
+* @param string $string HTTP Response string
+*
+* @return array
+*/
+function Parse_Http_response($string)
+{
+ $headers = array();
+ $content = '';
+ $str = strtok($string, "\n");
+ $h = null;
+ while ($str !== false) {
+ if ($h and trim($str) === '') {
+ $h = false;
+ continue;
+ }
+ if ($h !== false and false !== strpos($str, ':')) {
+ $h = true;
+ list($headername, $headervalue) = explode(':', trim($str), 2);
+ $headername = strtolower($headername);
+ $headervalue = ltrim($headervalue);
+ if (isset($headers[$headername])) {
+ $headers[$headername] .= ',' . $headervalue;
+ } else {
+ $headers[$headername] = $headervalue;
+ }
+ }
+ if ($h === false) {
+ $content .= $str."\n";
+ }
+ $str = strtok("\n");
+ }
+ return array($headers, trim($content));
+}
+/**
+* Stdclass_To_array
+*
+* @param array $ar array to convert to object
+*
+* @return array
+*/
+function Stdclass_To_array($ar)
+{
+ if (is_object($ar)) {
+ $ar = get_object_vars($ar);
+ }
+ if (is_array($ar)) {
+ return array_map(__FUNCTION__, $ar);
+ } else {
+ return $ar;
+ }
+}
+?>
\ No newline at end of file