<?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/
 */

// output an HTML table of an array's contents
function printTableFromArray($array) {
    print(tableFromArray($array));
}
function tableFromArray($array, $recursive = true) {
    if ($array) {
        // Start at the beginning
        reset($array);

        // Table opening HTML
        $str = "<table border=\"1\"><thead><tr>  <th>Key</th><th>Value</th></tr></thead><tbody>";

        // For every key/value pair in the array, add a table row
        while (list($key, $val) = each($array)) {
                $str .= "  <tr><td>$key</td>";
                $str .= "<td>";
                if (gettype($val) == "array" && $recursive) {
                    $str .= tableFromArray($val);
                } else {
                    $str .= $val;
                }
                $str .= "</td></tr>\n";
        }

        // Table closing HMTL
        $str .= "</tbody></table>\n\n";

        return $str;
    }
}

function importDesignFile($filename) {
    global $newDesignId;
    // Unserialize XML design to objects
    require_once 'XML/Unserializer.php';
    // An array of serializer options
    $unserializer_options = array (
        'returnResult' => true,
        'tagMap' => array('item'=>''),
    );
    // Instantiate the serializer with the options
    $Unserializer = &new XML_Unserializer($unserializer_options);

    // Serialize the data structure
    $design = $Unserializer->unserialize($filename, true);

    if (PEAR::isError($design)) {
        return "Couldn't load XML: ".$design->getMessage();
    } else {
        $design = $Unserializer->getUnserializedData();
        //print_r($design);

        if ($design['designInfo']) {
            // Insert data into the database
            include_once($_SERVER['DOCUMENT_ROOT'].'/db/addFuncts.php');
            $newDesignId = addDesign($design['designInfo']);
    
            $propIdUpdates = array();
            foreach($design['props']['children'] as &$value) {
                //$content['main'] .= $key." ".$value;
                // Clone all properties
                cloneProp($value);
            }
            foreach($design['props']['children'] as &$value) {
                // Update all property ids
                updatePropRelations($value);
            }
    
            if(ctype_digit($newDesignId)) {
                return true;
            }
        } else {
            return "Didn't recognise file.";
        }
    }
}

function designSummary($design) {
    $designActions = "\n".'<div class="desActions">Actions: '.designActionButtons($design);
    $designActions .= '</div>';

    if($design['openid'] != '') {
        $dispLogin = $design['openid'];
    } else {
        $dispLogin = $design['login_name'];
    }

    $designMetaInfo = '<dl class="hidden desMeta" id="info_'.$design['design_id'].'">
                            <dt>Author</dt>
                            <dd>'.$design['fullname'].' ('.$dispLogin.')</dd>
                            <dt>Created</dt>
                            <dd>'.$design['created'].'</dd>
                            <dt>Modified</dt>
                            <dd>'.$design['modified']."</dd>\n</dl>\n";

    $designBlock = '<div class="desSummary">'.$designActions;

    $designBlock .= '<h3>'.designLinkOrTitle($design).'</h3>';

    $designBlock .= '<div class="desDesc">'.$design['description'].'</div>';
    $designBlock .= $designMetaInfo;
    $designBlock .= '<div class="clear"></div></div>';
    
    return $designBlock;
}

function designLinkOrTitle($design) {
    global $user_id;
    if ($_SERVER['SCRIPT_NAME'] == '/templates.php') {
        if($design['owner_id'] == $user_id) {
            $text = '<a href="/editDesignStructure.php?design_id='.$design['design_id'].'" title="Edit this template">'.$design['title'].' <img src="/inc/img/spanner.gif" alt="Edit this template" height="16" width="16"></a>';
        } else {
            $text = '<a href="/view/viewDesign.php?design_id='.$design['design_id'].'" title="View this template">'.$design['title'].' <img src="/inc/img/view.gif" width="16" height="16" alt="View this template"/></a> ';
        }
    } else if ($_SERVER['SCRIPT_NAME'] == '/designs.php') {
        $text = '<a href="/editDesign.php?design_id='.$design['design_id'].'" title="Edit this design">'.$design['title'].' <img src="/inc/img/edit.gif" alt="Edit this design" height="16" width="16"></a>';
    } else {
        $text = '<a href="/view/viewDesign.php?design_id='.$design['design_id'].'" title="View this design">'.$design['title'].' <img width="16" height="16" src="/inc/img/view.gif" alt="View design"/></a>';
    }

    return $text;
}

