public function getStrings($values)
 {
     $contentStrings = array();
     $xmlTokenizer = new taoItems_models_classes_search_XmlItemContentTokenizer();
     foreach ($values as $valueUri) {
         $file = new core_kernel_file_File($valueUri);
         try {
             $content = file_get_contents($file->getAbsolutePath());
             if ($content === false) {
                 common_Logger::w('File ' . $file->getAbsolutePath() . ' not found for item');
             } else {
                 // Try to make it a DOM Document...
                 $dom = new DOMDocument('1.0', 'UTF-8');
                 if (@$dom->loadXML($content) === true) {
                     $contentStrings = array_merge($contentStrings, $xmlTokenizer->getStrings($dom));
                     unset($dom);
                 } else {
                     common_Logger::d('Skipped non XML content for ' . $file->getUri());
                 }
             }
         } catch (common_Exception $exc) {
             common_Logger::w('Invalid file ' . $valueUri . ' for ItemContentTokenizer: ' . $exc->getMessage());
         }
     }
     return $contentStrings;
 }
 /**
  * (non-PHPdoc)
  * @see tao_models_classes_export_ExportHandler::export()
  */
 public function export($formValues, $destination)
 {
     $file = null;
     if (isset($formValues['filename']) === true) {
         $instances = is_string($formValues['instances']) ? array($formValues['instances']) : $formValues['instances'];
         if (count($instances) > 0) {
             $fileName = $formValues['filename'] . '_' . time() . '.zip';
             $path = tao_helpers_File::concat(array($destination, $fileName));
             if (tao_helpers_File::securityCheck($path, true) === false) {
                 throw new common_Exception('Unauthorized file name for QTI Test ZIP archive.');
             }
             // Create a new ZIP archive to store data related to the QTI Test.
             $zip = new ZipArchive();
             if ($zip->open($path, ZipArchive::CREATE) !== true) {
                 throw new common_Exception("Unable to create ZIP archive for QTI Test at location '" . $path . "'.");
             }
             // Create an empty IMS Manifest as a basis.
             $manifest = taoQtiTest_helpers_Utils::emptyImsManifest();
             foreach ($instances as $instance) {
                 $testResource = new core_kernel_classes_Resource($instance);
                 $testExporter = new taoQtiTest_models_classes_export_QtiTestExporter($testResource, $zip, $manifest);
                 common_Logger::d('Export ' . $instance);
                 $testExporter->export();
             }
             $file = $path;
             $zip->close();
         } else {
             common_Logger::w("No instance in form to export");
         }
     } else {
         common_Logger::w("Missing filename for QTI Test export using Export Handler '" . __CLASS__ . "'.");
     }
     return $file;
 }
 public function isDeliveryExecutionAllowed(core_kernel_classes_Resource $delivery, User $user)
 {
     $userUri = $user->getIdentifier();
     if (is_null($delivery)) {
         common_Logger::w("Attempt to start the compiled delivery " . $delivery->getUri() . " related to no delivery");
         return false;
     }
     //first check the user is assigned
     if (!taoDelivery_models_classes_AssignmentService::singleton()->isUserAssigned($delivery, $user)) {
         common_Logger::w("User " . $userUri . " attempts to start the compiled delivery " . $delivery->getUri() . " he was not assigned to.");
         return false;
     }
     $settings = $this->getDeliverySettings($delivery);
     //check Tokens
     $usedTokens = count(taoDelivery_models_classes_execution_ServiceProxy::singleton()->getUserExecutions($delivery, $userUri));
     if ($settings[TAO_DELIVERY_MAXEXEC_PROP] != 0 and $usedTokens >= $settings[TAO_DELIVERY_MAXEXEC_PROP]) {
         common_Logger::d("Attempt to start the compiled delivery " . $delivery->getUri() . "without tokens");
         return false;
     }
     //check time
     $startDate = date_create('@' . $settings[TAO_DELIVERY_START_PROP]);
     $endDate = date_create('@' . $settings[TAO_DELIVERY_END_PROP]);
     if (!$this->areWeInRange($startDate, $endDate)) {
         common_Logger::d("Attempt to start the compiled delivery " . $delivery->getUri() . " at the wrong date");
         return false;
     }
     return true;
 }
