<?php
# ************** LICENCE ****************
/*
	Copyright (c) PORTANEO.

	This file is part of POSH (Portaneo Open Source Homepage) http://sourceforge.net/projects/posh/.

	POSH is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version

	POSH is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Posh.  If not, see <http://www.gnu.org/licenses/>.
*/
/*

 Tasks module PHP scripts
ALTER TABLE users_tasks_id ADD COLUMN tasklistname varchar(255);

 !! be careful, this file must be saved under uft8 format, and display an e accentuated here : é
 ***************************************
*/

header("content-type: application/xml"); 
$folder="";
$not_access=0;
$pagename="modules/wid_tasks.php";
$granted="I,N";
//includes
require_once('includes.php');
require_once('../includes/xml.inc.php');

$file=new xmlFile();

$file->header("channel");

$act = isset($_POST["act"])?$_POST["act"]:"";
$shareditemkey = isset($_POST["shareditemkey"])?$_POST["shareditemkey"]:"";
$acceptwriteshare = isset($_POST["acceptwriteshare"])?$_POST["acceptwriteshare"]:"";
$sharedMD5 = isset($_POST["shareditemkey"])?$_POST["shareditemkey"]:"";
$tasklistid = isset($_POST["modid"]) ? $_POST["modid"] : 0;

