<?php
/**
 * Phoebe pedagogic planner
 *
 * PHP version 5
 *
 * LICENSE: The GNU General Public License (GPL), version 2. See LICENSE.txt
 *
 * Copyright (c) 2006-2008 JISC/HEFCE/University of Oxford
 *
 * @author      David Balch <david.balch@conted.ox.ac.uk>
 * @license     http://opensource.org/licenses/gpl-license.php GPL2
 * @link        http://phoebe-project.conted.ox.ac.uk/
 */


function sanitize($vals, $recursive = true) {
    // Sanitise passed data array
    $goodVals = true;
    $cleanVals = array();

    //echo "vals: ";
    //print_r($vals);

    foreach ($vals as $key=>$value) {
        if (gettype($val) == "array" && $recursive) {
            $cleanVals[$key] = sanitize($value);
        } else {
            switch ($key) {
                case "desId":
                case "field_type":
                case "clone_of":
                case "parent_design_id":
                case "parent_property_id":
                case "refType":
                case "type":
                    //echo '['.$value.'='.ctype_digit($value).']<br/>';
                    if (ctype_digit($value) || is_int($value) || $value == '') {
                        $cleanVals[$key] = $value;
                    } else {
                        //echo "hey: ".$key.": ".$value."<br/>";
                        $goodVals = false;
                    }
                    break;
                case "first_child_id":
                case "is_template":
                case "ref_id":
                case "root_item":
                case "multiplicity":
                case "next_sibling_id":
                case "prop_id":
                    if (ctype_digit($value)) {
                        $cleanVals[$key] = $value;
                    }
                    break;
                case "description":
                case "title":
                case "uri":
                    if ($value != '') {
                        $cleanVals[$key] = $value;
                    } else {
                        $goodVals = false;
                    }
                    break;
                case "value":
                    $cleanVals[$key] = $value;
                    break;
            }
        }
    }

    if($goodVals) {
        return $cleanVals;
    } else {
        return false;
    }
}

function addDesign($vals) {
    global $mdb2, $user_id;
    $cleanVals = sanitize($vals);

    //echo '$cleanVals: ';
    //print_r($cleanVals);

    if($cleanVals) {
        if($cleanVals["is_template"] != 1) {
            $cleanVals["is_template"] = 0;
        }
        // Insert data into the database
        $now = $mdb2->quote(date('Y-m-d H:i:s'));
        $values = $user_id.', '.$now.', '.$now.', '.
                  $mdb2->quote($cleanVals["is_template"]).', '.
                  $mdb2->quote($cleanVals["title"]).', '.
                  $mdb2->quote($cleanVals["description"]);

        $sql = 'INSERT INTO designs (owner_id, created, modified, is_template, title, description) '.
               'VALUES ('.$values.')';
        //echo $sql.'<br><br>';
        $insert = $mdb2->exec($sql);

        // Always check that result is not an error
        if (PEAR::isError($insert)) {
            $result = 'Error saving new design - '.$insert->getMessage();
        } else {
            // Get the new design id
            $newDesignId = $mdb2->lastInsertID();
            $result = $newDesignId;
        }
    } else {
        $result = 'Error creating new property - invalid parameters.';
    }

    return $result;
}