Exemplo n.º 4
0
 public function send(Message $message)
 {
     $messageFile = $this->getFilePath($message->getTo());
     \common_Logger::d('Wrote message to ' . $messageFile);
     $written = file_put_contents($messageFile, $message->getBody());
     return $written !== false;
 }
Exemplo n.º 5
0
 public function testFileAppender()
 {
     $tfile = $this->createFile();
     $dfile = $this->createFile();
     $efile = $this->createFile();
     common_log_Dispatcher::singleton()->init(array(array('class' => 'SingleFileAppender', 'threshold' => common_Logger::TRACE_LEVEL, 'file' => $tfile), array('class' => 'SingleFileAppender', 'mask' => 2, 'file' => $dfile), array('class' => 'SingleFileAppender', 'threshold' => common_Logger::ERROR_LEVEL, 'file' => $efile)));
     common_Logger::singleton()->enable();
     common_Logger::t('message');
     $this->assertEntriesInFile($tfile, 1);
     $this->assertEntriesInFile($dfile, 0);
     $this->assertEntriesInFile($efile, 0);
     common_Logger::d('message');
     $this->assertEntriesInFile($tfile, 2);
     $this->assertEntriesInFile($dfile, 1);
     $this->assertEntriesInFile($efile, 0);
     common_Logger::e('message');
     $this->assertEntriesInFile($tfile, 3);
     $this->assertEntriesInFile($dfile, 1);
     $this->assertEntriesInFile($efile, 1);
     common_Logger::singleton()->disable();
     common_Logger::d('message');
     $this->assertEntriesInFile($tfile, 3);
     $this->assertEntriesInFile($dfile, 1);
     $this->assertEntriesInFile($efile, 1);
     common_Logger::singleton()->restore();
     common_Logger::d('message');
     $this->assertEntriesInFile($tfile, 4);
     $this->assertEntriesInFile($dfile, 2);
     $this->assertEntriesInFile($efile, 1);
     common_Logger::singleton()->restore();
 }
Exemplo n.º 6
0
 public function run(Task $task)
 {
     \common_Logger::d('Running task ' . $task->getId());
     $report = new \common_report_Report(\common_report_Report::TYPE_INFO, __('Running task %s', $task->getId()));
     $queue = $this->getServiceLocator()->get(Queue::CONFIG_ID);
     $queue->updateTaskStatus($task->getId(), Task::STATUS_RUNNING);
     try {
         $actionService = $this->getServiceLocator()->get(ActionService::SERVICE_ID);
         $invocable = $task->getInvocable();
         if (is_string($invocable)) {
             $invocable = $actionService->resolve($task->getInvocable());
         } else {
             if ($invocable instanceof ServiceLocatorAwareInterface) {
                 $invocable->setServiceLocator($this->getServiceLocator());
             }
         }
         $subReport = call_user_func($invocable, $task->getParameters());
         $report->add($subReport);
     } catch (\Exception $e) {
         $message = 'Task ' . $task->getId() . ' failed. Error message: ' . $e->getMessage();
         \common_Logger::e($message);
         $report = new \common_report_Report(\common_report_Report::TYPE_ERROR, $message);
     }
     $queue->updateTaskStatus($task->getId(), Task::STATUS_FINISHED, $report);
     return $report;
 }
Exemplo n.º 7
0
 /**
  * Load the extension.
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @param array $extraConstants
  * @return mixed
  */
 public function load($extraConstants = array())
 {
     if (!empty($extraConstants)) {
         throw new common_exception_Error('Loading extra constants in ' . __CLASS__ . ' nolonger supported');
     }
     common_Logger::t('Loading extension ' . $this->getExtension()->getId() . ' constants');
     // load the constants from the manifest
     if ($this->extension->getId() != "generis") {
         foreach ($this->extension->getConstants() as $key => $value) {
             if (!defined($key) && !is_array($value)) {
                 define($key, $value);
             }
         }
     }
     $constantFile = $this->getExtension()->getDir() . 'includes' . DIRECTORY_SEPARATOR . 'constants.php';
     if (file_exists($constantFile)) {
         //include the constant file
         include_once $constantFile;
         //this variable comes from the constant file and contain the const definition
         if (isset($todefine)) {
             foreach ($todefine as $constName => $constValue) {
                 if (!defined($constName)) {
                     define($constName, $constValue);
                     //constants are defined there!
                 } else {
                     common_Logger::d('Constant ' . $constName . ' in ' . $this->getExtension()->getId() . ' has already been defined');
                 }
             }
             unset($todefine);
         }
     }
 }