/*
    delete task
*/
if ($act=="sup" && isset($_SESSION['user_id']))
{
	$moduleid=$_POST["modid"];
    $tasklistid = isset($_POST["modid"]) ? $_POST["modid"] : 0;
	$DB->execute($widtask_RemoveTask,
                        $DB->escape($_POST["taskid"]),
                        $DB->escape($_SESSION['user_id'])
                      );
	if ($DB->nbAffected()==0)
	{
		$DB->execute($widtask_createNewId,
                        $DB->escape($_SESSION['user_id'])
                    );
		$oldid=$moduleid;
		$tasklistid=$DB->getId();
		$DB->execute($widtask_copyTasks,
                        $tasklistid,
                        $DB->escape($oldid),
                        $DB->escape($_POST["taskid"])
                    );
		//echo '<ret>'.$tasklistid.'_'.($DB->getId()).'</ret>';
   
	}
  //  echo '<ret>'.$tasklistid.'_'.($DB->getId()).'</ret>';
    echo '<sharedkey>'.$sharedMD5.'</sharedkey>';
    echo '<tasklistid>'.$tasklistid.'</tasklistid>';         
}
/*
        add a new task
        
        connection required
*/
if ($act=="add"  && isset($_SESSION['user_id']))
{
	$tasklistid = isset($_POST["modid"]) ? $_POST["modid"] : 0;
	$taskid     = isset($_POST["taskid"]) ? $_POST["taskid"] : 0;
    /*
                Add a new list of tasks in database, if tasklistid == 0
                where modid is id of the list of tasks see table users_task_id
    
    */
	if ($tasklistid==0)
	{
		$sharedMD5 = md5(uniqid(rand(), true));
        //create new entry for each new task
		$DB->execute($widtask_addNewTaskId2,
                    $DB->escape($_SESSION['user_id']),
                    $DB->quote($sharedMD5)
                    );
		$tasklistid=$DB->getId();
		$DB->execute($widtask_addNewTask,
                        $DB->escape($tasklistid),
                        $DB->noHTML($_POST["cat"]),
                        $DB->noHTML($_POST["name"]),
                        $DB->quote($sharedMD5)
                        );         
	}
	else
	{
    /*
    
            add new task on an existing task list which is owned by user or shared by another user
            must update rights
            
    */
    $sharedMD5 = isset($_POST["shareditemkey"])?$_POST["shareditemkey"]:"";
    $userid_owner = $_SESSION['user_id'];
    //$shareditemkey
    //must get task_id datas to obtain rights datas 

        if ($acceptwriteshare && $acceptwriteshare == 'yes') {
            $DB->getResults($widtask_getinfo, $DB->escape($tasklistid) );
            $oldjsonacl = '';
            if ($DB->nbResults()>0) {
                while ($row = $DB->fetch(0)) {
                    $userid_owner = $row['user_id'];
                }
                $DB->freeResults();
            }
            if ($userid_owner != $_SESSION['user_id']) {
                echo "<createdby>another</createdby>";
            } else {
                echo "<createdby>myself</createdby>";
            }
        }

        /*
                    case where a list of task exists
        
        */
		if ($taskid == 0)
		{
            //add a new task only if user_id == user_id who created list of tasks
            //must be changed if you want to share widget enterely
            //then entry is updated and there is
            /*
                            insert from a select
                            In case someone want to add a task on a list without authorization
            */
			$DB->execute($widtask_addNewTaskOnExistingMod,
                                            $DB->escape($tasklistid),
                                            $DB->noHTML($_POST["cat"]),
                                            $DB->noHTML($_POST["name"]),
                                            $DB->escape($tasklistid),
                                            $DB->escape($userid_owner)
                                            );                           
		}
		else
		{
            //update task only if user_id == user_id who created list of tasks
            //must be changed if want to share widget enterely
            //then entry is updated and there is            
			$DB->execute($widtask_updateTask,
                                    $DB->noHTML($_POST["name"]),
                                    $DB->noHTML($_POST["cat"]),
                                    $taskid,
                                    $DB->escape($userid_owner)
                                    );
		}
        
        //nbAffected is different of 0 only if updating
		if ($DB->nbAffected()==0)
		{
			$sharedMD5 = md5(uniqid(rand(), true));
            
            //in all case create a new list of tasks
            
			$DB->execute($widtask_createNewModule,
                            $DB->escape($_SESSION['user_id']),
                            $DB->quote($sharedMD5)
                            );
                                
			$oldtasklistid=$tasklistid;
			$tasklistid=$DB->getId();
            
			$DB->execute($widtask_insertExistingTasks,
                                        $tasklistid,
                                        $DB->escape($oldtasklistid)
                                  );
			if ($taskid==0)
			{
				$DB->execute($widtask_newModInsertTask,
                                            $DB->escape($tasklistid),
                                            $DB->noHTML($_POST["cat"]),
                                            $DB->noHTML($_POST["name"])
                            );        
			}
			else
			{
				$DB->execute($widtask_newModUpdateTask,
                                        $DB->noHTML($_POST["name"]),
                                        $DB->noHTML($_POST["cat"]),
                                        $DB->escape($tasklistid)
                            );
			}
             $taskid = $DB->getId();
		}
	}
    if (!$taskid) {
        $taskid = $DB->getId();
    }
    echo '<sharedkey>'.$sharedMD5.'</sharedkey>';
	echo '<ret>'.$tasklistid.'_'.$taskid.'</ret>';
    echo '<tasklistid>'.$tasklistid.'</tasklistid>';
    echo '<newtaskid>'.$taskid.'</newtaskid>';
}
if ($act=="done" && isset($_SESSION['user_id']))
{
    $tasklistid = isset($_POST["modid"]) ? $_POST["modid"] : 0;
	$DB->execute($widtask_changeStatus,
                            $DB->noHTML($_POST["val"]),
                            $DB->escape($_POST["taskid"])
                    );
  //  echo '<ret>'.$tasklistid.'_'.$taskid.'</ret>';
    echo '<sharedkey>'.$sharedMD5.'</sharedkey>';
    echo '<tasklistid>'.$tasklistid.'</tasklistid>';
}
if ($act == 'init')
{
	$sharedMD5 = md5(uniqid(rand(), true));
	
	//create new entry
	$DB->execute($widtask_addNewTaskId2,
				$DB->escape($_SESSION['user_id']),
				$DB->quote($sharedMD5)
				);

	echo '<sharedkey>' . $sharedMD5 . '</sharedkey>';
    echo '<tasklistid>' . $DB->getId() . '</tasklistid>';
}