function designActionButtons($design) {
    global $mdb2, $user_id;
    if($design['is_template']) {
        $desOrTemp = 'template';
    } else  {
        $desOrTemp = 'design';
    }

    $buttons = '<a href="#" onclick="toggleDisplay(\'info_'.$design['design_id'].'\'); return false;" title="More information"><img src="/inc/img/info.gif" alt="Information" height="16" width="16"></a> ';
    if($design['is_template']) {
        if ($design['owner_id'] == $user_id) {
            $buttons .= '<a href="/editDesignStructure.php?design_id='.$design['design_id'].'"><img src="/inc/img/spanner.gif" alt="Edit this template" title="Edit this template" height="16" width="16"></a> ';
        } else {
            $buttons .= '<a href="/view/viewDesign.php?design_id='.$design['design_id'].'"><img width="16" height="16" src="/inc/img/view.gif" alt="View template" title="View template"/></a> ';
        }
        $buttons .= '<a href="/createDesign.php?isTemplate=1&amp;clone='.$design['design_id'].'"><img src="/inc/img/clone.gif" alt="Clone" title="Clone this template" height="16" width="16"></a> ';
        $buttons .= '<a href="/createDesign.php?newFromTemplate=1&amp;clone='.$design['design_id'].'"><img src="/inc/img/new.gif" alt="New" title="Create a design based on this template" height="16" width="16"></a> ';
    } else {
        if ($design['owner_id'] == $user_id) {
            $buttons .= '<a href="/editDesign.php?design_id='.$design['design_id'].'"><img src="/inc/img/edit.gif" alt="Edit" title="Edit this design" height="16" width="16"></a> ';
        }
        $buttons .= '<a href="/view/viewDesign.php?design_id='.$design['design_id'].'" title="View this design"><img width="16" height="16" src="/inc/img/view.gif" alt="View design" title="View design"/></a> ';
        if ($user_id) {
            $buttons .= '<a href="/createDesign.php?clone='.$design['design_id'].'"><img src="/inc/img/clone.gif" alt="Clone" title="Clone this design" height="16" width="16"></a> ';
        }
    }

    if ($design['owner_id'] == $user_id) {
        $buttons .= '<a href="/deleteDesign.php?design_id='.$design['design_id'].'"><img src="/inc/img/del.gif" alt="Delete" title="Delete this '.$desOrTemp.'" height="16" width="16"></a> ';

        // Get share levels
        $sql = 'SELECT * FROM share_types';
        $share_types = $mdb2->queryAll($sql);
        if (PEAR::isError($field_types)) {
            echo ($field_types->getMessage());
        }
        $shareSelect = '<br>Access: <select id="share_level_'.$design['design_id'].'" name="share_level_'.$design['design_id'].'" onchange="setDes(this);" title="Set the access rights for this '.$desOrTemp.'">';
        foreach($share_types as $type) {
            $shareSelect .= ' <option title="'.$type['description'].
                             '" value="'.$type['share_type_id'].'"';
            if ($design['share_level'] == $type['share_type_id']) {
                $shareSelect .= ' selected="selected"';
            }
            $shareSelect .= '>'.$type['share_type_name'].'</option>';
        }
        $shareSelect .= '</select>';
        $shareSelect .= '<a href="/licensing.php"><img src="/inc/img/qmark.gif" alt="" title="Access/licensing information" width="16" height="16"/></a>';
        $buttons .= $shareSelect;

        // Get rights types
        /*
        $sql = 'SELECT * FROM right_types';
        $share_types = $mdb2->queryAll($sql);
        if (PEAR::isError($field_types)) {
            echo ($field_types->getMessage());
        $licenseSelect = '<br>License: <select disabled="disabled" id="rights_type_'.$design['design_id'].'" name="rights_type_'.$design['design_id'].'" onchange="setDes(this);">';
        foreach($rights_types as $type) {
            $licenseSelect .= ' <option title="'.$type['description'].
                             '" value="'.$type['rights_type_id'].'"';
            if ($design['rights'] == $type['rights_type_id']) {
                $licenseSelect .= ' selected="selected"';
            }
            $licenseSelect .= '>'.$type['rights_type_name'].'</option>';
        }
        $licenseSelect .= '</select>';
        $buttons .= $licenseSelect;*/
    }
    //print_r($design);
    if($design['is_template']) {
        if ($_SESSION['userprefs']['pref_default_template_id'] == $design['design_id']) {
            $defaultSelect = ' checked="checked"';
        }
        $buttons .= '<br>Default template: <input type="radio" name="pref_default_template_id" onclick="setPref(this);" value="'.$design['design_id'].'" '.$defaultSelect.'>';
    }

    return $buttons;
}

/* Password functions */
function setPassword($user_id, $plainText) {
    global $mdb2;
    $pSalt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
    $pHash = generateHash($plainText);

    $sql = 'UPDATE users'.
           ' SET password_hash = '.$mdb2->quote($pHash).
           ', confirmation_code = NULL'.
           ' WHERE user_id = '.$mdb2->quote($user_id);
    //echo $sql.'<br><br>';
    $insert = $mdb2->exec($sql);

    // Always check that result is not an error
    if (PEAR::isError($insert)) {
        die ('Error resetting password - '.$insert->getMessage());
    } else {
        return true;
    }
    
}

define('SALT_LENGTH', 9);
function generateHash($plainText, $salt = null) {
    if ($salt === null) {
        $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
    } else {
        $salt = substr($salt, 0, SALT_LENGTH);
    }
    return $salt . sha1($salt . $plainText);
}

function prefsToSession() {
    global $CNF, $mdb2;
    if ($_SESSION['userid']) {
        // User logged in, so load prefs into session.
        $sql = 'SELECT pref_show_des_start_page, pref_show_email, pref_default_template_id FROM users'.
               ' WHERE user_id = '.$mdb2->quote($_SESSION['userid']);
        //echo $sql;

        $userPrefs = $mdb2->queryRow($sql);
        if (PEAR::isError($userPrefs)) {
            die('Error accessing database - '.$userPrefs->getMessage());
        } else {
            foreach ($userPrefs as $key => $value) {
                $_SESSION['userprefs'][$key] = $value;
            }
            if ($_SESSION['userprefs']['pref_default_template_id'] == '') {
                $_SESSION['userprefs'][$key] = $CNF->defaultTemplate;
            }
        }
    }
}
?>