Exemplo n.º 8
0
 /**
  * @author "Lionel Lecaque, <*****@*****.**>"
  * @param string $namespace
  * @param string $data xml content
  */
 public function createModel($namespace, $data)
 {
     $modelId = $this->getModelId($namespace);
     if ($modelId === false) {
         common_Logger::d('modelId not found, need to add namespace ' . $namespace);
         $this->addNewModel($namespace);
         //TODO bad way, need to find better
         $modelId = $this->getModelId($namespace);
     }
     $modelDefinition = new EasyRdf_Graph($namespace);
     if (is_file($data)) {
         $modelDefinition->parseFile($data);
     } else {
         $modelDefinition->parse($data);
     }
     $graph = $modelDefinition->toRdfPhp();
     $resources = $modelDefinition->resources();
     $format = EasyRdf_Format::getFormat('php');
     $data = $modelDefinition->serialise($format);
     foreach ($data as $subjectUri => $propertiesValues) {
         foreach ($propertiesValues as $prop => $values) {
             foreach ($values as $k => $v) {
                 $this->addStatement($modelId, $subjectUri, $prop, $v['value'], isset($v['lang']) ? $v['lang'] : null);
             }
         }
     }
     return true;
 }
 /**
  * Manage permissions
  */
 protected function adminPermissions()
 {
     $resource = new \core_kernel_classes_Resource($this->getRequestParameter('id'));
     $accessRights = AdminService::getUsersPermissions($resource->getUri());
     $userList = $this->getUserList();
     $roleList = $this->getRoleList();
     $this->setData('privileges', PermissionProvider::getRightLabels());
     $userData = array();
     foreach (array_keys($accessRights) as $uri) {
         if (isset($userList[$uri])) {
             $userData[$uri] = array('label' => $userList[$uri], 'isRole' => false);
             unset($userList[$uri]);
         } elseif (isset($roleList[$uri])) {
             $userData[$uri] = array('label' => $roleList[$uri], 'isRole' => true);
             unset($roleList[$uri]);
         } else {
             \common_Logger::d('unknown user ' . $uri);
         }
     }
     $this->setData('users', $userList);
     $this->setData('roles', $roleList);
     $this->setData('userPrivileges', $accessRights);
     $this->setData('userData', $userData);
     $this->setData('uri', $resource->getUri());
     $this->setData('label', _dh($resource->getLabel()));
     $this->setView('AdminAccessController/index.tpl');
 }