if ($act=="get")
{
	$tasklistid=isset($_POST["modid"]) ? $_POST["modid"] : 0;
    $sharedmd5key=isset($_POST['sharedmd5key'])?$_POST['sharedmd5key']:'';
    $widgetid = isset($_POST['widgetid'])?$_POST['widgetid']:0;
    
    //get a task
    if (isset($_SESSION['user_id'])) {
        if( (empty($sharedmd5key))
        || (!isset($sharedmd5key)) 
        || ($sharedmd5key=='undefined') ) {
            echo "<createdby>myself</createdby>";
            $DB->getResults($wid_getTasks,
                                $DB->escape($tasklistid),
                                $DB->escape($_SESSION['user_id'])
                           );      
        }
        else {
            $DB->getResults($wid_getTasksShared,
                                $DB->quote("%taskid=".$DB->escape($tasklistid)."%"),
                                $DB->quote($sharedmd5key),
                                $DB->escape($_SESSION['user_id']),
                                $DB->escape($widgetid),
                                $DB->escape($tasklistid)
                            );          
        }
        $inc=0;
        while ($row = $DB->fetch(0)){
            echo '<task>';
            echo '<task_id>'.$row["task_id"].'</task_id>';
            echo '<name><![CDATA['.$row["name"].']]></name>';
            echo '<comments><![CDATA['.$row["comments"].']]></comments>';
            echo '<done><![CDATA['.$row["done"].']]></done>';
            echo '</task>';
            $inc++;
        }
        $DB->freeResults();
    } else {
        echo "<createdby>another</createdby>";
		$shareditemkey = isset($_POST["shareditemkey"])?$_POST["shareditemkey"]:"";
        $DB->getResults($wid_getTasksSharedKey,
							$DB->quote($shareditemkey),
							$DB->escape($tasklistid)
                            );
		$inc=0;
        while ($row = $DB->fetch(0)){
            echo '<task>';
            echo '<task_id>'.$row["task_id"].'</task_id>';
            echo '<name><![CDATA['.$row["name"].']]></name>';
            echo '<comments><![CDATA['.$row["comments"].']]></comments>';
            echo '<done><![CDATA['.$row["done"].']]></done>';
            echo '</task>';
            $inc++;
        }
        $DB->freeResults();
	}
    // if ($tasklistid == 0) {
        // getOldTaskList($DB);
    // }
}
    
$DB->close();

$file->status("1");

$file->footer();

/*
    getNewACL
    
     add or update acl on that widget
     
     return json string
    

*/
function getNewACL ($acl,$aclrights) {
    $network = isset($_REQUEST["network"])?$_REQUEST["network"]:0;
    $world = isset($_REQUEST["world"])?$_REQUEST["world"]:0;
    $aclarray = $aclrights;

    if ($network == 1) {
        $acl->addRight($aclrights,'write','ago');
        $acl->addRight($aclrights,'read','ago');
    } else {
        $acl->removeRight($aclrights,'write','ago');
        $acl->removeRight($aclrights,'read','ago');
    }
    if ($world == 1) {
        $acl->addRight($aclrights,'write','ao');
        $acl->addRight($aclrights,'read','ao');
    } else {
        $acl->removeRight($aclrights,'write','ao');
        $acl->removeRight($aclrights,'read','ao');
    }    
    $acl->addDefaultRights($aclrights);    
    return $acl->encodeJson();        
} 

/*
    getDefaultRights
    
    get array of rights for that widget

*/
function getDefaultRights () {
    return array(
            'read'=> array('auo'=>$_SESSION['user_id'],
                            'ago'=>0,
                            'ag'=>array(),
                            'au'=>array(),
                            'ao'=>0,
                            'am'=>0),
            'write'=> array('auo'=>$_SESSION['user_id'],
                            'ago'=>0,
                            'ag'=>array(),
                            'au'=>array(),
                            'ao'=>0,
                            'am'=>0)
            );
}

// function getOldTaskList ($DB) {
    // global $widtask_getOldLists;
    // $DB->getResults($widtask_getOldLists,
                                // $DB->escape($_SESSION['user_id'])
                           // );
    // if ($DB->nbResults()>0) {
        // echo "<tasklists>";
        // while ($row = $DB->fetch(0)) {
            // //status,shared,tasklistname
            // $id = $row['id'];
            // $status = $row['status'];
            // $shared = $row['shared'];
            // $tasklistname = $row['tasklistname'];
            // echo "<tasklist>";
            // echo "<tasklistid>$id</tasklistid>";
            // echo "<shared><![CDATA[$shared]]></shared>";
            // echo "<tasklistname><![CDATA[$tasklistname]]></tasklistname>";
            // echo "</tasklist>";
        // }
        // echo "</tasklists>";
    // }

// }

?>