/**
  * add an exercise with id.
  *
  * @param string $session_id    current session
  * @param int $target_id refid of parent in repository
  * @param string $exercise_xml   qti xml description of test
  *
  * @return int reference id in the tree, 0 if not successful
  */
 function addExercise($sid, $target_id, $exercise_xml)
 {
     $this->initAuth($sid);
     $this->initIlias();
     if (!$this->__checkSession($sid)) {
         return $this->__raiseError($this->__getMessage(), $this->__getMessageCode());
     }
     global $rbacsystem, $tree, $ilLog;
     if (!($target_obj =& ilObjectFactory::getInstanceByRefId($target_id, false))) {
         return $this->__raiseError('No valid target given.', 'Client');
     }
     if (ilObject::_isInTrash($target_id)) {
         return $this->__raiseError("Parent with ID {$target_id} has been deleted.", 'CLIENT_OBJECT_DELETED');
     }
     // Check access
     $allowed_types = array('cat', 'grp', 'crs', 'fold', 'root');
     if (!in_array($target_obj->getType(), $allowed_types)) {
         return $this->__raiseError('No valid target type. Target must be reference id of "course, group, category or folder"', 'Client');
     }
     if (!$rbacsystem->checkAccess('create', $target_id, "exc")) {
         return $this->__raiseError('No permission to create exercises in target  ' . $target_id . '!', 'Client');
     }
     // create object, put it into the tree and use the parser to update the settings
     include_once './Modules/Exercise/classes/class.ilObjExercise.php';
     include_once './Modules/Exercise/classes/class.ilExerciseXMLParser.php';
     include_once './Modules/Exercise/classes/class.ilExerciseException.php';
     $exercise = new ilObjExercise();
     $exercise->create();
     $exercise->createReference();
     $exercise->putInTree($target_id);
     $exercise->setPermissions($target_id);
     $exercise->saveData();
     // we need this as workaround because file and member objects need to be initialised
     $exercise->read();
     $exerciseXMLParser = new ilExerciseXMLParser($exercise, $exercise_xml);
     try {
         if ($exerciseXMLParser->start()) {
             $exerciseXMLParser->getAssignment()->update();
             return $exercise->update() ? $exercise->getRefId() : -1;
         }
         throw new ilExerciseException("Could not parse XML");
     } catch (ilExerciseException $exception) {
         return $this->__raiseError($exception->getMessage(), $exception->getCode() == ilExerciseException::$ID_MISMATCH ? "Client" : "Server");
     }
 }