Exemplo n.º 10
0
 /**
  * uninstall an extension
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @return boolean
  */
 public function uninstall()
 {
     common_Logger::i('Uninstalling ' . $this->extension->getId(), 'UNINSTALL');
     // uninstall possible
     if (is_null($this->extension->getManifest()->getUninstallData())) {
         throw new common_Exception('Problem uninstalling extension ' . $this->extension->getId() . ' : Uninstall not supported');
     }
     // installed?
     if (!common_ext_ExtensionsManager::singleton()->isInstalled($this->extension->getId())) {
         throw new common_Exception('Problem uninstalling extension ' . $this->extension->getId() . ' : Not installed');
     }
     // check dependcies
     if (helpers_ExtensionHelper::isRequired($this->extension)) {
         throw new common_Exception('Problem uninstalling extension ' . $this->extension->getId() . ' : Still required');
     }
     common_Logger::d('uninstall script for ' . $this->extension->getId());
     $this->uninstallScripts();
     // hook
     $this->extendedUninstall();
     common_Logger::d('unregister extension ' . $this->extension->getId());
     $this->unregister();
     // we purge the whole cache.
     $cache = common_cache_FileCache::singleton();
     $cache->purge();
     common_Logger::i('Uninstalled ' . $this->extension->getId());
     return true;
 }
 /**
  * 
  * @author Lionel Lecaque, lionel@taotesting.com
  * @param string $extName
  * @param string $file
  */
 public static function update($extName, $file)
 {
     $config = (require_once $file);
     $ext = common_ext_ExtensionsManager::singleton()->getExtensionById($extName);
     foreach ($config as $key => $value) {
         common_Logger::d('Set config ' . $key . ' for extension ' . $extName);
         $ext->setConfig($key, $value);
     }
 }
 /**
  * Builds a simple Diagram of the Process
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param  Resource process
  * @return string
  */
 public static function buildDiagramData(core_kernel_classes_Resource $process)
 {
     $returnValue = (string) '';
     common_Logger::i("Building diagram for " . $process->getLabel());
     $authoringService = wfAuthoring_models_classes_ProcessService::singleton();
     $activityService = wfEngine_models_classes_ActivityService::singleton();
     $connectorService = wfEngine_models_classes_ConnectorService::singleton();
     $activityCardinalityService = wfEngine_models_classes_ActivityCardinalityService::singleton();
     $activities = $authoringService->getActivitiesByProcess($process);
     $todo = array();
     foreach ($activities as $activity) {
         if ($activityService->isInitial($activity)) {
             $todo[] = $activity;
         }
     }
     $currentLevel = 0;
     $diagram = new wfAuthoring_models_classes_ProcessDiagram();
     $done = array();
     while (!empty($todo)) {
         $nextLevel = array();
         $posOnLevel = 0;
         foreach ($todo as $item) {
             $next = array();
             if ($activityService->isActivity($item)) {
                 // add this activity
                 $diagram->addActivity($item, 54 + 200 * $posOnLevel + 10 * $currentLevel, 35 + 80 * $currentLevel);
                 $next = array_merge($next, $activityService->getNextConnectors($item));
                 common_Logger::d('Activity added ' . $item->getUri());
             } elseif ($connectorService->isConnector($item)) {
                 // add this connector
                 $diagram->addConnector($item, 100 + 200 * $posOnLevel + 10 * $currentLevel, 40 + 80 * $currentLevel);
                 $next = array_merge($next, $connectorService->getNextActivities($item));
             } else {
                 common_Logger::w('unexpected ressource in process ' . $item->getUri());
             }
             //replace cardinalities
             foreach ($next as $key => $destination) {
                 if ($activityCardinalityService->isCardinality($destination)) {
                     // not represented on diagram
                     $next[$key] = $activityCardinalityService->getDestination($destination);
                 }
             }
             //add arrows
             foreach ($next as $destination) {
                 $diagram->addArrow($item, $destination);
             }
             $posOnLevel++;
             $nextLevel = array_merge($nextLevel, $next);
         }
         $done = array_merge($done, $todo);
         $todo = array_diff($nextLevel, $done);
         $currentLevel++;
     }
     $returnValue = $diagram->toJSON();
     return (string) $returnValue;
 }
Exemplo n.º 13
0
 /**
  * Connect to Dbal
  * 
  * @param string $id
  * @param array $params
  * @return \Doctrine\DBAL\Connection;
  */
 function connect($id, array $params)
 {
     common_Logger::d('Running Dbal Driver');
     $params['driver'] = str_replace('dbal_', '', $params['driver']);
     $config = new \Doctrine\DBAL\Configuration();
     //          $logger = new Doctrine\DBAL\Logging\EchoSQLLogger();
     //          $config->setSQLLogger($logger);
     $this->connection = \Doctrine\DBAL\DriverManager::getConnection($params, $config);
     return new common_persistence_SqlPersistence($params, $this);
 }
Exemplo n.º 14
0
 /**
  * (non-PHPdoc)
  * @see common_persistence_sql_SchemaManager::getSchemaManager()
  */
 public function getSchemaManager()
 {
     if ($this->schemaManager == null) {
         common_Logger::d('init dbal connection to get SchemaMangager');
         $config = new \Doctrine\DBAL\Configuration();
         $params = $this->getDriver()->getParams();
         $connection = \Doctrine\DBAL\DriverManager::getConnection($params, $config);
         $this->schemaManager = $connection->getSchemaManager();
     }
     return $this->schemaManager;
 }
