I am making my first attempt (so go easy on me) at writing a custom snippet using xPDO which is basically converting a php/mysql script that was fairly raw but functional. The intent is to enable an android device to upload raw csv log data to the resource referencing the snippet below and adding the raw log data to a custom db. I have already created the tables and schema and tested them to make sure I can read. Now I'm to the point of writing the upload log file snippet.
My first question is if this snippet is called from an anonymous user, how could the security be handled? Would it be safer to create a separate context for this that permits anonymous users access to only this resource/snippet? The data does pass device IDs that I could query and match against a pre-defined list to allow only certain IDs to post data. While this isn't the greatest security, it will at least be obscurity;)
Secondly, my ported snippet is throwing a 500 error (I'm on modxcloud and no server errors, thus attempting modx->log entries and returns. The snippet code is:
<?php
$path = MODX_CORE_PATH . 'components/torque-web/';
$result = $modx->addPackage('torque-web',$path . 'model/','torque_');
if (! $result) {
$modx->log(xPDO::LOG_LEVEL_ERROR, '[upLoadLogs] failed to add package!'); return "Script failed";
}
else {
// get all the fields in the raw_logs and set to db fields
$dbcols = $xpdo->getFields('RawLogs');
$count = count($dbcols);
// get all the fields in the db
if ($count > 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$dbfields[]=($row['Field']);
}
}
else { $modx->log(xPDO::LOG_LEVEL_ERROR, '[upLoadLogs] no fields found in RawLogs!'); return "Script failed"; }
// check through the k* _REQUEST arguments to make sure there's a field to insert into
foreach ($_REQUEST as $key => $value) {
$keys[] = $key;
if (preg_match("/^k/", $key)) {
$values[] = $value;
} else {
$values[] = "'".$value."'";
}
if (!in_array($key, $dbfields)) {
// if the field doesn't exist, alter the table to add it.
$manager->addField('RawLogs', '$key');
}
}
if ((! $keys) && (! $values)) {$modx->log(xPDO::LOG_LEVEL_ERROR, '[upLoadLogs] keys and/or values arrays are empty!'); return "Script failed"; }
// we have 2 arrays, the fields($keys) and the data($values) so throw them into the database.
$logData = array_combine($keys, $values);
$myLog = $xpdo->newObject('Log',array($logData));
// torque expects the page to return OK! so this should be the only output
if ($$myLog->save() == false) {
$modx->log(xPDO::LOG_LEVEL_ERROR, '[upLoadLogs] Log file save failed!'); return "Script failed"; }
}
else {
return "OK!";
}
}
Again, this is my first xPDO attempt. I'm sure I'm missing something.
TIA