PageRenderTime 68ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/index.php

https://github.com/deefactorial/openmoney-server
PHP | 859 lines | 560 code | 203 blank | 96 comment | 151 complexity | 92d359c86fcd5eba2708f87d5dde7838 MD5 | raw file
Possible License(s): Apache-2.0
  1. <?php
  2. require 'vendor/autoload.php';
  3. use GuzzleHttp\Exception\ClientException;
  4. // Guzzle Docs
  5. /*
  6. * $client = new GuzzleHttp\Client();
  7. * $response = $client->get('http://guzzlephp.org');
  8. * $res = $client->get('https://api.github.com/user', ['auth' => ['user', 'pass']]);
  9. * echo $res->getStatusCode();
  10. * // "200"
  11. * echo $res->getHeader('content-type');
  12. * // 'application/json; charset=utf8'
  13. * echo $res->getBody();
  14. * // {"type":"User"...'
  15. * var_export($res->json());
  16. * // Outputs the JSON decoded data
  17. *
  18. * // Send an asynchronous request.
  19. * $req = $client->createRequest('GET', 'http://httpbin.org', ['future' => true]);
  20. * $client->send($req)->then(function ($response) {
  21. * echo 'I completed! ' . $response;
  22. * });
  23. */
  24. function get_http_response_code($url) {
  25. $headers = get_headers($url);
  26. return substr($headers[0], 9, 3);
  27. }
  28. // global functions
  29. // https://stackoverflow.com/questions/4757392/php-fast-random-string-function
  30. function randomString($length = 10) {
  31. return bin2hex(openssl_random_pseudo_bytes($length / 2));
  32. }
  33. function ajax_put($doc_id, $document) {
  34. $url = "https://cloud.openmoney.cc:4985/openmoney_shadow/" . urlencode($doc_id);
  35. $client = new GuzzleHttp\Client();
  36. $request_options = array("json" => json_decode($document, true));
  37. try {
  38. $response = $client->put($url, $request_options);
  39. } catch (ClientException $e) {
  40. $response = $e->getResponse();
  41. }
  42. $response_code = $response->getStatusCode();
  43. if ($response_code == 200 || $response_code == 204 || $response_code == 201) {
  44. return $response->json();
  45. } else {
  46. return json_decode("{}", true);
  47. }
  48. }
  49. function ajax_get($doc_id) {
  50. $url = "https://cloud.openmoney.cc:4985/openmoney_shadow/" . urlencode($doc_id);
  51. $client = new GuzzleHttp\Client();
  52. try {
  53. $response = $client->get($url);
  54. } catch (ClientException $e) {
  55. $response = $e->getResponse();
  56. }
  57. $response_code = $response->getStatusCode();
  58. if ($response_code == 200) {
  59. return $response->getBody();
  60. } else {
  61. return "{}";
  62. }
  63. }
  64. function ajax_getView($design_doc, $view, $options, $errors = false) {
  65. $url = "https://cloud.openmoney.cc:4985/openmoney_shadow/_design/" . urlencode($design_doc) . "/_view/" . urlencode($view);
  66. $client = new GuzzleHttp\Client();
  67. $request_options = array("query" => $options);
  68. try {
  69. $response = $client->get($url, $request_options);
  70. } catch (ClientException $e) {
  71. $response = $e->getResponse();
  72. }
  73. $response_code = $response->getStatusCode();
  74. if ($response_code == 200) {
  75. return ($response->json());
  76. } else {
  77. return json_decode("{}", true);
  78. }
  79. }
  80. function ajax_bulkPut($docs) {
  81. $url = "https://cloud.openmoney.cc:4985/openmoney_shadow/_bulk_docs";
  82. $client = new GuzzleHttp\Client();
  83. $request_options = array("json" => $docs);
  84. try {
  85. $response = $client->post($url, $request_options);
  86. } catch (ClientException $e) {
  87. $response = $e->getResponse();
  88. }
  89. $response_code = $response->getStatusCode();
  90. if ($response_code == 201) {
  91. return $response->json();
  92. } else {
  93. return $response_code;
  94. }
  95. }
  96. function updateSession(){
  97. if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 86400)) {
  98. // last request was more than one day ago
  99. session_unset(); // unset $_SESSION variable for the run-time
  100. session_destroy(); // destroy session data in storage
  101. }
  102. $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
  103. if (!isset($_SESSION['CREATED'])) {
  104. ini_set('session.gc-maxlifetime', 86400);
  105. $_SESSION['CREATED'] = time();
  106. } else if (time() - $_SESSION['CREATED'] > 1800) {
  107. // session started more than 30 minutes ago
  108. session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
  109. $_SESSION['CREATED'] = time(); // update creation time
  110. }
  111. }
  112. function authenticate($app){
  113. $username = '';
  114. $password = '';
  115. $email = '';
  116. $session = false;
  117. session_start();
  118. updateSession();//&& $_SESSION['expires'] > time()
  119. if (isset($_SESSION['username']) && isset($_SESSION['expires']) && isset($_SESSION['password']) ) {
  120. $username = $_SESSION['username'];
  121. $password = $_SESSION['password'];
  122. $expires = $_SESSION['expires'];
  123. $session = true;
  124. } else {
  125. // remove all session variables
  126. session_unset();
  127. // destroy the session
  128. session_destroy();
  129. }
  130. session_write_close();
  131. if (($username == '' && $password == '' && $email == '') && (!isset($_POST['username']) || !isset($_POST['password']) || !isset($_POST['email']))) {
  132. $post = json_decode(file_get_contents('php://input'), true);
  133. if (isset($post['username']))
  134. $username = $post['username'];
  135. if (isset($post['password']))
  136. $password = $post['password'];
  137. if (isset($post['email']))
  138. $email = $post['email'];
  139. } else {
  140. if ($username == '' && $password == '' && $email == '' && $session == false) {
  141. if (isset($_POST['username']))
  142. $username = $_POST['username'];
  143. if (isset($_POST['password']))
  144. $password = $_POST['password'];
  145. if (isset($_POST['email']))
  146. $email = $_POST['email'];
  147. }
  148. }
  149. if (($username != '' || $email != '') && $password == '') {
  150. return array("error"=>'Email or Username and password are required !');
  151. }
  152. $user = json_decode(ajax_get("users," . $username), true);
  153. // TODO: cytpographically decode password using cryptographic algorithms specified in the $user ['cryptographic_algorithms'] array.
  154. require ("password.php");
  155. if(isset($user['password'])) {
  156. if ($email != '' && !password_verify($password, $user['password'])) {
  157. //this needs to be switched to use the sync_gateway
  158. $cb = new Couchbase("127.0.0.1:8091", "openmoney", "", "openmoney");
  159. // $profile_lookup_function = 'function (doc, meta) { if( doc.type == \"profile\" && doc.email && doc.username) { emit( doc.email, doc.username ); } }';
  160. // $designDoc = '{ "views": { "profileLookup" : { "map": "' . $profile_lookup_function . '" } } }';
  161. // $cb->setDesignDoc("dev_profile", $designDoc);
  162. $options = array('startkey' => $email,'endkey' => $email . '\uefff');
  163. // do trading name lookup on
  164. $profile_result = $cb->view('dev_profile', 'profileLookup', $options);
  165. foreach($profile_result['rows'] as $row) {
  166. $user = json_decode(ajax_get("users," . $row['value']), true);
  167. }
  168. }
  169. if ((isset($user['password']) && password_verify($password, $user['password'])) || $session) {
  170. return $user;
  171. } else {
  172. return array("error"=>"Password did not match!");
  173. }
  174. } else {
  175. $newUser = array();
  176. $newUser['username'] = strtolower($username);
  177. $newUser['email'] = strtolower($email);
  178. $newUser['password'] = $password;
  179. $newUser['new_user'] = true;
  180. return $newUser;
  181. }
  182. }
  183. function login($user, $app) {
  184. $session_token = randomString(64);
  185. if (isset($user['session_expires']) ){
  186. // example format 2015-05-05T19:42:24.349453085Z
  187. $expiryseconds = strtotime( substr($user['session_expires'],0,strlen($user['session_expires'])-8) . "Z");
  188. $nowseconds = strtotime("NOW");
  189. }
  190. //note check expiry has not happened.
  191. if( isset($user['session_expires']) && $expiryseconds > $nowseconds){
  192. $session_token = $user['session_token'];
  193. $sessionID = $user['session_id'];
  194. $expiry = $user['session_expires'];
  195. $cookie_name = $user['session_cookie_name'];
  196. } else {
  197. if(isset($user['username'])) {
  198. $url = 'https://localhost:4985/openmoney_shadow/_user/' . $user['username'];
  199. // update user
  200. $data = array('name' => $user['username'],'password' => $session_token);
  201. $json = json_encode($data);
  202. $options = array('http' => array('method' => 'PUT','content' => $json,'header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n"));
  203. $context = stream_context_create($options);
  204. $default_context = stream_context_set_default($options);
  205. $result = file_get_contents($url, false, $context);
  206. $url = 'https://localhost:4985/openmoney_shadow/_session';
  207. $data = array('name' => $user['username'],'password' => $session_token); // time to live 24hrs
  208. $json = json_encode($data);
  209. $options = array('http' => array('method' => 'POST','content' => $json,'header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n"));
  210. $context = stream_context_create($options);
  211. $default_context = stream_context_set_default($options);
  212. $result = file_get_contents($url, false, $context);
  213. $json = json_decode($result, true);
  214. $sessionID = $json['session_id'];
  215. $expiry = $json['expires'];
  216. $cookie_name = $json['cookie_name'];
  217. $user['session_id'] = $sessionID;
  218. $user['session_token'] = $session_token;
  219. $user['session_expires'] = $expiry;
  220. $user['session_cookie_name'] = $json['cookie_name'];
  221. ajax_put( "users," . strtolower( $user['username'] ), json_encode ( $user ) );
  222. }
  223. }
  224. if (isset($sessionID)) {
  225. session_start();
  226. $_SESSION['username'] = strtolower($user['username']);
  227. $_SESSION['password'] = $session_token;
  228. $_SESSION['session_id'] = $sessionID;
  229. $_SESSION['expires'] = strtotime($expiry);
  230. session_write_close();
  231. setcookie($cookie_name, $sessionID, strtotime($expiry));
  232. $result = array('cookie_name' => $cookie_name,'sessionID' => $sessionID,'expires' => $expiry,'username' => $user['username'],'session_token' => $session_token,'email' => $user['email']);
  233. return json_encode($result);
  234. } else {
  235. $app->halt(401, json_encode(array('error' => true,'msg' => 'The session could not be set!')));
  236. }
  237. }
  238. $app = new \Slim\Slim();
  239. $app->response->headers->set('Access-Control-Allow-Origin', '*');
  240. $app->response->headers->set('Access-Control-Allow-Credentials', 'true');
  241. $app->response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  242. $app->response->headers->set('Access-Control-Allow-Headers', 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type');
  243. $app->response->headers->set('Content-Type', 'application/json');
  244. $app->notFound(function () use($app) {
  245. $app->halt(404, json_encode(array('error' => true,'msg' => 'Page Not Found')));
  246. });
  247. // $app->view ( new \JsonApiView () );
  248. // $app->add ( new \JsonApiMiddleware () );
  249. $app->get('/', function () use($app) {
  250. $app->redirect('/webclient/');
  251. // echo json_encode ( array ('message' => "Welcome the openmoney json API! go to https://cloud.openmoney.cc/README.md for more information.") );
  252. });
  253. $app->post('/login', function () use($app) {
  254. $user = authenticate($app);
  255. if(isset($user['error'])){
  256. $app->halt(401, json_encode(array('error' => true,'msg' => $user['error'])));
  257. exit();
  258. } else {
  259. if(isset($user['new_user'])){
  260. $app->halt(401, json_encode(array('error' => true,'msg' => "No user found!")));
  261. exit();
  262. } else {
  263. echo login($user, $app);
  264. $app->stop();
  265. }
  266. }
  267. });
  268. $app->post('/registration', function () use($app) {
  269. $user = authenticate($app);
  270. if(isset($user['error'])){
  271. if($user['error'] == 'Password did not match!'){
  272. $app->halt(401, json_encode(array('error' => true,'msg' => 'User already exists!')));
  273. exit();
  274. } else {
  275. $app->halt(401, json_encode(array('error' => true,'msg' => $user['error'])));
  276. exit();
  277. }
  278. }
  279. if (isset($user['new_user']) && $user['new_user']) {
  280. unset($user['new_user']);
  281. $user['cost'] = $options['cost'] = 10;
  282. $user['type'] = "users";
  283. require ("password.php");
  284. $password_hash = password_hash($user['password'], PASSWORD_BCRYPT, $options);
  285. $user['password'] = $password_hash;
  286. $user['password_encryption_algorithm'] = array(PASSWORD_BCRYPT);
  287. $user['created'] = intval(round(microtime(true) * 1000));
  288. ajax_put( "users," . strtolower( $user['username'] ), json_encode ( $user ) );
  289. //$cb->set ( "users," . strtolower( $username ), json_encode ( $user ) );
  290. $bulk_docs = array();
  291. $user['_id'] = "users," . $user['username'];
  292. array_push($bulk_docs, $user);
  293. $subusername = $user['username'];
  294. if (strpos($user['username'], "@") !== false)
  295. $subusername = substr($user['username'], 0, strpos($user['username'], "@"));
  296. // $subusername = str_replace ( ".", "", $subusername );
  297. $subusername = preg_replace("/[^a-zA-Z\d_\.]*/", "", $subusername);
  298. $subspace = "";
  299. $tradingName = $subusername;
  300. if (strpos($subusername, ".") !== false) {
  301. $tradingName = substr($subusername, 0, strpos($subusername, "."));
  302. $subspace = substr($subusername, strpos($subusername, ".") + 1, strlen($subusername));
  303. unset($space);
  304. $space = json_decode(ajax_get("space," . strtolower($subspace)), true);
  305. if (isset($space['steward'])) {
  306. $spaces_array = explode(".", $subspace);
  307. $current_space = $spaces_array[count($spaces_array) - 1]; // last element
  308. $trading_name_space_view['type'] = "space_view";
  309. $trading_name_space_view['space'] = $current_space;
  310. $trading_name_space_view['steward'] = array($user['username']);
  311. $trading_name_space_view['created'] = intval(round(microtime(true) * 1000));
  312. // ajax_put ( "space_view," . strtolower($username) . "," . strtolower( $trading_name_space_view ['space'] ), json_encode ( $trading_name_space_view ) );
  313. // $cb->set ( "space_view," . strtolower($username) . "," . strtolower( $trading_name_space_view ['space'] ), json_encode ( $trading_name_space_view ) );
  314. $trading_name_space_view['_id'] = "space_view," . $user['username'] . "," . strtolower($trading_name_space_view['space']);
  315. array_push($bulk_docs, $trading_name_space_view);
  316. for($i = count($spaces_array) - 2; $i >= 0; $i--) {
  317. $current_space = $spaces_array[$i] . "." . $current_space;
  318. $trading_name_space_view['type'] = "space_view";
  319. $trading_name_space_view['space'] = $current_space;
  320. $trading_name_space_view['steward'] = array($user['username']);
  321. $trading_name_space_view['created'] = intval(round(microtime(true) * 1000));
  322. // ajax_put ( "space_view," . strtolower($username) . "," . strtolower( $trading_name_space_view ['space'] ), json_encode ( $trading_name_space_view ) );
  323. // $cb->set ( "space_view," . strtolower($username) . "," . strtolower( $trading_name_space_view ['space'] ), json_encode ( $trading_name_space_view ) );
  324. $trading_name_space_view['_id'] = "space_view," . $user['username'] . "," . strtolower($trading_name_space_view['space']);
  325. array_push($bulk_docs, $trading_name_space_view);
  326. }
  327. $subspace = $current_space;
  328. } else {
  329. // create or add view of the space
  330. $spaces_array = explode(".", $subspace);
  331. $current_space = "cc";
  332. $subspace = "cc";
  333. for($i = count($spaces_array) - 1; $i >= 0; $i--) {
  334. // check if the root of what they asked for is cc and ignore
  335. if ($i == count($spaces_array) - 1 && $spaces_array[$i] == ".cc") {} else {
  336. $current_space = $spaces_array[$i] . "." . $current_space;
  337. // if space doesn't exist create it.
  338. unset($space);
  339. $space = json_decode(ajax_get("space," . strtolower($current_space)), true);
  340. if (!isset($space['steward'])) {
  341. // create the space as this users
  342. $trading_name_space['type'] = "space";
  343. $trading_name_space['space'] = $current_space;
  344. $trading_name_space['subspace'] = $subspace;
  345. $trading_name_space['steward'] = array($user['username']);
  346. $trading_name_space['created'] = intval(round(microtime(true) * 1000));
  347. // $space = ajax_get ( "space," . strtolower( $trading_name_space ['space'] ) );
  348. // ajax_put ( "space," . strtolower( $trading_name_space ['space'] ), json_encode ( $trading_name_space ) );
  349. // $cb->set ( "space," . strtolower( $trading_name_space ['space'] ), json_encode ( $trading_name_space ) );
  350. $trading_name_space['_id'] = "space," . strtolower($trading_name_space['space']);
  351. array_push($bulk_docs, $trading_name_space);
  352. }
  353. $trading_name_space_view['type'] = "space_view";
  354. $trading_name_space_view['space'] = $current_space;
  355. $trading_name_space_view['steward'] = array($user['username']);
  356. $trading_name_space_view['created'] = intval(round(microtime(true) * 1000));
  357. // ajax_put ( "space_view," . strtolower($username) . "," . strtolower( $trading_name_space_view ['space'] ), json_encode ( $trading_name_space_view ) );
  358. // $cb->set ( "space_view," . strtolower($username) . "," . strtolower( $trading_name_space_view ['space'] ), json_encode ( $trading_name_space_view ) );
  359. $trading_name_space_view['_id'] = "space_view," . $user['username'] . "," . strtolower($trading_name_space_view['space']);
  360. array_push($bulk_docs, $trading_name_space_view);
  361. $subspace = $current_space;
  362. }
  363. }
  364. }
  365. }
  366. $trading_name_space['type'] = "space";
  367. $trading_name_space['space'] = $subspace != "" ? $tradingName . "." . $subspace : $tradingName . ".cc";
  368. $trading_name_space['subspace'] = $subspace != "" ? $subspace : "cc";
  369. $trading_name_space['steward'] = array($user['username']);
  370. $trading_name_space['created'] = intval(round(microtime(true) * 1000));
  371. // ajax_put ( "space," . strtolower( $trading_name_space ['space'] ), json_encode ( $trading_name_space ) );
  372. $trading_name_space['_id'] = "space," . strtolower($trading_name_space['space']);
  373. array_push($bulk_docs, $trading_name_space);
  374. $trading_name_space_view['type'] = "space_view";
  375. $trading_name_space_view['space'] = $subspace != "" ? $tradingName . "." . $subspace : $tradingName . ".cc";
  376. $trading_name_space_view['steward'] = array($user['username']);
  377. $trading_name_space_view['created'] = intval(round(microtime(true) * 1000));
  378. // ajax_put ( "space_view," . strtolower($username) . "," . strtolower( $trading_name_space_view ['space'] ), json_encode ( $trading_name_space_view ) );
  379. $trading_name_space_view['_id'] = "space_view," . $user['username'] . "," . strtolower($trading_name_space_view['space']);
  380. array_push($bulk_docs, $trading_name_space_view);
  381. $trading_name_space_view['type'] = "space_view";
  382. $trading_name_space_view['space'] = "cc";
  383. $trading_name_space_view['steward'] = array($user['username']);
  384. $trading_name_space_view['created'] = intval(round(microtime(true) * 1000));
  385. // ajax_put ( "space_view," . strtolower($username) . "," . strtolower( $trading_name_space_view ['space'] ), json_encode ( $trading_name_space_view ) );
  386. $trading_name_space_view['_id'] = "space_view," . $user['username'] . "," . strtolower($trading_name_space_view['space']);
  387. array_push($bulk_docs, $trading_name_space_view);
  388. $trading_name['type'] = "trading_name";
  389. $trading_name['trading_name'] = $tradingName;
  390. $trading_name['name'] = $subspace != "" ? $tradingName . "." . $subspace : $tradingName . ".cc";
  391. $trading_name['space'] = $subspace != "" ? $subspace : "cc";
  392. $trading_name['currency'] = "cc";
  393. $trading_name['steward'] = array($user['username']);
  394. $trading_name['created'] = intval(round(microtime(true) * 1000));
  395. $exists = json_decode(ajax_get("trading_name," . strtolower($trading_name['name']) . "," . strtolower($trading_name['currency'])), true);
  396. if (isset($exists['steward'])) {
  397. $app->halt(401, json_encode(array('error' => true,'msg' => 'User already exists!')));
  398. } else {
  399. // ajax_put ( "trading_name," . strtolower( $trading_name ['name'] ) . "," . strtolower( $trading_name ['currency'] ), json_encode ( $trading_name ) );
  400. $trading_name['_id'] = "trading_name," . strtolower($trading_name['name']) . "," . strtolower($trading_name['currency']);
  401. array_push($bulk_docs, $trading_name);
  402. }
  403. $currency_view['type'] = "currency_view";
  404. $currency_view['currency'] = "cc";
  405. $currency_view['steward'] = array($user['username']);
  406. $currency_view['created'] = intval(round(microtime(true) * 1000));
  407. // ajax_put ( "currency_view," . strtolower( $username ) . "," . strtolower( $currency_view ['currency'] ), json_encode ( $currency_view ) );
  408. $currency_view['_id'] = "currency_view," .$user['username'] . "," . strtolower($currency_view['currency']);
  409. array_push($bulk_docs, $currency_view);
  410. $subspace_document = json_decode(ajax_get("space," . $user['username']), true);
  411. $defaultcurrency = strtolower($subspace);
  412. if (isset($subspace_document['defaultcurrency'])) {
  413. $defaultcurrency = strtolower($subspace_document['defaultcurrency']);
  414. }
  415. unset($currency);
  416. $currency = json_decode(ajax_get("currency," . strtolower($defaultcurrency)), true);
  417. if (isset($currency['steward'])) {
  418. $trading_name['currency'] = $currency['currency'];
  419. $exists = json_decode(ajax_get("trading_name," . strtolower($trading_name['name']) . "," . strtolower($trading_name['currency'])), true);
  420. if (isset($exists['steward'])) {
  421. if ($exists['steward'] != $trading_name['steward']) {
  422. $app->halt(401, json_encode(array('error' => true,'msg' => 'User already exists!')));
  423. }
  424. } else {
  425. // ajax_put ( "trading_name," . strtolower( $trading_name ['name'] ) . "," . strtolower( $trading_name ['currency'] ), json_encode ( $trading_name ) );
  426. $trading_name['_id'] = "trading_name," . strtolower($trading_name['name']) . "," . strtolower($trading_name['currency']);
  427. array_push($bulk_docs, $trading_name);
  428. }
  429. $currency_view['type'] = "currency_view";
  430. $currency_view['currency'] = strtolower($trading_name['currency']);
  431. $currency_view['steward'] = array($user['username']);
  432. $currency_view['created'] = intval(round(microtime(true) * 1000));
  433. // ajax_put ( "currency_view," . strtolower( $username ) . "," . strtolower( $currency_view ['currency'] ), json_encode ( $currency_view ) );
  434. $currency_view['_id'] = "currency_view," . $user['username'] . "," . strtolower($currency_view['currency']);
  435. array_push($bulk_docs, $currency_view);
  436. }
  437. $profile['type'] = "profile";
  438. $profile['username'] = $user['username'];
  439. $profile['email'] = $user['email'];
  440. $profile['notification'] = true;
  441. $profile['mode'] = false;
  442. $profile['theme'] = false;
  443. $profile['created'] = intval(round(microtime(true) * 1000));
  444. // ajax_put ( "profile," . strtolower( $username ) , json_encode ( $profile ) );
  445. $profile['_id'] = "profile," . $user['username'];
  446. array_push($bulk_docs, $profile);
  447. $bulk = array("docs" => $bulk_docs);
  448. $bulk_result = ajax_bulkPut($bulk);
  449. $key = "trading_name," . strtolower($trading_name['name']) . "," . strtolower($trading_name['currency']);
  450. $options = array('startkey' => '"' . $key . '"','endkey' => '"' . $key . '\uefff"');
  451. $options['stale'] = 'false';
  452. $result = ajax_getView('dev_rest', "accounts", $options);
  453. echo login($user, $app);
  454. $app->stop();
  455. }
  456. });
  457. $app->get('/logout', function () use($app) {
  458. session_start();
  459. // if (isset($_SESSION['session_id'])) {
  460. // $url = 'https://localhost:4985/openmoney_shadow/_session/' . $_SESSION['session_id'];
  461. // // $url = 'https://localhost:4985/todos/_session';
  462. // // $data = array ('name' => $user ['username'], 'ttl' => 86400); // time to live 24hrs
  463. // // $json = json_encode ( $data );
  464. // $options = array('http' => array('method' => 'DELETE','header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n"));
  465. // $context = stream_context_create($options);
  466. // $default_context = stream_context_set_default($options);
  467. // // $response_code = get_http_response_code ( $url );
  468. // $result = file_get_contents($url, false, $context);
  469. // $json = json_decode($result, true);
  470. // }
  471. // remove all session variables
  472. session_unset();
  473. // destroy the session
  474. session_destroy();
  475. session_write_close();
  476. // unset ( $_COOKIE ['SyncGatewaySession'] );
  477. // setcookie ( "SyncGatewaySession", '', time () - 3600, '/' );
  478. // unset cookies
  479. if (isset($_SERVER['HTTP_COOKIE'])) {
  480. $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
  481. foreach($cookies as $cookie) {
  482. $parts = explode('=', $cookie);
  483. $name = trim($parts[0]);
  484. setcookie($name, '', time() - 1000);
  485. setcookie($name, '', time() - 1000, '/');
  486. }
  487. }
  488. echo json_encode(array('error' => false,'msg' => 'you are now logged out'));
  489. $app->stop();
  490. });
  491. $app->post('/lostpw', function () use($app) {
  492. $username = '';
  493. $email = '';
  494. if (($username == '') && (!isset($_POST['username']))) {
  495. $post = json_decode(file_get_contents('php://input'), true);
  496. if (isset($post['username'])) {
  497. $username = $post['username'];
  498. } else {
  499. $app->render(401, array('error' => true,'msg' => 'Username or Email required!'));
  500. exit();
  501. }
  502. } else {
  503. if ($username == '') {
  504. $username = $_POST['username'];
  505. }
  506. }
  507. if ($username != '') {
  508. require ("password.php");
  509. function email_letter($to, $from, $subject = 'no subject', $message = 'no msg') {
  510. $headers = "From: $from\r\n";
  511. $headers .= "MIME-Version: 1.0\r\n";
  512. $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
  513. $headers .= 'X-Mailer: PHP/' . phpversion();
  514. // Make sure linefeeds are in CRLF format - it is essential for signing
  515. $message = preg_replace('/(?<!\r)\n/', "\r\n", $message);
  516. $headers = preg_replace('/(?<!\r)\n/', "\r\n", $headers);
  517. require_once 'mail-signature.class.php';
  518. require_once 'mail-signature.config.php';
  519. $signature = new mail_signature(
  520. MAIL_RSA_PRIV,
  521. MAIL_RSA_PASSPHRASE,
  522. MAIL_DOMAIN,
  523. MAIL_SELECTOR
  524. );
  525. $signed_headers = $signature -> get_signed_headers($to, $subject, $message, $headers);
  526. return mail($to, $subject, $message, $signed_headers.$headers);
  527. }
  528. $cb = new Couchbase("127.0.0.1:8091", "openmoney", "", "openmoney");
  529. $user = json_decode(ajax_get("users," . $username), true);
  530. if (!isset($user['username']) || $user['username'] == '') {
  531. // $profile_lookup_function = 'function (doc, meta) { if( doc.type == \"profile\" && doc.email && doc.username) { emit( doc.email, doc.username ); } }';
  532. // $designDoc = '{ "views": { "profileLookup" : { "map": "' . $profile_lookup_function . '" } } }';
  533. // $cb->setDesignDoc ( "dev_profile", $designDoc );
  534. $options = array('startkey' => $username,'endkey' => $username . '\uefff','stale' => false);
  535. // do profile email lookup
  536. $profile_result = $cb->view('dev_profile', 'profileLookup', $options);
  537. foreach($profile_result['rows'] as $row) {
  538. $user = json_decode(ajax_get("users," . $row['value']), true);
  539. $email = $username;
  540. }
  541. if (!isset($user['username']) || $user['username'] == '') {
  542. // user is undefined
  543. $responseCode = 404;
  544. $app->halt($responseCode, json_encode(array('error' => true,'msg' => 'Email ' . $username . ' was not found !' . $user)));
  545. }
  546. }
  547. // email passed check send email with password reset link
  548. $reset_key = randomString(64);
  549. $reset_hash = password_hash($reset_key, PASSWORD_BCRYPT);
  550. // update key on user table, then verify in resetPassword.php
  551. $user['reset_token_key'] = $reset_key;
  552. ajax_put("users," . $user['username'], json_encode($user));
  553. $msg = "To Reset your password click on this link <a href='https://cloud.openmoney.cc/resetPassword.php?email=" . urlencode($user['username']) . "&reset=" . urlencode($reset_hash) . "'>Reset Password</a>";
  554. $msg .= "<p>OpenMoney IT Team</p>";
  555. $msg .= "If you did not initiate the lost password link request then ignore this and your password will remain the same.";
  556. $subject = "openmoney: lost password reset REQUESTED for " . $user['username'];
  557. $dear = $user['username'];
  558. if ($email != '') {
  559. $sentEmail = email_letter("\"" . $dear . "\"<" . $email . ">", "noreply@openmoney.cc", $subject, $msg);
  560. } else {
  561. $profile = json_decode(ajax_get("profile," . strtolower($user['username'])), true);
  562. $sentEmail = email_letter("\"" . $dear . "\"<" . $profile['email'] . ">", "noreply@openmoney.cc", $subject, $msg);
  563. }
  564. echo json_encode(array('sentEmail' => $sentEmail));
  565. $app->stop();
  566. } else {
  567. $app->halt(401, json_encode(array('error' => true,msg => 'Email is required!')));
  568. }
  569. });
  570. $app->post('/lookupTag', function () use($app) {
  571. $user = authenticate($app);
  572. $post = json_decode(file_get_contents('php://input'), true);
  573. $key = $post['key'];
  574. $beamlookup_function = 'function (doc, meta) { if( doc.type == \"beamtag\" ) { if(typeof doc.archived == \"undefined\" || doc.archived === false) { emit(doc.hashTag, doc.trading_names); } } }';
  575. $tradingname_lookup_function = 'function (doc, meta) { if( doc.type == \"trading_name\" && doc.steward && doc.name && doc.currency && !doc.archived && !doc.disabled) { emit( \"trading_name,\"+doc.name+\",\"+doc.currency, { \"trading_name\": doc.name, \"currency\": doc.currency } ); } }';
  576. $designDoc = '{ "views": { "tradingnamelookup4" : { "map": "' . $tradingname_lookup_function . '" }, "beamlookup2": { "map": "' . $beamlookup_function . '" } } }';
  577. // echo $designDoc;
  578. // $cb->setDesignDoc("dev_nfctag", $designDoc);
  579. // $result = $cb->view('dev_nfctag', 'beamlookup2', array('startkey' => $key,'endkey' => $key . '\uefff'));
  580. $viewname = 'beamtag';
  581. $options = array('startkey' => '"' . $key . '"','endkey' => '"' . $key . '\uefff"');
  582. $options['stale'] = 'false';
  583. $result = ajax_getView('dev_rest', $viewname, $options);
  584. $trading_names_array = array();
  585. foreach($result['rows'] as $row) {
  586. // remove users, from id
  587. $trading_names = $row['value'];
  588. foreach($trading_names as $trading_name) {
  589. array_push($trading_names_array, $trading_name);
  590. // $options = array('startkey' => "trading_name," . $trading_name['trading_name'] . "," . $trading_name['currency'],'endkey' => "trading_name," . $trading_name['trading_name'] . "," . $trading_name['currency'] . '\uefff');
  591. if (isset($trading_name['trading_name']) && $trading_name['trading_name'] != null) {
  592. $trading_name_view = json_decode(ajax_get("trading_name_view," . $user['username'] . "," . $trading_name['trading_name'] . "," . $trading_name['currency']), true);
  593. if (!isset($trading_name_view['trading_name'])) {
  594. // add them to their list of senders
  595. $trading_name_from_view['type'] = "trading_name_view";
  596. $trading_name_from_view['steward'] = array($user['username']);
  597. $trading_name_from_view['trading_name'] = $trading_name['trading_name'];
  598. $trading_name_from_view['currency'] = $trading_name['currency'];
  599. $trading_name_from_view['created'] = intval(round(microtime(true) * 1000));
  600. ajax_put("trading_name_view," . $user['username'] . "," . $trading_name_from_view['trading_name'] . "," . $trading_name_from_view['currency'], json_encode($trading_name_from_view));
  601. }
  602. }
  603. }
  604. }
  605. if (empty($trading_names_array)) {
  606. $app->halt(404, json_encode(array('error' => true,msg => 'No Trading Names Found!')));
  607. } else {
  608. // output array
  609. echo json_encode($trading_names_array);
  610. $app->stop();
  611. }
  612. });
  613. $app->post('/customerLookup', function () use($app) {
  614. $username = '';
  615. $password = '';
  616. if (($username == '' && $password == '') && (!isset($_POST['username']) || !isset($_POST['password']))) {
  617. $post = json_decode(file_get_contents('php://input'), true);
  618. $username = $post['username'];
  619. $password = $post['password'];
  620. if ($username == '' && $password == '') {
  621. $app->halt(401, json_encode(array('error' => true,'msg' => 'Email and password are required !')));
  622. }
  623. } else {
  624. if ($username == '' && $password == '') {
  625. $username = $_POST['username'];
  626. $password = $_POST['password'];
  627. }
  628. }
  629. $cb = new Couchbase("127.0.0.1:8091", "openmoney", "", "openmoney");
  630. $user = ajax_get("users," . $username);
  631. $user = json_decode($user, true);
  632. // TODO: cytpographically decode password using cryptographic algorithms specified in the $user ['cryptographic_algorithms'] array.
  633. require ("password.php");
  634. if (password_verify($password, $user['password'])) {
  635. $tradingname_lookup_function = 'function (doc, meta) { if( doc.type == \"trading_name\" && doc.steward && doc.name && doc.currency && !doc.archived) { doc.steward.forEach(function( steward ) { emit( [steward, doc.currency, doc.name], { \"name\": doc.name, \"currency\": doc.currency } ); } ); } }';
  636. $designDoc = '{ "views": { "tradingnamelookup" : { "map": "' . $tradingname_lookup_function . '" } } }';
  637. // echo $designDoc;
  638. $cb->setDesignDoc("dev_customer", $designDoc);
  639. $options = array('startkey' => array($username),'endkey' => array($username . '\uefff','\uefff','\uefff'));
  640. // do trading name lookup on
  641. $tradingname_result = $cb->view('dev_customer', 'tradingnamelookup', $options);
  642. $tradingname_array = array();
  643. foreach($tradingname_result['rows'] as $row) {
  644. unset($object);
  645. $object['id'] = $row['id'];
  646. $object['value'] = $row['value'];
  647. array_push($tradingname_array, $object);
  648. }
  649. echo json_encode($tradingname_array);
  650. $app->stop();
  651. } else {
  652. $app->halt(401, json_encode(array('error' => true,'msg' => 'Password did not match!')));
  653. }
  654. });
  655. $app->run();
  656. ?>