Exemplo n.º 15
0
 public function __construct()
 {
     parent::__construct();
     if ($this->hasRequestParameter('standalone') && $this->getRequestParameter('standalone')) {
         tao_helpers_Context::load('STANDALONE_MODE');
         $this->isStandAlone = true;
         $this->setData('client_config_url', $this->getClientConfigUrl());
         common_Logger::d('Standalone mode set');
     } else {
         $this->isStandAlone = false;
     }
 }
Exemplo n.º 16
0
 public function send(Message $message)
 {
     $receiver = $message->getTo();
     $path = $this->getOption(self::CONFIG_FILEPATH) . \tao_helpers_File::getSafeFileName($receiver->getIdentifier()) . DIRECTORY_SEPARATOR;
     if (!file_exists($path)) {
         mkdir($path);
     }
     $messageFile = $path . \tao_helpers_File::getSafeFileName('message.html', $path);
     \common_Logger::d($messageFile);
     $written = file_put_contents($messageFile, $message->getBody());
     return $written !== false;
 }
 /**
  * retrieve the logged in user
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @return core_kernel_classes_Resource
  */
 public function getCurrentUser()
 {
     $returnValue = null;
     if (!common_session_SessionManager::isAnonymous()) {
         $userUri = \common_session_SessionManager::getSession()->getUser()->getIdentifier();
         if (!empty($userUri)) {
             $returnValue = new core_kernel_classes_Resource($userUri);
         } else {
             common_Logger::d('no userUri');
         }
     }
     return $returnValue;
 }
 /**
  *
  * @access
  * @author "Lionel Lecaque, <*****@*****.**>"
  * @param unknown $ext
  * @return boolean
  */
 public function unShield($ext)
 {
     $extFolder = ROOT_PATH . DIRECTORY_SEPARATOR . $ext;
     if (!is_file($extFolder . '/htaccess.1')) {
         common_Logger::d('Previous lock,  ' . $extFolder . '/htaccess.1 do not exits something may have go wrong, please check');
         return false;
     }
     if (unlink($extFolder . '/.htaccess')) {
         return tao_helpers_File::move($extFolder . '/htaccess.1', $extFolder . '/.htaccess', true, false);
     } else {
         common_Logger::i('Fail to remove htaccess in ' . $ext . ' . You may copy by hand file htaccess.1');
         return false;
     }
 }
 /**
  * Forward alias that use and parse an URL to extract extension/controller/actions?params 
  * @param string $url the url to forward to
  */
 public function forwardUrl($url)
 {
     $context = Context::getInstance();
     $parsedUrl = parse_url($url);
     common_Logger::d($parsedUrl);
     $parts = explode('/', trim($parsedUrl['path'], '/'));
     if (count($parts) === 3) {
         $params = array();
         if (strlen($parsedUrl['query']) > 0) {
             parse_str($parsedUrl['query'], $params);
         }
         $this->forward($parts[2], $parts[1], $parts[0], $params);
     }
     throw new InterruptedActionException('Interrupted action after a forward', $context->getModuleName(), $context->getActionName());
 }
Exemplo n.º 20
0
 protected function prepare($hook)
 {
     if (isset($this->properties['uri'])) {
         $item = new \core_kernel_classes_Resource($this->properties['uri']);
         //check for implementation in debugging state:
         if (isset($hook['debug']) && $hook['debug']) {
             //add required resources:
             $registry = new $hook['registry']();
             $registry->addRequiredResources($hook['typeIdentifier'], $item);
             \common_Logger::d('added ' . $hook['registry'] . ' ' . $hook['typeIdentifier']);
         }
     } else {
         throw new \common_Exception('cannot prepare hook because of missing property in config : "uri" ');
     }
 }