function addProp($vals) {
    global $mdb2;
    //print_r($vals);
    $cleanVals = sanitize($vals);

    //echo '$cleanVals: ';
    //print_r($cleanVals);

    if($cleanVals) {
        /* Not sure if this is needed.
        if(!isset($cleanVals['parent_design_id'])) {
            $cleanVals['parent_design_id'] = $cleanVals['desId'];
        }*/

        // Insert data into the database
        $values = $mdb2->quote($cleanVals['parent_design_id']).', '.
                  $mdb2->quote($cleanVals['root_item']).', '.
                  $mdb2->quote($cleanVals['title']).', '.
                  $mdb2->quote($cleanVals['field_type']).', '.
                  $mdb2->quote($cleanVals['multiplicity']).', '.
                  $mdb2->quote($cleanVals['value']).', '.
                  $mdb2->quote($cleanVals['first_child_id']).', '.
                  $mdb2->quote($cleanVals['next_sibling_id']).', '.
                  $mdb2->quote($cleanVals['clone_of']);
        //print_r($values);

        $sql = 'INSERT INTO properties (parent_design_id, root_item, title, field_type, multiplicity, value, first_child_id, next_sibling_id, clone_of) '.
               'VALUES ('.$values.')';
        //echo $sql;

        $insert = $mdb2->queryAll($sql);
        if (PEAR::isError($insert)) {
            $result = 'Error saving new property - '.$insert->getMessage();
        } else {
            // Update design modified date
            desModified($cleanVals['parent_design_id']);
            // Get the new property id
            $newPropId = $mdb2->lastInsertID();
            $result = $newPropId;
        }
    } else {
        $result = 'Error creating new property - invalid parameters:<br/>';
        $result .= ' $vals: ';
        $result .= '<br/>';
        foreach ($vals as $key=>$val) {
            $result .= '___'.$key.' = '.$val.'<br/>';
        }
    }

    return $result;
}

function updateProp($field, $vals) {
    global $mdb2;

    $cleanVals = sanitize($vals);

    if($cleanVals) {
        // Update property
        $sql = 'UPDATE properties'.
               ' SET '.$field.' = '.$mdb2->quote($cleanVals['value']).
               ' WHERE prop_id = '.$cleanVals['prop_id'];
        //echo $sql;

        $update = $mdb2->queryAll($sql);
        if (PEAR::isError($update)) {
            $result = 'Error updating property - '.$update->getMessage();
        } else {
            // Update design modified date
            //TODO: desModified($cleanVals['parent_design_id']);
            $result = $cleanVals['value'];
        }
    } else {
        $result = 'Error updating property - invalid parameters.';
    }

    return $result;
}

function addRef($vals) {
    global $mdb2;

    $cleanVals = sanitize($vals);

    if($cleanVals) {
        // Get Insert new reference
        $sql = 'INSERT INTO refs (parent_design_id, parent_property_id, type, uri) '.
               'VALUES ('.$mdb2->quote($cleanVals['parent_design_id']).', '.
                          $mdb2->quote($cleanVals['parent_property_id']).', '.
                          $mdb2->quote($cleanVals['type']).', '.
                          $mdb2->quote($cleanVals['uri']).
                        ')';
        //echo $sql;

        $insert = $mdb2->queryAll($sql);
        if (PEAR::isError($insert)) {
            $result = 'Error saving new reference - '.$insert->getMessage();
        } else {
            // Get the new property id
            $newRefId = $mdb2->lastInsertID();
            $result = $newRefId;

            // Update design modified date
            desModified($cleanVals['parent_design_id']);
        }
    } else {
        $result = 'Error creating new reference - invalid parameters.';
    }

    return $result;
}

function updateRef($vals) {
    global $mdb2;

    $cleanVals = sanitize($vals);

    if($cleanVals) {
        // TODO: Lookup reference
        $refExists = true;

        if($refExists) {
            // Update reference
            $sql = 'UPDATE refs'.
                   ' Set uri = '.$mdb2->quote($cleanVals['uri']).
                   ' WHERE ref_id = '.$cleanVals['ref_id'];
            //echo $sql;

            $update = $mdb2->queryAll($sql);
            if (PEAR::isError($update)) {
                $result = 'Error updating reference - '.$update->getMessage();
            } else {
                // Update design modified date
                //TODO: desModified($cleanVals['parent_design_id']);
                $result = $cleanVals['uri'];
            }
        }
    } else {
        $result = 'Error updating reference - invalid parameters.';
    }

    return $result;
}

function desModified($design_id) {
    global $mdb2;
    // Update the modified field on the design
    $sql = 'UPDATE designs'.
           ' SET modified = '.$mdb2->quote(date('Y-m-d H:i:s')).
           ' WHERE design_id = '.$design_id;
    //echo $sql;

    $update = $mdb2->queryAll($sql);
    if (PEAR::isError($update)) {
        $result = 'Error updating modified date - '.$update->getMessage();
    } else {
        $result = 'updated';
    }
    //echo $result;
}
?>