-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata-cat-process.php
436 lines (402 loc) · 17.2 KB
/
data-cat-process.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<?php
/**
* @package Data Cat Process
*/
/*
Plugin Name: Data Cataloguing Process
Plugin URI: https://github.com/afel-project/data-catalogue-process-wordpress
Description: Service for generating datasets for the Entity-Centric API and generating user keys for accessing them. Also supports the creation of learning dashboards for users.
Version: 0.2.0 - 16-02-2017
Author: mdaquin
Author URI: http://mdaquin.net
License: -
*/
// Prevent direct calls
if( !function_exists('add_action') ) die( "This is a plugin, there's nothing for you here." );
register_activation_hook( __FILE__, 'dcp_activate' );
// for couchdb code reuse from ecapi plugin
require_once( str_replace("/data-cat-process/", "/", plugin_dir_path( __FILE__ )) . 'ecapi/inc/ecapiconfigform/couchdb.class.php');
define('DCP_VERSION', "0.1.1");
define('DCP_LOG', true);
function dcp_log(){
if(DCP_LOG === true){
error_log("[DCP] " . implode(' ', func_get_args()));
}
}
/*
* TODO This should be configurable from WordPress!
*/
$config = array(
"ecapiuri" => "http://localhost:8081/jit/",
"ecapikey" => ""
);
/**
* Check for dependencies.
*/
function dcp_activate(){
$deps = array( 'ecapi', 'mks-data-cataloguing' );
$unsatisfied = array();
foreach( $deps as $dep )
if( !is_plugin_active("{$dep}/{$dep}.php") ) $unsatisfied []= $dep;
if( !empty($unsatisfied) && current_user_can('activate_plugins') ) {
$msg = 'Plugin <strong>Data Cataloguing Process</strong> (' . plugin_basename( __FILE__ ) . ')'
. ' requires the following WordPress plugins to be installed and activated first:<ul>';
foreach( $unsatisfied as $dep ) $msg .= '<li>'.$dep.'</li>';
$msg .= '</ul><p><a href="' . admin_url( 'plugins.php' ) . '">« Return to Plugins</a>';
wp_die($msg);
}
}
function dcp_admin_init() {
register_setting('ecapi_options', 'dcp_options', 'dcp_options_validate');
add_settings_section('dcp_perm', 'Update and Creation of Datasets', 'dcp_perm_text', 'ecapi-settings');
add_settings_field('ecapi_su_key', 'Entity-centric API Super User Key', 'dcp_setting_su_key', 'ecapi-settings', 'dcp_perm');
add_settings_field('ecapi_sparql_query', 'SPARQL query endpoint', 'dcp_setting_sparql_query', 'ecapi-settings', 'dcp_perm');
add_settings_field('ecapi_sparql_update', 'SPARQL update endpoint', 'dcp_setting_sparql_update', 'ecapi-settings', 'dcp_perm');
}
function dcp_handle_registration() {
$resp = array( "version" => DCP_VERSION);
switch( $_SERVER['REQUEST_METHOD'] ) {
case 'GET':
// some other function creates the content
break;
case 'POST':
// XXX there is a hardcoded path here which needs to be matched
// by a page slug on WordPress!
// TODO handle this condition somewhere else
$bn = basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if( $bn === "newuserdataset" ) {
$result = array( "version" => DCP_VERSION );
$missing = [];
// check that the query includes what we need
if( empty($_POST['type']) ) $missing []= "a type of dataset";
if( empty($_POST['description']) ) $missing []= "a description for the dataset";
// if( empty($_POST['ecapiconf']) ) $missing []= "a configuration for the Data API";
handle_invalid_registration( $missing, $result );
$rez = dcp_login_and_create_dataset( $_POST['type'], $_POST['description'] );
wp_send_json( $rez, $rez['http_status'] );
}
/* ****** BEGIN super-temporary hack ****** */
elseif( $bn === "verifyuser" ) {
// header('Access-Control-Allow-Origin : http://analytics.didactalia.net');
$result = array( "version" => DCP_VERSION );
if( !empty($_POST['username']) && !empty($_POST['password']) ) {
$user = get_user_by( 'login', $_POST['username'] );
if( !$user || !wp_check_password( $_POST['password'], $user->data->user_pass, $user->ID) ) {
$result['http_status'] = 401;
$result['error'] = "invalide username or password";
} else {
$result["whoami"] = $user->user_login;
$result["key"] = computeUserKey($user->user_login);
$result['http_status'] = 200;
}
} else $result['http_status'] = 403;
wp_send_json( $result, $result['http_status'] ); // it also dies after sending.
}
/* ****** END super-temporary hack ****** */
break;
// default:
// wp_send_json( $resp, 405 );
}
}
/**
* If no user_id is provided, the function will expect
* username and password in POSTdata.
*
* TODO: get rid of credential checks in POSTdata.
* In fact, change this function to pass it the WP User object
*/
function dcp_login_and_create_dataset( $ds_type, $ds_description, $user_id = 0 ) {
$result = array( "version" => DCP_VERSION );
$missing = [];
$status = 200;
// Check that we have enough information to identify the user
if( isset($user_id) && $user_id > 0 ) {
$user = get_user_by( 'id', $user_id );
if( !$user ) {
$status = 401;
$missing []= "your browser must be logged into the AFEL platform"
. " (unless username and password are provided instead)";
}
} else {
if( empty($_POST['username']) ) $missing []= "your AFEL username";
if( empty($_POST['password']) ) $missing []= "your non-empty AFEL password";
if( !empty($missing) ) {
$status = 400;
$missing []= "Alternatively, make sure to be logged into the AFEL platform from your browser.";
}
$user = get_user_by( 'login', $_POST['username'] );
if( !$user || !wp_check_password( $_POST['password'], $user->data->user_pass, $user->ID) ) {
$status = 401;
$missing []= "_valid_ credentials for the AFEL data platform";
}
}
handle_invalid_registration( $missing, $result, $status );
// From this point on, everything seems alright regarding credentials.
$username = $user->user_login;
$result['username'] = $username;
// Set the following immediately, so clients can interpret
// a Conflict as a hint to reuse an existing dataset.
$result['key'] = computeUserKey($username);
$result['dataset'] = computeDatasetId($ds_type, $username);
if( !createDatasetEntry($ds_type, $username, $user->ID, $result['dataset'], $ds_description) ){
$result['error'] = "could not create dataset entry - maybe it already exists";
$status = 409;
} else {
// declare the dataset in ECAPI
/* $options = get_option('ecapi_options');
$ecapiroot = str_replace("entity", "dataset", $options['ecapi_url']);
$options = get_option('dcp_options');
$sukey = $options['ecapi_su_key'];
$sparqlq = $options['ecapi_sparql_query'];
$result['ecapi'] = $ecapiroot;
$ch = curl_init($ecapiroot.$result['dataset'].'?key='.$sukey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$response = curl_exec($ch);
$info = curl_getinfo($ch);
if ($info['http_code'] !== 200){
$result["error"] = "could not create ecapi dataset ".
$result['dataset'].": ".$info['http_code'];
}
curl_close($ch);
// GRANT write and read to user key
$ch = curl_init($ecapiroot.$result['dataset'].'/grant/?key='.$sukey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POST, 2);
curl_setopt($ch,CURLOPT_POSTFIELDS, "right=write&ukey=".$result['key']);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
if ($info['http_code'] !== 200){
$result["error"] = "could not grant access to ecapi dataset ".
$result['dataset'].": ".$info['http_code'];
}
curl_close($ch);
// update the couchdb config for ECAPI
$opts = get_option('ecapi_options');
$dbms = new couchdb(
$opts['ecapi_config_db_url'], $opts['ecapi_config_db_name'],
$opts['ecapi_config_db_username'], $opts['ecapi_config_db_password']
);
$json = $dbms->getDoc($result['dataset']);
$is_change = empty($json['data']->error);
if( $is_change ) {
$json = $json['data'];
$_rev = $json->_rev;
} else {
$json = new stdClass();
$_rev = NULL;
}
$json->type = "provider-spec";
$json->{"mks:cache-lifetime"} = intval($cachetime);
// TODO: probably how you make the link...
// $json->{'catalogue-uuid'};
$json->{'http://rdfs.org/ns/void#sparqlEndpoint'} = $sparqlq;
// Changed because URNs don't like slashes
$json->{'mks:graph'} = 'urn:dataset:'.$result['dataset'].':graph';
if( is_array($ecapi_conf) )
$conf_obj = $ecapi_conf;
elseif( is_object($ecapi_conf) )
$conf_obj = (array) $ecapi_conf;
else
$conf_obj = json_decode(str_replace('\"','"', str_replace('\\\"', '\"', $ecapi_conf)));
foreach( $conf_obj as $typename => &$rules ) {
foreach( $rules as $rulename => &$rule )
$rule = str_replace('[GRAPH]', $json->{'mks:graph'}, $rule);
}
//$replaced = str_replace('\"','"', str_replace('\\\"', '\"', str_replace('[GRAPH]', $json->{'mks:graph'}, $ecapi_conf)));
//$result['rules'] = $replaced;
//$json->{'mks:types'} = json_decode(str_replace('\"','"', str_replace('\\\"', '\"', str_replace('[GRAPH]', $json->{'mks:graph'}, $ecapi_conf))));
$json->{'mks:types'} = $conf_obj;
$response = $dbms->saveDoc( $result['dataset'], $json );
if( !empty($response['data']->error) )
$result['error'] = "failed to configure dataset ".$result['dataset'].' - '.$response['data']->error.': '.$response['data']->reason;
// TODO: Connect the catalogue dataset to ECAPI */
}
$result['http_status'] = $status;
// wp_send_json( $result, $status ); // it also dies after sending.
return $result;
}
function dcp_options_validate($input) {
$options = get_option('dcp_options');
$options['ecapi_su_key'] = trim($input['ecapi_su_key']);
$options['ecapi_sparql_query'] = trim($input['ecapi_sparql_query']);
$options['ecapi_sparql_update'] = trim($input['ecapi_sparql_update']);
return $options;
}
function dcp_perm_text(){
print '<p>Set up the catalogue permissions and endpoint to enable the creation of new datasets in ECAPI.</p>';
}
function dcp_setting_sparql_update() {
$options = get_option('dcp_options');
print "<input id=\"ecapi_sparql_update\" name=\"dcp_options[ecapi_sparql_update]\" size=\"48\" type=\"text\" value=\"{$options['ecapi_sparql_update']}\"/>";
}
function dcp_setting_sparql_query() {
$options = get_option('dcp_options');
print "<input id=\"ecapi_sparql_query\" name=\"dcp_options[ecapi_sparql_query]\" size=\"48\" type=\"text\" value=\"{$options['ecapi_sparql_query']}\"/>";
}
function dcp_setting_su_key() {
$options = get_option('dcp_options');
print "<input id=\"ecapi_su_key\" name=\"dcp_options[ecapi_su_key]\" size=\"48\" type=\"text\" value=\"{$options['ecapi_su_key']}\"/>";
}
function computeUserKey($username){
$salt1 = "I don't know what to do";
$salt2 = "about this really";
return md5($salt1.$username.$salt2);
}
function computeDatasetId($type, $username){
$salt1 = "rumble in the jungle";
$salt2 = "the party is on";
$salt3 = "but the giraff will be sad";
return md5($salt1.$type.$salt2.$username.$salt3);
}
function createDatasetEntry($type, $username, $userid, $datasetid, $description, $force = FALSE) {
$post_id = -1;
$author_id = $userid;
// $slug = sanitize_title($type).'-'.$username;
$slug = $datasetid;
$title = "$type for $username";
$query = array(
'name' => $slug,
'post_type' => 'mksdc-datasets',
'numberposts' => 1
);
$found = get_posts($query);
// Do nothing if title or dataset ID exists as WP slug, unless forced to insert.
if( ($found || get_page_by_title($title) != NULL ) && !$force ) {
// print $found[0]->ID;
return FALSE;
}
$post_id = wp_insert_post( array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => 'mksdc-datasets' // of course that means that mksdc needs to be installed
));
return TRUE;
}
function handle_invalid_registration( $missing, $response_obj, $http_status = 400 ) {
if( empty($missing) ) return;
$response_obj['error'] = "Please provide the following:";
foreach( $missing as $mi )
$response_obj['error'] .= " * $mi\n";
wp_send_json( $response_obj, $http_status );
die();
}
/**
* If username is null, look for a currently logged user
*/
function validate_credentials( $username = NULL, $password = NULL ) {
if( !empty($username) && !empty($password) ) {
$user = get_user_by( 'login', $username );
if( $user && wp_check_password( $password, $user->data->user_pass, $user->ID) )
return $user;
else return FALSE;
} elseif( is_user_logged_in() ) {
$user_id = get_current_user_id();
if( isset($user_id) && $user_id > 0 )
return get_user_by( 'id', $user_id );
else return FALSE;
}
return FALSE;
}
// Hooks
add_action( 'admin_init', 'dcp_admin_init' );
add_action( 'template_redirect', 'dcp_handle_registration' );
//================================================================================
// Dashboard-specific code
//================================================================================
function createDashboard( $atts ){
ob_start();
if (!is_user_logged_in()){
echo '<div><strong>You don'."'".'t seem to be currently <a href="http://data.afel-project.eu/catalogue/wp-login.php">logged in</a>?<strong></div><div> </div><div> </div>';
} else {
$current_user = wp_get_current_user();
$u = $current_user->user_login;
$key = computeUserKey($u);
$csvid = getCSVId($key);
if ($csvid != "") {
echo '<iframe id="advanceddashboard" style="width: 100%; height: 100vh;" src="https://vizrectest.know-center.tugraz.at?dataurl=http%3A%2F%2Fdata.afel-project.eu%2Fapi%2Fbh%2Fcsv%2F%3Fid%3D'.$csvid.'"> </iframe>';
} else {
echo '<div><strong>Could not connect to your data. Try refreshing and check that you are <a href="http://data.afel-project.eu/catalogue/wp-login.php">logged in</a>?<strong></div><div> </div><div> </div>';
}
}
$html = ob_get_contents();
ob_end_clean();
return $html;
}
function getCSVId($u){
$process = curl_init("http://127.0.0.1:8106?user=".$u."&csvid=yes");
// curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
// curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, "browsinghistory:kaH3GNCG");
// curl_setopt($process, CURLOPT_TIMEOUT, 30);
// curl_setopt($process, CURLOPT_POST, 1);
// curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
$ro = json_decode($return);
curl_close($process);
return $ro->csvid;
}
function createDataLink( $atts ){
ob_start();
if (!is_user_logged_in()){
echo '<div><strong>You don'."'".'t seem to be currently <a href="http://data.afel-project.eu/catalogue/wp-login.php">logged in</a>?<strong></div><div> </div><div> </div>';
} else {
$current_user = wp_get_current_user();
$u = $current_user->user_login;
$key = computeUserKey($u);
$csvid = getCSVId($key);
// include 'pages/user_dashboard.phtml';
if ($csvid != "") {
echo '<div><a class="downloadbutton" target="_blank" href="http://data.afel-project.eu/api/bh/csv/?id='.$csvid.'">Get Your Data (csv file)</a></div><div> </div>';
} else {
echo '<div><strong>Could not connect to your data. Try refreshing and check that you are <a href="http://data.afel-project.eu/catalogue/wp-login.php">logged in</a>?<strong></div><div> </div><div> </div>';
}
}
$html = ob_get_contents();
ob_end_clean();
return $html;
}
function dcp_add_scripts(){
wp_register_style('afel_dashboard', plugins_url('/css/style.css', __FILE__));
wp_enqueue_style('afel_dashboard');
wp_register_script( 'canvasjs', 'http://canvasjs.com/assets/script/canvasjs.min.js' );
wp_enqueue_script ( 'canvasjs' );
wp_register_script( 'afeldb-script', plugins_url( '/afelDashboard.js', __FILE__ ) );
wp_enqueue_script ( 'afeldb-script' );
}
function getDailyActivityData($k, $d){
// FIXME hardcoded URI here
$process = curl_init("http://data.afel-project.eu/api/entity/day/".$d);
// curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
// curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $k . ":");
// curl_setopt($process, CURLOPT_TIMEOUT, 30);
// curl_setopt($process, CURLOPT_POST, 1);
// curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);
return $return;
}
// Hooks
add_action( 'wp_enqueue_scripts', 'dcp_add_scripts' );
add_shortcode( 'afel_dashboard', 'createDashboard' );
add_shortcode( 'afel_data', 'createDataLink' );
/* ****** BEGIN ugly CORS hack ****** */
add_action( 'init', 'handle_preflight' );
function handle_preflight() {
header("Access-Control-Allow-Origin: http://analytics.didactalia.net");
header("Access-Control-Allow-Methods: POST");
}
/* ****** END ugly CORS hack ****** */
//================================================================================
// Additional extractor-specific scripts
//================================================================================
include_once 'apps/facebook.php';