Exemplo n.º 21
0
 /**
  * @param mixed $script
  * @throws common_ext_InstallationException
  */
 protected function runExtensionScript($script)
 {
     common_Logger::d('Running custom extension script ' . $script . ' for extension ' . $this->getExtension()->getId(), 'INSTALL');
     if (file_exists($script)) {
         require_once $script;
     } elseif (class_exists($script) && is_subclass_of($script, 'oat\\oatbox\\action\\Action')) {
         $action = new $script();
         if ($action instanceof ServiceLocatorAwareInterface) {
             $action->setServiceLocator(ServiceManager::getServiceManager());
         }
         $report = call_user_func($action, array());
     } else {
         throw new common_ext_InstallationException('Unable to run install script ' . $script);
     }
 }
 public function execute()
 {
     // get the controller
     $controllerClass = $this->getControllerClass();
     if (class_exists($controllerClass)) {
         // namespaced?
         $module = new $controllerClass();
     } else {
         if (($str = substr($controllerClass, 1)) && class_exists($str)) {
             // non namespaced?
             $module = new $str();
         } else {
             throw new ActionEnforcingException('Controller "' . $controllerClass . '" could not be loaded.', $this->context->getModuleName(), $this->context->getActionName());
         }
     }
     // get the action, module, extension of the action
     $extensionId = $this->context->getExtensionName();
     $moduleName = $this->context->getModuleName() ? Camelizer::firstToUpper($this->context->getModuleName()) : DEFAULT_MODULE_NAME;
     $action = $this->context->getActionName() ? Camelizer::firstToLower($this->context->getActionName()) : DEFAULT_ACTION_NAME;
     // Are we authorized to execute this action?
     $requestParameters = $this->context->getRequest()->getParameters();
     if (!tao_models_classes_accessControl_AclProxy::hasAccess($action, $moduleName, $extensionId, $requestParameters)) {
         $userUri = common_session_SessionManager::getSession()->getUserUri();
         throw new tao_models_classes_AccessDeniedException($userUri, $action, $moduleName, $extensionId);
     }
     // if the method related to the specified action exists, call it
     if (method_exists($module, $action)) {
         $this->context->setActionName($action);
         // search parameters method
         $reflect = new ReflectionMethod($module, $action);
         $parameters = $reflect->getParameters();
         $tabParam = array();
         foreach ($parameters as $param) {
             $tabParam[$param->getName()] = $this->context->getRequest()->getParameter($param->getName());
         }
         // Action method is invoked, passing request parameters as
         // method parameters.
         common_Logger::d('Invoking ' . get_class($module) . '::' . $action, array('GENERIS', 'CLEARRFW'));
         call_user_func_array(array($module, $action), $tabParam);
         // Render the view if selected.
         if ($module->hasView()) {
             $renderer = $module->getRenderer();
             echo $renderer->render();
         }
     } else {
         throw new ActionEnforcingException("Unable to find the action '" . $action . "' in '" . get_class($module) . "'.", $this->context->getModuleName(), $this->context->getActionName());
     }
 }
Exemplo n.º 23
0
 /**
  * Short description of method install
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @return mixed
  */
 public function install()
 {
     if ($this->extension->getId() != 'generis') {
         throw new common_ext_ExtensionException('Tried to install "' . $this->extension->getId() . '" extension using the GenerisInstaller');
     }
     //$this->installCustomScript();
     $this->installLoadDefaultConfig();
     ModelManager::setModel(new \core_kernel_persistence_smoothsql_SmoothModel(array(\core_kernel_persistence_smoothsql_SmoothModel::OPTION_PERSISTENCE => 'default', \core_kernel_persistence_smoothsql_SmoothModel::OPTION_READABLE_MODELS => array('1'), \core_kernel_persistence_smoothsql_SmoothModel::OPTION_WRITEABLE_MODELS => array('1'), \core_kernel_persistence_smoothsql_SmoothModel::OPTION_NEW_TRIPLE_MODEL => '1')));
     $this->installOntology();
     //$this->installLocalData();
     //$this->installModuleModel();
     $this->installRegisterExt();
     common_cache_FileCache::singleton()->purge();
     common_Logger::d('Installing custom script for extension ' . $this->extension->getId());
     $this->installCustomScript();
 }
Exemplo n.º 24
0
 public function getPropertyValues($property)
 {
     $returnValue = null;
     switch ($property) {
         case PROPERTY_USER_DEFLG:
         case PROPERTY_USER_UILG:
             $returnValue = array($this->getLanguage());
             break;
         case PROPERTY_USER_ROLES:
             $returnValue = $this->roles;
             break;
         default:
             common_Logger::d('Unkown property ' . $property . ' requested from ' . __CLASS__);
             $returnValue = array();
     }
     return $returnValue;
 }
 /**
  * Fille the variable $variableName with a correctly transformed
  * $clientSideValue.
  * 
  * @param string $variableName The variable identifier you want to fill.
  * @param string $clientSideValue The value received from the client-side.
  * @return Variable A Variable object filled with a correctly transformed $clientSideValue.
  * @throws OutOfBoundsException If no variable with $variableName is described in the item.
  * @throws OutOfRangeException If the $clientSideValue does not fit the target variable's baseType.
  */
 public function fill($variableName, $clientSideValue)
 {
     $variable = null;
     $outcomeDeclarations = $this->getItemRef()->getOutcomeDeclarations();
     $responseDeclarations = $this->getItemRef()->getResponseDeclarations();
     if (isset($responseDeclarations[$variableName]) === true) {
         $variable = ResponseVariable::createFromDataModel($responseDeclarations[$variableName]);
     } else {
         if (isset($outcomeDeclarations[$variableName]) === true) {
             $variable = OutcomeVariable::createFromDataModel($outcomeDeclarations[$variableName]);
         }
     }
     if (empty($variable) === true) {
         $itemId = $this->getItemRef()->getIdentifier();
         $msg = "No variable declaration '{$variableName}' found in '{$itemId}'.";
         throw new OutOfBoundsException($msg);
     }
     common_Logger::d("Filling variable '" . $variable->getIdentifier() . "'.");
     if (is_array($clientSideValue) === false) {
         $clientSideValue = array($clientSideValue);
     }
     try {
         $finalValues = array();
         foreach ($clientSideValue as $val) {
             $finalValues[] = self::transform($variable->getBaseType(), $val);
         }
         if ($variable->getCardinality() === Cardinality::SINGLE) {
             $variable->setValue($finalValues[0]);
         } else {
             if ($variable->getCardinality() === Cardinality::MULTIPLE) {
                 $variable->setValue(new MultipleContainer($variable->getBaseType(), $finalValues));
             } else {
                 // Cardinality is ORDERED.
                 $variable->setValue(new OrderedContainer($variable->getBaseType(), $finalValues));
             }
         }
         return $variable;
     } catch (InvalidArgumentException $e) {
         if (is_array($clientSideValue)) {
             $clientSideValue = implode(',', $clientSideValue);
         }
         $msg = "An error occured while filling variable '{$variableName}' with client-side value '{$clientSideValue}':" . $e->getMessage();
         throw new InvalidArgumentException($msg, 0, $e);
     }
 }
Exemplo n.º 26
0
 public static function installRecursively($extensionIDs, $installData = array())
 {
     $toInstall = array();
     foreach ($extensionIDs as $id) {
         try {
             $ext = common_ext_ExtensionsManager::singleton()->getExtensionById($id);
             if (!common_ext_ExtensionsManager::singleton()->isInstalled($ext->getId())) {
                 common_Logger::d('Extension ' . $id . ' needs to be installed');
                 $toInstall[$id] = $ext;
             }
         } catch (common_ext_ExtensionException $e) {
             common_Logger::w('Extension ' . $id . ' not found');
         }
     }
     while (!empty($toInstall)) {
         $modified = false;
         foreach ($toInstall as $key => $extension) {
             // if all dependencies are installed
             common_Logger::d('Considering extension ' . $key);
             $installed = array_keys(common_ext_ExtensionsManager::singleton()->getinstalledextensions());
             $missing = array_diff(array_keys($extension->getDependencies()), $installed);
             if (count($missing) == 0) {
                 static::install($extension, $installData);
                 common_Logger::i('Extension ' . $extension->getId() . ' installed');
                 unset($toInstall[$key]);
                 $modified = true;
             } else {
                 $missing = array_diff($missing, array_keys($toInstall));
                 foreach ($missing as $extID) {
                     common_Logger::d('Extension ' . $extID . ' is required but missing, added to install list');
                     $toInstall[$extID] = common_ext_ExtensionsManager::singleton()->getExtensionById($extID);
                     $modified = true;
                 }
             }
         }
         // no extension could be installed, and no new requirements was added
         if (!$modified) {
             throw new \common_exception_Error('Unfulfilable/Cyclic reference found in extensions');
         }
     }
     return true;
 }
 function compile()
 {
     $content = $this->getResource()->getUniquePropertyValue(new core_kernel_classes_Property(TEST_TESTCONTENT_PROP));
     $ltiLaunchUrl = $content->getOnePropertyValue(new core_kernel_classes_Property(PROPERTY_LTI_LINK_LAUNCHURL));
     $ltiLinkConsumer = $content->getOnePropertyValue(new core_kernel_classes_Property(PROPERTY_LTI_LINK_CONSUMER));
     if (empty($ltiLaunchUrl)) {
         throw new tao_models_classes_CompilationFailedException('Missing launch Url for test ' . $this->getResource()->getUri());
     }
     if (empty($ltiLinkConsumer)) {
         throw new tao_models_classes_CompilationFailedException('Missing LTI consumer for test ' . $this->getResource()->getUri());
     }
     // Build the service call.
     $service = new tao_models_classes_service_ServiceCall(new core_kernel_classes_Resource(INSTANCE_LTI_CONSUMER_SERVICE));
     $param = new tao_models_classes_service_ConstantParameter(new core_kernel_classes_Resource(INSTANCE_FORMALPARAM_LTI_LAUNCH_URL), $ltiLaunchUrl);
     $service->addInParameter($param);
     $param = new tao_models_classes_service_ConstantParameter(new core_kernel_classes_Resource(INSTANCE_FORMALPARAM_LTI_CONSUMER), $ltiLinkConsumer->getUri());
     $service->addInParameter($param);
     common_Logger::d("LTI Test successfully compiled.");
     return $service;
 }
Exemplo n.º 28
0
 /**
  * Add a file
  *
  * Adds a l10n file in translation strings. $file should be given without
  * extension. This method will look for $file.lang.php and $file.po (in this
  * order) and retrieve the first one found.
  *
  * @param string	$file		Filename (without extension)
  */
 public static function set($file)
 {
     $lang_file = $file . '.lang';
     $po_file = $file . '.po';
     $php_file = $file . '.lang.php';
     if (file_exists($php_file)) {
         require $php_file;
     } elseif (($tmp = self::getPoFile($po_file)) !== false) {
         $GLOBALS['__l10n_files'][] = $po_file;
         $GLOBALS['__l10n'] = array_merge($GLOBALS['__l10n'], $tmp);
         common_Logger::d('loaded PO file ' . $po_file);
     } elseif (($tmp = self::getLangFile($lang_file)) !== false) {
         $GLOBALS['__l10n_files'][] = $lang_file;
         $GLOBALS['__l10n'] = array_merge($GLOBALS['__l10n'], $tmp);
         common_Logger::d('loaded lang file ' . $lang_file);
     } else {
         common_Logger::w('loaded NO i18n file ' . $file);
         return false;
     }
 }
Exemplo n.º 29
0
 /**
  * Closses the current session, restores the session provided
  * in the parameter session, regenerates a new sessionid and
  * redirects the user to the original address
  */
 public function restoreSession()
 {
     $sessId = $this->getRequestParameter('session');
     $url = $this->getRequestParameter('redirect');
     if (session_id() != $sessId) {
         common_Logger::i('Changing session to ' . $sessId);
         session_unset();
         session_destroy();
         session_id($sessId);
         session_start();
         if (session_id() != $sessId) {
             $this->returnError(__('Unable to restore Session'));
         }
         session_regenerate_id(true);
         common_Logger::d('regenerated session to id \'' . session_id() . '\'');
     } else {
         common_Logger::w('Restore session called with correct session id \'' . session_id() . '\'');
     }
     $this->redirect($url);
 }
Exemplo n.º 30
0
 /**
  * Short description of method evaluate
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param  values
  * @return boolean
  */
 public function evaluate($values)
 {
     $returnValue = (bool) false;
     $mimetype = '';
     if (is_array($values)) {
         if (file_exists($values['uploaded_file'])) {
             $mimetype = tao_helpers_File::getMimeType($values['uploaded_file']);
             common_Logger::d($mimetype);
         }
         if (!empty($mimetype)) {
             if (in_array($mimetype, $this->getOption('mimetype'))) {
                 $returnValue = true;
             } else {
                 $this->setMessage(__('%1$s expected but %2$s detected', implode(', ', $this->getOption('mimetype')), $mimetype));
             }
         } else {
             common_Logger::i('mimetype empty');
         }
     }
     return (bool) $returnValue;
 }