/**
  * Helper function that runs the user import for a sample enrolment
  *
  * @param array $data Import data to use
  */
 private function run_enrolment_import($data)
 {
     global $CFG;
     $file = get_plugin_directory('dhimport', 'version1elis') . '/version1elis.class.php';
     require_once $file;
     $provider = new rlipimport_version1elis_importprovider_mockenrolment($data);
     $importplugin = new rlip_importplugin_version1elis($provider);
     $importplugin->run();
 }
 /**
  * Validate that the file-system logger factory constructs an object of the
  * correct type
  */
 public function test_fsloggerfactoryinstantiatescorrectclass()
 {
     global $CFG;
     require_once $CFG->dirroot . '/local/datahub/lib/rlip_fslogger.class.php';
     $file = get_plugin_directory('dhimport', 'version1') . '/rlip_import_version1_fslogger.class.php';
     require_once $file;
     // Setup.
     $fslogger = rlip_fslogger_factory::factory('dhexport_version1', null);
     // Validation.
     $this->assertInstanceOf('rlip_fslogger_linebased', $fslogger);
     // Setup.
     $fslogger = rlip_fslogger_factory::factory('dhimport_version1', null);
     // Validation.
     $this->assertInstanceOf('rlip_import_version1_fslogger', $fslogger);
 }
 /**
  * Return generator for given plugin
  * @param string $component
  * @return mixed plugin data generator
  */
 public function get_plugin_generator($component)
 {
     list($type, $plugin) = normalize_component($component);
     if ($type !== 'mod' and $type !== 'block') {
         throw new coding_exception("Plugin type {$type} does not support generators yet");
     }
     $dir = get_plugin_directory($type, $plugin);
     if (!isset($this->generators[$type . '_' . $plugin])) {
         $lib = "{$dir}/tests/generator/lib.php";
         if (!(include_once $lib)) {
             throw new coding_exception("Plugin {$component} does not support data generator, missing tests/generator/lib");
         }
         $classname = $type . '_' . $plugin . '_generator';
         $this->generators[$type . '_' . $plugin] = new $classname($this);
     }
     return $this->generators[$type . '_' . $plugin];
 }
/**
 * Return exact path to plugin directory,
 * this method support "simpletest_" prefix designed for unit testing.
 * @param string $component name such as 'moodle', 'mod_forum' or special simpletest value
 * @param bool $fullpaths false means relative paths from dirroot
 * @return directory path, full or relative to dirroot
 */
function get_component_directory($component, $fullpaths = true)
{
    global $CFG;
    $simpletest = false;
    if (strpos($component, 'simpletest_') === 0) {
        $subdir = substr($component, strlen('simpletest_'));
        return $subdir;
    }
    if ($component == 'moodle') {
        $path = $fullpaths ? $CFG->libdir : 'lib';
    } elseif ($component == 'local') {
        $path = ($fullpaths ? $CFG->dirroot . '/' : '') . 'local';
    } else {
        list($type, $plugin) = explode('_', $component, 2);
        $path = get_plugin_directory($type, $plugin, $fullpaths);
    }
    return $path;
}
/**
 * Loads the task definitions for the component (from file). If no
 * tasks are defined for the component, we simply return an empty array.
 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
 * @return array of tasks or empty array if not exists
 *
 * INTERNAL - to be used from cronlib only
 */
function elis_tasks_load_def($component)
{
    global $CFG;
    require_once $CFG->libdir . '/moodlelib2.0.php';
    if ($component == 'moodle') {
        $defpath = $CFG->libdir . '/db/tasks.php';
        //} else if ($component == 'unittest') {
        //    $defpath = $CFG->libdir.'/simpletest/fixtures/tasks.php';
    } else {
        $compparts = explode('/', $component);
        $defpath = get_plugin_directory($compparts[0], $compparts[1]) . '/db/tasks.php';
    }
    $tasks = array();
    if (file_exists($defpath)) {
        require $defpath;
    }
    return $tasks;
}
 /**
  * Validate that the CSV file plugin handles empty lines correctly
  */
 public function test_fileplugincsvhandlesemptylines()
 {
     global $CFG;
     require_once $CFG->dirroot . '/local/datahub/lib/rlip_fileplugin.class.php';
     $file = get_plugin_directory('dhfile', 'csv') . '/csv.class.php';
     require_once $file;
     // Fileplugin instance.
     $inputfile = dirname(__FILE__) . '/fixtures/blankline.csv';
     $fileplugin = new rlip_fileplugin_csv($inputfile);
     $fileplugin->open(RLIP_FILE_READ);
     // Simple data validation.
     $headerline = $fileplugin->read();
     $this->assertEquals($headerline, array('header1', 'header2'));
     $dataline = $fileplugin->read();
     $this->assertEquals($dataline, array('nextline', 'isblank'));
     // Line with just a newline character.
     $emptyline = $fileplugin->read();
     $this->assertEquals($emptyline, false);
     // Line with no content.
     $finalline = $fileplugin->read();
     $this->assertEquals($finalline, false);
 }
 /**
  * Get the question type class for a particular question type.
  * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
  * @param bool $mustexist if false, the missing question type is returned when
  *      the requested question type is not installed.
  * @return question_type the corresponding question type class.
  */
 public static function get_qtype($qtypename, $mustexist = true)
 {
     global $CFG;
     if (isset(self::$questiontypes[$qtypename])) {
         return self::$questiontypes[$qtypename];
     }
     $file = get_plugin_directory('qtype', $qtypename) . '/questiontype.php';
     if (!is_readable($file)) {
         if ($mustexist || $qtypename == 'missingtype') {
             throw new coding_exception('Unknown question type ' . $qtypename);
         } else {
             return self::get_qtype('missingtype');
         }
     }
     include_once $file;
     $class = 'qtype_' . $qtypename;
     if (!class_exists($class)) {
         throw new coding_exception("Class {$class} must be defined in {$file}");
     }
     self::$questiontypes[$qtypename] = new $class();
     return self::$questiontypes[$qtypename];
 }
 /**
  * Factory method to obtain a default file system logger object
  *
  * @param string $plugin The plugin we are running, either dhimport_* or dhexport_*
  * @param object $fileplugin The file plugin that should be used to write out log data
  * @param boolean $manual True on a manual run, false on a scheduled run
  */
 static function factory($plugin, $fileplugin, $manual = false)
 {
     global $CFG;
     //determine the components of the plugin (type and instance)
     list($type, $instance) = explode('_', $plugin);
     //try to load in the appropriate file
     $file = get_plugin_directory($type, $instance) . '/' . $instance . '.class.php';
     if (!file_exists($file)) {
         //this should only happen during unit tests
         require_once $CFG->dirroot . '/local/datahub/lib/rlip_fslogger.class.php';
         return new rlip_fslogger_linebased($fileplugin, $manual);
     }
     require_once $file;
     //determine classname
     $classname = $plugin;
     $classname = str_replace('dhexport_', 'rlip_exportplugin_', $classname);
     $classname = str_replace('dhimport_', 'rlip_importplugin_', $classname);
     //ask the plugin to provide the logger
     return $classname::get_fs_logger($fileplugin, $manual);
 }
 /**
  * Fetches our export data as a multi-dimensional array.
  *
  * @param bool $manual          Whether this is a manual run.
  * @param int  $targetstarttime The timestamp representing the theoretical time when this task was meant to be run
  * @param int  $lastruntime     The last time the export was run (required for incremental scheduled export)
  *
  * @return array The export data
  */
 protected function get_export_data($manual = true, $targetstarttime = 0, $lastruntime = 0)
 {
     global $CFG;
     $file = get_plugin_directory('dhexport', 'version1elis') . '/version1elis.class.php';
     require_once $file;
     // Set the export to be incremental.
     set_config('nonincremental', 0, 'dhexport_version1elis');
     // Set the incremental time delta.
     set_config('incrementaldelta', '1d', 'dhexport_version1elis');
     // Plugin for file IO.
     $fileplugin = new rlip_fileplugin_export();
     $fileplugin->open(RLIP_FILE_WRITE);
     // Our specific export.
     $exportplugin = new rlip_exportplugin_version1elis($fileplugin, $manual);
     $exportplugin->init($targetstarttime, $lastruntime);
     $exportplugin->export_records(0);
     $exportplugin->close();
     $fileplugin->close();
     return $fileplugin->get_data();
 }
Exemple #10
0
/**
 * Figure out exactly what needs to be called and stashes it in $remoteclient
 * Does some further verification that the method is callable
 *
 * @param string   $method the full xmlrpc method that was called eg auth/mnet/auth.php/user_authorise
 * @param array    $callstack  the exploded callstack
 * @param stdclass $rpcrecord  the record from mnet_rpc
 *
 * @throws mnet_server_exception
 */
function mnet_setup_dummy_method($method, $callstack, $rpcrecord) {
    global $CFG;
    $remoteclient = get_mnet_remote_client();
    // verify that the callpath in the stack matches our records
    // callstack will look like array('mod', 'forum', 'lib.php', 'forum_add_instance');
    $path = get_plugin_directory($rpcrecord->plugintype, $rpcrecord->pluginname);
    $path = substr($path, strlen($CFG->dirroot)+1); // this is a bit hacky and fragile, it is not guaranteed that plugins are in dirroot
    array_pop($callstack);
    $providedpath =  implode('/', $callstack);
    if ($providedpath != $path . '/' . $rpcrecord->filename) {
        throw new mnet_server_exception(705, "nosuchfile");
    }
    if (!file_exists($CFG->dirroot . '/' . $providedpath)) {
        throw new mnet_server_exception(705, "nosuchfile");
    }
    require_once($CFG->dirroot . '/' . $providedpath);
    if (!empty($rpcrecord->classname)) {
        if (!class_exists($rpcrecord->classname)) {
            throw new mnet_server_exception(708, 'nosuchclass');
        }
        if (!$rpcrecord->static) {
            try {
                $object = new $rpcrecord->classname;
            } catch (Exception $e) {
                throw new mnet_server_exception(709, "classerror");
            }
            if (!is_callable(array($object, $rpcrecord->functionname))) {
                throw new mnet_server_exception(706, "nosuchfunction");
            }
            $remoteclient->object_to_call($object);
        } else {
            if (!is_callable(array($rpcrecord->classname, $rpcrecord->functionname))) {
                throw new mnet_server_exception(706, "nosuchfunction");
            }
            $remoteclient->static_location($rpcrecord->classname);
        }
    }
}
Exemple #11
0
 /**
  * Get the test helper class for a particular question type.
  * @param $qtype the question type name, e.g. 'multichoice'.
  * @return question_test_helper the test helper class.
  */
 public static function get_test_helper($qtype)
 {
     global $CFG;
     if (array_key_exists($qtype, self::$testhelpers)) {
         return self::$testhelpers[$qtype];
     }
     $file = get_plugin_directory('qtype', $qtype) . '/tests/helper.php';
     if (!is_readable($file)) {
         throw new coding_exception('Question type ' . $qtype . ' does not have test helper code.');
     }
     include_once $file;
     $class = 'qtype_' . $qtype . '_test_helper';
     if (!class_exists($class)) {
         throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
     }
     self::$testhelpers[$qtype] = new $class();
     return self::$testhelpers[$qtype];
 }
 /**
  * Helper function that runs the userset import for a sample userset
  *
  * @param array $extradata Extra fields to set for the new userset
  * @param boolean $usedefaultdata If true, use the default userset data,
  *                                  along with any data specifically provided
  */
 private function run_core_userset_import($extradata, $usedefaultdata = true)
 {
     global $CFG;
     $file = get_plugin_directory('dhimport', 'version1elis') . '/version1elis.class.php';
     require_once $file;
     if ($usedefaultdata) {
         $data = $this->get_core_userset_data();
     } else {
         $data = array();
     }
     foreach ($extradata as $key => $value) {
         $data[$key] = $value;
     }
     $provider = new rlipimport_version1elis_importprovider_mockuserset($data);
     $importplugin = new rlip_importplugin_version1elis($provider);
     $importplugin->run();
 }
Exemple #13
0
/**
 * Given a specific page type, parent context and currect context, return all the page type patterns
 * that might be used by this block.
 *
 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
 * @param stdClass $parentcontext Block's parent context
 * @param stdClass $currentcontext Current context of block
 * @return array an array of all the page type patterns that might match this page type.
 */
function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null)
{
    global $CFG;
    $bits = explode('-', $pagetype);
    $core = get_core_subsystems();
    $plugins = get_plugin_types();
    //progressively strip pieces off the page type looking for a match
    $componentarray = null;
    for ($i = count($bits); $i > 0; $i--) {
        $possiblecomponentarray = array_slice($bits, 0, $i);
        $possiblecomponent = implode('', $possiblecomponentarray);
        // Check to see if the component is a core component
        if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
            $libfile = $CFG->dirroot . '/' . $core[$possiblecomponent] . '/lib.php';
            if (file_exists($libfile)) {
                require_once $libfile;
                $function = $possiblecomponent . '_page_type_list';
                if (function_exists($function)) {
                    if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
                        break;
                    }
                }
            }
        }
        //check the plugin directory and look for a callback
        if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
            //We've found a plugin type. Look for a plugin name by getting the next section of page type
            if (count($bits) > $i) {
                $pluginname = $bits[$i];
                $directory = get_plugin_directory($possiblecomponent, $pluginname);
                if (!empty($directory)) {
                    $libfile = $directory . '/lib.php';
                    if (file_exists($libfile)) {
                        require_once $libfile;
                        $function = $possiblecomponent . '_' . $pluginname . '_page_type_list';
                        if (!function_exists($function)) {
                            $function = $pluginname . '_page_type_list';
                        }
                        if (function_exists($function)) {
                            if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
                                break;
                            }
                        }
                    }
                }
            }
            //we'll only get to here if we still don't have any patterns
            //the plugin type may have a callback
            $directory = get_plugin_directory($possiblecomponent, null);
            if (!empty($directory)) {
                $libfile = $directory . '/lib.php';
                if (file_exists($libfile)) {
                    require_once $libfile;
                    $function = $possiblecomponent . '_page_type_list';
                    if (function_exists($function)) {
                        if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
                            break;
                        }
                    }
                }
            }
        }
    }
    if (empty($patterns)) {
        $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
    }
    // Ensure that the * pattern is always available if editing block 'at distance', so
    // we always can 'bring back' it to the original context. MDL-30340
    if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
        // TODO: We could change the string here, showing its 'bring back' meaning
        $patterns['*'] = get_string('page-x', 'pagetype');
    }
    return $patterns;
}
 /**
  * Creates an import field mapping record in the database
  *
  * @param string $entitytype The type of entity, such as user or course
  * @param string $standardfieldname The typical import field name
  * @param string $customfieldname The custom import field name
  */
 private function create_mapping_record($entitytype, $standardfieldname, $customfieldname)
 {
     global $DB;
     $file = get_plugin_directory('dhimport', 'version1elis') . '/lib.php';
     require_once $file;
     $record = new stdClass();
     $record->entitytype = $entitytype;
     $record->standardfieldname = $standardfieldname;
     $record->customfieldname = $customfieldname;
     $DB->insert_record(RLIPIMPORT_VERSION1ELIS_MAPPING_TABLE, $record);
 }
Exemple #15
0
 /**
  * Get String returns a requested string
  *
  * @param string $identifier The identifier of the string to search for
  * @param string $component The module the string is associated with
  * @param string|object|array $a An object, string or number that can be used
  *      within translation strings
  * @param string $lang moodle translation language, NULL means use current
  * @return string The String !
  */
 public function get_string($identifier, $component = '', $a = NULL, $lang = NULL)
 {
     $this->countgetstring++;
     // there are very many uses of these time formating strings without the 'langconfig' component,
     // it would not be reasonable to expect that all of them would be converted during 2.0 migration
     static $langconfigstrs = array('strftimedate' => 1, 'strftimedatefullshort' => 1, 'strftimedateshort' => 1, 'strftimedatetime' => 1, 'strftimedatetimeshort' => 1, 'strftimedaydate' => 1, 'strftimedaydatetime' => 1, 'strftimedayshort' => 1, 'strftimedaytime' => 1, 'strftimemonthyear' => 1, 'strftimerecent' => 1, 'strftimerecentfull' => 1, 'strftimetime' => 1);
     if (empty($component)) {
         if (isset($langconfigstrs[$identifier])) {
             $component = 'langconfig';
         } else {
             $component = 'moodle';
         }
     }
     if ($lang === NULL) {
         $lang = current_language();
     }
     $string = $this->load_component_strings($component, $lang);
     if (!isset($string[$identifier])) {
         if ($component === 'pix' or $component === 'core_pix') {
             // this component contains only alt tags for emoticons,
             // not all of them are supposed to be defined
             return '';
         }
         if ($identifier === 'parentlanguage' and ($component === 'langconfig' or $component === 'core_langconfig')) {
             // parentlanguage is a special string, undefined means use English if not defined
             return 'en';
         }
         if ($this->usediskcache) {
             // maybe the on-disk cache is dirty - let the last attempt be to find the string in original sources,
             // do NOT write the results to disk cache because it may end up in race conditions see MDL-31904
             $this->usediskcache = false;
             $string = $this->load_component_strings($component, $lang, true);
             $this->usediskcache = true;
         }
         if (!isset($string[$identifier])) {
             // the string is still missing - should be fixed by developer
             list($plugintype, $pluginname) = normalize_component($component);
             if ($plugintype == 'core') {
                 $file = "lang/en/{$component}.php";
             } else {
                 if ($plugintype == 'mod') {
                     $file = "mod/{$pluginname}/lang/en/{$pluginname}.php";
                 } else {
                     $path = get_plugin_directory($plugintype, $pluginname);
                     $file = "{$path}/lang/en/{$plugintype}_{$pluginname}.php";
                 }
             }
             debugging("Invalid get_string() identifier: '{$identifier}' or component '{$component}'. " . "Perhaps you are missing \$string['{$identifier}'] = ''; in {$file}?", DEBUG_DEVELOPER);
             return "[[{$identifier}]]";
         }
     }
     $string = $string[$identifier];
     if ($a !== NULL) {
         // Process array's and objects (except lang_strings)
         if (is_array($a) or is_object($a) && !$a instanceof lang_string) {
             $a = (array) $a;
             $search = array();
             $replace = array();
             foreach ($a as $key => $value) {
                 if (is_int($key)) {
                     // we do not support numeric keys - sorry!
                     continue;
                 }
                 if (is_array($value) or is_object($value) && !$value instanceof lang_string) {
                     // we support just string or lang_string as value
                     continue;
                 }
                 $search[] = '{$a->' . $key . '}';
                 $replace[] = (string) $value;
             }
             if ($search) {
                 $string = str_replace($search, $replace, $string);
             }
         } else {
             $string = str_replace('{$a}', (string) $a, $string);
         }
     }
     return $string;
 }
/**
 * Given a specific page type, parent context and currect context, return all the page type patterns
 * that might be used by this block.
 *
 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
 * @param stdClass $parentcontext Block's parent context
 * @param stdClass $currentcontext Current context of block
 * @return array an array of all the page type patterns that might match this page type.
 */
function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null)
{
    global $CFG;
    $bits = explode('-', $pagetype);
    $core = get_core_subsystems();
    $plugins = get_plugin_types();
    //progressively strip pieces off the page type looking for a match
    $componentarray = null;
    for ($i = count($bits); $i > 0; $i--) {
        $possiblecomponentarray = array_slice($bits, 0, $i);
        $possiblecomponent = implode('', $possiblecomponentarray);
        // Check to see if the component is a core component
        if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
            $libfile = $CFG->dirroot . '/' . $core[$possiblecomponent] . '/lib.php';
            if (file_exists($libfile)) {
                require_once $libfile;
                $function = $possiblecomponent . '_page_type_list';
                if (function_exists($function)) {
                    if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
                        break;
                    }
                }
            }
        }
        //check the plugin directory and look for a callback
        if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
            //We've found a plugin type. Look for a plugin name by getting the next section of page type
            if (count($bits) > $i) {
                $pluginname = $bits[$i];
                $directory = get_plugin_directory($possiblecomponent, $pluginname);
                if (!empty($directory)) {
                    $libfile = $directory . '/lib.php';
                    if (file_exists($libfile)) {
                        require_once $libfile;
                        $function = $pluginname . '_page_type_list';
                        if (function_exists($function)) {
                            if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
                                break;
                            }
                        }
                    }
                }
            }
            //we'll only get to here if we still don't have any patterns
            //the plugin type may have a callback
            $directory = get_plugin_directory($possiblecomponent, null);
            if (!empty($directory)) {
                $libfile = $directory . '/lib.php';
                if (file_exists($libfile)) {
                    require_once $libfile;
                    $function = $possiblecomponent . '_page_type_list';
                    if (function_exists($function)) {
                        if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
                            break;
                        }
                    }
                }
            }
        }
    }
    if (empty($patterns)) {
        $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
    }
    return $patterns;
}
 public function test_deprecated_get_plugin_directory()
 {
     $plugintypes = core_component::get_plugin_types();
     foreach ($plugintypes as $plugintype => $fulldir) {
         $plugins = core_component::get_plugin_list($plugintype);
         foreach ($plugins as $pluginname => $plugindir) {
             $this->assertSame(core_component::get_plugin_directory($plugintype, $pluginname), get_plugin_directory($plugintype, $pluginname));
         }
     }
 }
Exemple #18
0
/**
 * upgrades the mnet rpc definitions for the given component.
 * this method doesn't return status, an exception will be thrown in the case of an error
 *
 * @param string $component the plugin to upgrade, eg auth_mnet
 */
function upgrade_plugin_mnet_functions($component) {
    global $DB, $CFG;

    list($type, $plugin) = explode('_', $component);
    $path = get_plugin_directory($type, $plugin);

    $publishes = array();
    $subscribes = array();
    if (file_exists($path . '/db/mnet.php')) {
        require_once($path . '/db/mnet.php'); // $publishes comes from this file
    }
    if (empty($publishes)) {
        $publishes = array(); // still need this to be able to disable stuff later
    }
    if (empty($subscribes)) {
        $subscribes = array(); // still need this to be able to disable stuff later
    }

    static $servicecache = array();

    // rekey an array based on the rpc method for easy lookups later
    $publishmethodservices = array();
    $subscribemethodservices = array();
    foreach($publishes as $servicename => $service) {
        if (is_array($service['methods'])) {
            foreach($service['methods'] as $methodname) {
                $service['servicename'] = $servicename;
                $publishmethodservices[$methodname][] = $service;
            }
        }
    }

    // Disable functions that don't exist (any more) in the source
    // Should these be deleted? What about their permissions records?
    foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
        if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
            $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
        } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
            $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
        }
    }

    // reflect all the services we're publishing and save them
    require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
    static $cachedclasses = array(); // to store reflection information in
    foreach ($publishes as $service => $data) {
        $f = $data['filename'];
        $c = $data['classname'];
        foreach ($data['methods'] as $method) {
            $dataobject = new stdClass();
            $dataobject->plugintype  = $type;
            $dataobject->pluginname  = $plugin;
            $dataobject->enabled     = 1;
            $dataobject->classname   = $c;
            $dataobject->filename    = $f;

            if (is_string($method)) {
                $dataobject->functionname = $method;

            } else if (is_array($method)) { // wants to override file or class
                $dataobject->functionname = $method['method'];
                $dataobject->classname     = $method['classname'];
                $dataobject->filename      = $method['filename'];
            }
            $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
            $dataobject->static = false;

            require_once($path . '/' . $dataobject->filename);
            $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
            if (!empty($dataobject->classname)) {
                if (!class_exists($dataobject->classname)) {
                    throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
                }
                $key = $dataobject->filename . '|' . $dataobject->classname;
                if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
                    try {
                        $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
                    } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
                        throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
                    }
                }
                $r =& $cachedclasses[$key];
                if (!$r->hasMethod($dataobject->functionname)) {
                    throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
                }
                // stupid workaround for zend not having a getMethod($name) function
                $ms = $r->getMethods();
                foreach ($ms as $m) {
                    if ($m->getName() == $dataobject->functionname) {
                        $functionreflect = $m;
                        break;
                    }
                }
                $dataobject->static = (int)$functionreflect->isStatic();
            } else {
                if (!function_exists($dataobject->functionname)) {
                    throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
                }
                try {
                    $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
                } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
                    throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
                }
            }
            $dataobject->profile =  serialize(admin_mnet_method_profile($functionreflect));
            $dataobject->help = $functionreflect->getDescription();

            if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
                $dataobject->id      = $record_exists->id;
                $dataobject->enabled = $record_exists->enabled;
                $DB->update_record('mnet_rpc', $dataobject);
            } else {
                $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
            }

            // TODO this API versioning must be reworked, here the recently processed method
            // sets the service API which may not be correct
            foreach ($publishmethodservices[$dataobject->functionname] as $service) {
                if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
                    $serviceobj->apiversion = $service['apiversion'];
                    $DB->update_record('mnet_service', $serviceobj);
                } else {
                    $serviceobj = new stdClass();
                    $serviceobj->name        = $service['servicename'];
                    $serviceobj->description = empty($service['description']) ? '' : $service['description'];
                    $serviceobj->apiversion  = $service['apiversion'];
                    $serviceobj->offer       = 1;
                    $serviceobj->id          = $DB->insert_record('mnet_service', $serviceobj);
                }
                $servicecache[$service['servicename']] = $serviceobj;
                if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
                    $obj = new stdClass();
                    $obj->rpcid = $dataobject->id;
                    $obj->serviceid = $serviceobj->id;
                    $DB->insert_record('mnet_service2rpc', $obj, true);
                }
            }
        }
    }
    // finished with methods we publish, now do subscribable methods
    foreach($subscribes as $service => $methods) {
        if (!array_key_exists($service, $servicecache)) {
            if (!$serviceobj = $DB->get_record('mnet_service', array('name' =>  $service))) {
                debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
                continue;
            }
            $servicecache[$service] = $serviceobj;
        } else {
            $serviceobj = $servicecache[$service];
        }
        foreach ($methods as $method => $xmlrpcpath) {
            if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
                $remoterpc = (object)array(
                    'functionname' => $method,
                    'xmlrpcpath' => $xmlrpcpath,
                    'plugintype' => $type,
                    'pluginname' => $plugin,
                    'enabled'    => 1,
                );
                $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
            }
            if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
                $obj = new stdClass();
                $obj->rpcid = $rpcid;
                $obj->serviceid = $serviceobj->id;
                $DB->insert_record('mnet_remote_service2rpc', $obj, true);
            }
            $subscribemethodservices[$method][] = $service;
        }
    }

    foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
        if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
            $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
        } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
            $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
        }
    }

    return true;
}
 /**
  * Returns whether the grade item can control the visibility of the grades
  *
  * @return bool
  */
 public function can_control_visibility()
 {
     if (get_plugin_directory($this->itemtype, $this->itemmodule)) {
         return !plugin_supports($this->itemtype, $this->itemmodule, FEATURE_CONTROLS_GRADE_VISIBILITY, false);
     }
     return parent::can_control_visibility();
 }
 /**
  * Checks if the given component's directory is writable
  *
  * For the purpose of the deployment, the web server process has to have
  * write access to all files in the component's directory (recursively) and for the
  * directory itself.
  *
  * @see worker::move_directory_source_precheck()
  * @param string $component normalized component name
  * @return boolean
  */
 protected function component_writable($component)
 {
     list($plugintype, $pluginname) = normalize_component($component);
     $directory = get_plugin_directory($plugintype, $pluginname);
     if (is_null($directory)) {
         throw new coding_exception('Unknown component location', $component);
     }
     return $this->directory_writable($directory);
 }
 function general_validation_message($record, $message, $type)
 {
     //need the plugin class for some utility functions
     $file = get_plugin_directory('dhimport', 'version1') . '/version1.class.php';
     require_once $file;
     // "action" is not always provided. In that case, return only the specific message
     if (empty($record->action)) {
         //missing action, general message will be fairly generic
         $type_display = ucfirst($type);
         return "{$type_display} could not be processed. {$message}";
         return $message;
     }
     $msg = "";
     if ($type == "enrolment") {
         if ($record->action != 'create' && $record->action != 'delete') {
             //invalid action
             return 'Enrolment could not be processed. ' . $message;
         }
         if (!$this->track_role_actions && !$this->track_enrolment_actions) {
             //error without sufficient information to properly provide details
             if ($record->action == 'create') {
                 return 'Enrolment could not be created. ' . $message;
             } else {
                 if ($record->action == 'delete') {
                     return 'Enrolment could not be deleted. ' . $message;
                 }
             }
         }
         //collect role assignment and enrolment messages
         $lines = array();
         if ($this->track_role_actions) {
             //determine if a user identifier was set
             $user_identifier_set = !empty($record->username) || !empty($record->email) || !empty($record->idnumber);
             //determine if all required fields were set
             $required_fields_set = !empty($record->role) && $user_identifier_set && !empty($record->context);
             //list of contexts at which role assignments are allowed for specific instances
             $valid_contexts = array('coursecat', 'course', 'user');
             //descriptive string for user and context
             $user_descriptor = rlip_importplugin_version1::get_user_descriptor($record);
             $context_descriptor = rlip_importplugin_version1::get_context_descriptor($record);
             switch ($record->action) {
                 case "create":
                     if ($required_fields_set && in_array($record->context, $valid_contexts) && !empty($record->instance)) {
                         //assignment on a specific context
                         $lines[] = "User with {$user_descriptor} could not be assigned role " . "with shortname \"{$record->role}\" on {$context_descriptor}.";
                     } else {
                         if ($required_fields_set && $record->context == 'system') {
                             //assignment on the system context
                             $lines[] = "User with {$user_descriptor} could not be assigned role " . "with shortname \"{$record->role}\" on the system context.";
                         } else {
                             //not valid
                             $lines[] = "Role assignment could not be created.";
                         }
                     }
                     break;
                 case "delete":
                     if ($required_fields_set && in_array($record->context, $valid_contexts) && !empty($record->instance)) {
                         //unassignment from a specific context
                         $lines[] = "User with {$user_descriptor} could not be unassigned role " . "with shortname \"{$record->role}\" on {$context_descriptor}.";
                     } else {
                         if ($required_fields_set && $record->context == 'system') {
                             //unassignment from the system context
                             $lines[] = "User with {$user_descriptor} could not be unassigned role " . "with shortname \"{$record->role}\" on the system context.";
                         } else {
                             //not valid
                             $lines[] = "Role assignment could not be deleted. ";
                         }
                     }
                     break;
             }
         }
         if ($this->track_enrolment_actions) {
             //determine if a user identifier was set
             $user_identifier_set = !empty($record->username) || !empty($record->email) || !empty($record->idnumber);
             //determine if some required field is missing
             $missing_required_field = !$user_identifier_set || empty($record->instance);
             //descriptive string for user
             $user_descriptor = rlip_importplugin_version1::get_user_descriptor($record);
             switch ($record->action) {
                 case "create":
                     if ($missing_required_field) {
                         //required field missing, so use generic failure message
                         $lines[] = "Enrolment could not be created.";
                     } else {
                         //more accurate failure message
                         $lines[] = "User with {$user_descriptor} could not be enrolled in " . "course with shortname \"{$record->instance}\".";
                     }
                     break;
                 case "delete":
                     if ($missing_required_field) {
                         //required field missing, so use generic failure message
                         $lines[] = "Enrolment could not be deleted.";
                     } else {
                         //more accurate failure message
                         $lines[] = "User with {$user_descriptor} could not be unenrolled " . "from course with shortname \"{$record->instance}\".";
                     }
                     break;
             }
         }
         //create combined message, potentially containing role assignment and
         //enrolment components
         $msg = implode(' ', $lines) . ' ' . $message;
     }
     if ($type == "course") {
         $type = ucfirst($type);
         switch ($record->action) {
             case "create":
                 if (empty($record->shortname)) {
                     $msg = "Course could not be created. " . $message;
                 } else {
                     $msg = "{$type} with shortname \"{$record->shortname}\" could not be created. " . $message;
                 }
                 break;
             case "update":
                 if (empty($record->shortname)) {
                     $msg = "Course could not be updated. " . $message;
                 } else {
                     $msg = "{$type} with shortname \"{$record->shortname}\" could not be updated. " . $message;
                 }
                 break;
             case "delete":
                 if (empty($record->shortname)) {
                     $msg = "Course could not be deleted. " . $message;
                 } else {
                     $msg = "{$type} with shortname \"{$record->shortname}\" could not be deleted. " . $message;
                 }
                 break;
             default:
                 //invalid action
                 $msg = 'Course could not be processed. ' . $message;
                 break;
         }
     }
     if ($type == "user") {
         $type = ucfirst($type);
         switch ($record->action) {
             case "create":
                 //make sure all required fields are specified
                 if (empty($record->username) || empty($record->email)) {
                     $msg = "User could not be created. " . $message;
                 } else {
                     $user_descriptor = rlip_importplugin_version1::get_user_descriptor($record);
                     $msg = "{$type} with {$user_descriptor} could not be created. " . $message;
                 }
                 break;
             case "update":
                 //make sure all required fields are specified
                 if (empty($record->username) && empty($record->email) && empty($record->idnumber)) {
                     $msg = "User could not be updated. " . $message;
                 } else {
                     $user_descriptor = rlip_importplugin_version1::get_user_descriptor($record);
                     $msg = "{$type} with {$user_descriptor} could not be updated. " . $message;
                 }
                 break;
             case "delete":
                 //make sure all required fields are specified
                 if (empty($record->username) && empty($record->email) && empty($record->idnumber)) {
                     $msg = "User could not be deleted. " . $message;
                 } else {
                     $user_descriptor = rlip_importplugin_version1::get_user_descriptor($record);
                     $msg = "{$type} with {$user_descriptor} could not be deleted. " . $message;
                 }
                 break;
             default:
                 //invalid action
                 $msg = 'User could not be processed. ' . $message;
                 break;
         }
     }
     return $msg;
 }
Exemple #22
0
/**
 * Automatically clean-up all plugin data and remove the plugin DB tables
 *
 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
 * @uses global $OUTPUT to produce notices and other messages
 * @return void
 */
function uninstall_plugin($type, $name)
{
    global $CFG, $DB, $OUTPUT;
    // recursively uninstall all module subplugins first
    if ($type === 'mod') {
        if (file_exists("{$CFG->dirroot}/mod/{$name}/db/subplugins.php")) {
            $subplugins = array();
            include "{$CFG->dirroot}/mod/{$name}/db/subplugins.php";
            foreach ($subplugins as $subplugintype => $dir) {
                $instances = get_plugin_list($subplugintype);
                foreach ($instances as $subpluginname => $notusedpluginpath) {
                    uninstall_plugin($subplugintype, $subpluginname);
                }
            }
        }
    }
    $component = $type . '_' . $name;
    // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
    if ($type === 'mod') {
        $pluginname = $name;
        // eg. 'forum'
        if (get_string_manager()->string_exists('modulename', $component)) {
            $strpluginname = get_string('modulename', $component);
        } else {
            $strpluginname = $component;
        }
    } else {
        $pluginname = $component;
        if (get_string_manager()->string_exists('pluginname', $component)) {
            $strpluginname = get_string('pluginname', $component);
        } else {
            $strpluginname = $component;
        }
    }
    echo $OUTPUT->heading($pluginname);
    $plugindirectory = get_plugin_directory($type, $name);
    $uninstalllib = $plugindirectory . '/db/uninstall.php';
    if (file_exists($uninstalllib)) {
        require_once $uninstalllib;
        $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall';
        // eg. 'xmldb_workshop_uninstall()'
        if (function_exists($uninstallfunction)) {
            if (!$uninstallfunction()) {
                echo $OUTPUT->notification('Encountered a problem running uninstall function for ' . $pluginname);
            }
        }
    }
    if ($type === 'mod') {
        // perform cleanup tasks specific for activity modules
        if (!($module = $DB->get_record('modules', array('name' => $name)))) {
            print_error('moduledoesnotexist', 'error');
        }
        // delete all the relevant instances from all course sections
        if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
            foreach ($coursemods as $coursemod) {
                if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
                    echo $OUTPUT->notification("Could not delete the {$strpluginname} with id = {$coursemod->id} from section {$coursemod->section}");
                }
            }
        }
        // clear course.modinfo for courses that used this module
        $sql = "UPDATE {course}\n                   SET modinfo=''\n                 WHERE id IN (SELECT DISTINCT course\n                                FROM {course_modules}\n                               WHERE module=?)";
        $DB->execute($sql, array($module->id));
        // delete all the course module records
        $DB->delete_records('course_modules', array('module' => $module->id));
        // delete module contexts
        if ($coursemods) {
            foreach ($coursemods as $coursemod) {
                if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
                    echo $OUTPUT->notification("Could not delete the context for {$strpluginname} with id = {$coursemod->id}");
                }
            }
        }
        // delete the module entry itself
        $DB->delete_records('modules', array('name' => $module->name));
        // cleanup the gradebook
        require_once $CFG->libdir . '/gradelib.php';
        grade_uninstalled_module($module->name);
        // Perform any custom uninstall tasks
        if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
            require_once $CFG->dirroot . '/mod/' . $module->name . '/lib.php';
            $uninstallfunction = $module->name . '_uninstall';
            if (function_exists($uninstallfunction)) {
                debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
                if (!$uninstallfunction()) {
                    echo $OUTPUT->notification('Encountered a problem running uninstall function for ' . $module->name . '!');
                }
            }
        }
    } else {
        if ($type === 'enrol') {
            // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
            // nuke all role assignments
            role_unassign_all(array('component' => $component));
            // purge participants
            $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
            // purge enrol instances
            $DB->delete_records('enrol', array('enrol' => $name));
            // tweak enrol settings
            if (!empty($CFG->enrol_plugins_enabled)) {
                $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
                $enabledenrols = array_unique($enabledenrols);
                $enabledenrols = array_flip($enabledenrols);
                unset($enabledenrols[$name]);
                $enabledenrols = array_flip($enabledenrols);
                if (is_array($enabledenrols)) {
                    set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
                }
            }
        } else {
            if ($type === 'block') {
                if ($block = $DB->get_record('block', array('name' => $name))) {
                    // Inform block it's about to be deleted
                    if (file_exists("{$CFG->dirroot}/blocks/{$block->name}/block_{$block->name}.php")) {
                        $blockobject = block_instance($block->name);
                        if ($blockobject) {
                            $blockobject->before_delete();
                            //only if we can create instance, block might have been already removed
                        }
                    }
                    // First delete instances and related contexts
                    $instances = $DB->get_records('block_instances', array('blockname' => $block->name));
                    foreach ($instances as $instance) {
                        blocks_delete_instance($instance);
                    }
                    // Delete block
                    $DB->delete_records('block', array('id' => $block->id));
                }
            }
        }
    }
    // perform clean-up task common for all the plugin/subplugin types
    // delete calendar events
    $DB->delete_records('event', array('modulename' => $pluginname));
    // delete all the logs
    $DB->delete_records('log', array('module' => $pluginname));
    // delete log_display information
    $DB->delete_records('log_display', array('component' => $component));
    // delete the module configuration records
    unset_all_config_for_plugin($pluginname);
    // delete message provider
    message_provider_uninstall($component);
    // delete message processor
    if ($type === 'message') {
        message_processor_uninstall($name);
    }
    // delete the plugin tables
    $xmldbfilepath = $plugindirectory . '/db/install.xml';
    drop_plugin_tables($component, $xmldbfilepath, false);
    if ($type === 'mod' or $type === 'block') {
        // non-frankenstyle table prefixes
        drop_plugin_tables($name, $xmldbfilepath, false);
    }
    // delete the capabilities that were defined by this module
    capabilities_cleanup($component);
    // remove event handlers and dequeue pending events
    events_uninstall($component);
    echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
}
 /**
  * Validate that the version 1 export includes custom field headers in the output
  *
  * @dataProvider entity_provider
  */
 public function test_exportincludes_correct_customfield_header_info($entityname, $entitytable)
 {
     global $CFG, $DB;
     $file = get_plugin_directory('dhexport', 'version1elis') . '/lib.php';
     require_once $file;
     // Set the export to be incremental.
     set_config('nonincremental', 0, 'dhexport_version1elis');
     // Set up necessary custom field information in the database.
     // Create categpry.
     $categoryid = $this->create_custom_field_category();
     // Create custom field.
     $field = $this->create_test_field($entityname, 'rliptext', 'char', 'text', $categoryid);
     $this->create_field_mapping('testcustomfields', 'field_' . $field->id);
     // Obtain our export data based on the current DB state.
     $data = $this->get_export_data();
     $this->assertEquals(count($data), 1);
     $expectedheader = array(get_string('header_firstname', 'dhexport_version1elis'), get_string('header_lastname', 'dhexport_version1elis'), get_string('header_username', 'dhexport_version1elis'), get_string('header_useridnumber', 'dhexport_version1elis'), get_string('header_courseidnumber', 'dhexport_version1elis'), get_string('header_startdate', 'dhexport_version1elis'), get_string('header_enddate', 'dhexport_version1elis'), get_string('header_status', 'dhexport_version1elis'), get_string('header_grade', 'dhexport_version1elis'), get_string('header_letter', 'dhexport_version1elis'), 'Header');
     // Make sure the data matches the expected header.
     $this->assertEquals($expectedheader, $data[0]);
 }
 /**
  * Validate that the API call for moving a profile field down in export
  * position deals with deleted user profile fields correctly
  */
 public function test_version1exporthandlesdeletedfieldswhenmovingdown()
 {
     global $CFG, $DB;
     $file = get_plugin_directory('dhexport', 'version1') . '/lib.php';
     require_once $file;
     // Set up the category and field, along with the export mapping.
     $categoryid = $this->create_custom_field_category();
     $firstfieldid = $this->create_profile_field('rliptext', 'text', $categoryid);
     $this->create_field_mapping($firstfieldid);
     // Set up a second mapping record without a field.
     $secondfieldid = 9999;
     $this->create_field_mapping($secondfieldid, 'Header2', 2);
     // Set up a third field with a mapping record.
     $thirdfieldid = $this->create_profile_field('rliptext3', 'text', $categoryid);
     $this->create_field_mapping($thirdfieldid, 'Header3', 3);
     // Move the first field down.
     $id = $DB->get_field(RLIPEXPORT_VERSION1_FIELD_TABLE, 'id', array('fieldid' => $firstfieldid));
     rlipexport_version1_config::move_field($id, rlipexport_version1_config::DIR_DOWN);
     // Validate that the first and third fields swapped, ignoring the second field.
     $this->assert_record_exists(RLIPEXPORT_VERSION1_FIELD_TABLE, array('fieldid' => $firstfieldid, 'fieldorder' => 3));
     $this->assert_record_exists(RLIPEXPORT_VERSION1_FIELD_TABLE, array('fieldid' => $thirdfieldid, 'fieldorder' => 1));
 }
 /**
  * Helper function that runs the user import for a sample user
  *
  * @param array $data Import data to use
  */
 private function run_user_import($data, $usedefaultdata = true)
 {
     global $CFG;
     $file = get_plugin_directory('dhimport', 'version1elis') . '/version1elis.class.php';
     require_once $file;
     $provider = new rlipimport_version1elis_importprovider_mockuser($data);
     $importplugin = new rlip_importplugin_version1elis($provider);
     $importplugin->run();
 }
Exemple #26
0
        // then div wrapper for xhtml strictness
        $output = html_writer::tag('div', $output);

        // now the form itself around it
        $formattributes = array(
            'method' => $select->method,
            'action' => $select->url->out_omit_querystring(),
            'id'     => $select->formid
        );
        $output = html_writer::tag('form', $output, $formattributes);

        // and finally one more wrapper with class
        return html_writer::tag('div', $output, array('class' => $select->class));
    }
}

/**
 * Overridden choice module renderer for the mymobile theme
 *
 * @package    theme
 * @subpackage mymobile
 * @copyright  John Stabinger
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

$choice = get_plugin_directory('mod', 'choice');
if (file_exists($choice . '/renderer.php')) {
    require_once($CFG->dirroot . '/theme/mymobile/renderers/mod_choice_renderer.php');
}
Exemple #27
0
    if (($key = array_search($delete, $disabledbehaviours)) !== false) {
        unset($disabledbehaviours[$key]);
        set_config('disabledbehaviours', implode(',', $disabledbehaviours), 'question');
    }
    $behaviourorder = array_keys($sortedbehaviours);
    if (($key = array_search($delete, $behaviourorder)) !== false) {
        unset($behaviourorder[$key]);
        set_config('behavioursortorder', implode(',', $behaviourorder), 'question');
    }
    // Then the tables themselves
    drop_plugin_tables($delete, get_plugin_directory('qbehaviour', $delete) . '/db/install.xml', false);
    // Remove event handlers and dequeue pending events
    events_uninstall('qbehaviour_' . $delete);
    $a = new stdClass();
    $a->behaviour = $behaviourname;
    $a->directory = get_plugin_directory('qbehaviour', $delete);
    echo $OUTPUT->box(get_string('qbehaviourdeletefiles', 'question', $a), 'generalbox', 'notice');
    echo $OUTPUT->continue_button($thispageurl);
    echo $OUTPUT->footer();
    exit;
}
// End of process actions ==================================================
// Print the page heading.
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('manageqbehaviours', 'admin'));
// Set up the table.
$table = new flexible_table('qbehaviouradmintable');
$table->define_baseurl($thispageurl);
$table->define_columns(array('behaviour', 'numqas', 'version', 'requires', 'available', 'delete'));
$table->define_headers(array(get_string('behaviour', 'question'), get_string('numqas', 'question'), get_string('version'), get_string('requires', 'admin'), get_string('availableq', 'question'), get_string('delete')));
$table->set_attribute('id', 'qbehaviours');
Exemple #28
0
 /**
  * Load all strings for one component
  * @param string $component The module the string is associated with
  * @param string $lang
  * @param bool $disablecache Do not use caches, force fetching the strings from sources
  * @param bool $disablelocal Do not use customized strings in xx_local language packs
  * @return array of all string for given component and lang
  */
 public function load_component_strings($component, $lang, $disablecache = false, $disablelocal = false)
 {
     global $CFG;
     list($plugintype, $pluginname) = normalize_component($component);
     if ($plugintype == 'core' and is_null($pluginname)) {
         $component = 'core';
     } else {
         $component = $plugintype . '_' . $pluginname;
     }
     if (!$disablecache) {
         // try in-memory cache first
         if (isset($this->cache[$lang][$component])) {
             $this->countmemcache++;
             return $this->cache[$lang][$component];
         }
         // try on-disk cache then
         if ($this->usediskcache and file_exists($this->cacheroot . "/{$lang}/{$component}.php")) {
             $this->countdiskcache++;
             include $this->cacheroot . "/{$lang}/{$component}.php";
             return $this->cache[$lang][$component];
         }
     }
     // no cache found - let us merge all possible sources of the strings
     if ($plugintype === 'core') {
         $file = $pluginname;
         if ($file === null) {
             $file = 'moodle';
         }
         $string = array();
         // first load english pack
         if (!file_exists("{$CFG->dirroot}/lang/en/{$file}.php")) {
             return array();
         }
         include "{$CFG->dirroot}/lang/en/{$file}.php";
         $originalkeys = array_keys($string);
         $originalkeys = array_flip($originalkeys);
         // and then corresponding local if present and allowed
         if (!$disablelocal and file_exists("{$this->localroot}/en_local/{$file}.php")) {
             include "{$this->localroot}/en_local/{$file}.php";
         }
         // now loop through all langs in correct order
         $deps = $this->get_language_dependencies($lang);
         foreach ($deps as $dep) {
             // the main lang string location
             if (file_exists("{$this->otherroot}/{$dep}/{$file}.php")) {
                 include "{$this->otherroot}/{$dep}/{$file}.php";
             }
             if (!$disablelocal and file_exists("{$this->localroot}/{$dep}_local/{$file}.php")) {
                 include "{$this->localroot}/{$dep}_local/{$file}.php";
             }
         }
     } else {
         if (!($location = get_plugin_directory($plugintype, $pluginname)) or !is_dir($location)) {
             return array();
         }
         if ($plugintype === 'mod') {
             // bloody mod hack
             $file = $pluginname;
         } else {
             $file = $plugintype . '_' . $pluginname;
         }
         $string = array();
         // first load English pack
         if (!file_exists("{$location}/lang/en/{$file}.php")) {
             //English pack does not exist, so do not try to load anything else
             return array();
         }
         include "{$location}/lang/en/{$file}.php";
         $originalkeys = array_keys($string);
         $originalkeys = array_flip($originalkeys);
         // and then corresponding local english if present
         if (!$disablelocal and file_exists("{$this->localroot}/en_local/{$file}.php")) {
             include "{$this->localroot}/en_local/{$file}.php";
         }
         // now loop through all langs in correct order
         $deps = $this->get_language_dependencies($lang);
         foreach ($deps as $dep) {
             // legacy location - used by contrib only
             if (file_exists("{$location}/lang/{$dep}/{$file}.php")) {
                 include "{$location}/lang/{$dep}/{$file}.php";
             }
             // the main lang string location
             if (file_exists("{$this->otherroot}/{$dep}/{$file}.php")) {
                 include "{$this->otherroot}/{$dep}/{$file}.php";
             }
             // local customisations
             if (!$disablelocal and file_exists("{$this->localroot}/{$dep}_local/{$file}.php")) {
                 include "{$this->localroot}/{$dep}_local/{$file}.php";
             }
         }
     }
     // we do not want any extra strings from other languages - everything must be in en lang pack
     $string = array_intersect_key($string, $originalkeys);
     // now we have a list of strings from all possible sources. put it into both in-memory and on-disk
     // caches so we do not need to do all this merging and dependencies resolving again
     $this->cache[$lang][$component] = $string;
     if ($this->usediskcache) {
         check_dir_exists("{$this->cacheroot}/{$lang}");
         file_put_contents("{$this->cacheroot}/{$lang}/{$component}.php", "<?php \$this->cache['{$lang}']['{$component}'] = " . var_export($string, true) . ";");
     }
     return $string;
 }
Exemple #29
0
/**
 * This gets the mod/block/course/core etc strings.
 *
 * @param string $component
 * @param int $contextlevel
 * @return string|bool String is success, false if failed
 */
function get_component_string($component, $contextlevel)
{
    if ($component === 'moodle' or $component === 'core') {
        switch ($contextlevel) {
            // TODO: this should probably use context level names instead
            case CONTEXT_SYSTEM:
                return get_string('coresystem');
            case CONTEXT_USER:
                return get_string('users');
            case CONTEXT_COURSECAT:
                return get_string('categories');
            case CONTEXT_COURSE:
                return get_string('course');
            case CONTEXT_MODULE:
                return get_string('activities');
            case CONTEXT_BLOCK:
                return get_string('block');
            default:
                print_error('unknowncontext');
        }
    }
    list($type, $name) = normalize_component($component);
    $dir = get_plugin_directory($type, $name);
    if (!file_exists($dir)) {
        // plugin not installed, bad luck, there is no way to find the name
        return $component . ' ???';
    }
    switch ($type) {
        // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
        case 'quiz':
            return get_string($name . ':componentname', $component);
            // insane hack!!!
        // insane hack!!!
        case 'repository':
            return get_string('repository', 'repository') . ': ' . get_string('pluginname', $component);
        case 'gradeimport':
            return get_string('gradeimport', 'grades') . ': ' . get_string('pluginname', $component);
        case 'gradeexport':
            return get_string('gradeexport', 'grades') . ': ' . get_string('pluginname', $component);
        case 'gradereport':
            return get_string('gradereport', 'grades') . ': ' . get_string('pluginname', $component);
        case 'webservice':
            return get_string('webservice', 'webservice') . ': ' . get_string('pluginname', $component);
        case 'block':
            return get_string('block') . ': ' . get_string('pluginname', basename($component));
        case 'mod':
            if (get_string_manager()->string_exists('pluginname', $component)) {
                return get_string('activity') . ': ' . get_string('pluginname', $component);
            } else {
                return get_string('activity') . ': ' . get_string('modulename', $component);
            }
        default:
            return get_string('pluginname', $component);
    }
}
Exemple #30
0
 /**
  * Resolves the real image location.
  * @param string $image name of image, may contain relative path
  * @param string $component
  * @return string full file path
  */
 public function resolve_image_location($image, $component)
 {
     global $CFG;
     if ($component === 'moodle' or $component === 'core' or empty($component)) {
         if ($imagefile = $this->image_exists("{$this->dir}/pix_core/{$image}")) {
             return $imagefile;
         }
         foreach (array_reverse($this->parent_configs) as $parent_config) {
             // base first, the immediate parent last
             if ($imagefile = $this->image_exists("{$parent_config->dir}/pix_core/{$image}")) {
                 return $imagefile;
             }
         }
         if ($imagefile = $this->image_exists("{$CFG->dataroot}/pix/{$image}")) {
             return $imagefile;
         }
         if ($imagefile = $this->image_exists("{$CFG->dirroot}/pix/{$image}")) {
             return $imagefile;
         }
         return null;
     } else {
         if ($component === 'theme') {
             //exception
             if ($image === 'favicon') {
                 return "{$this->dir}/pix/favicon.ico";
             }
             if ($imagefile = $this->image_exists("{$this->dir}/pix/{$image}")) {
                 return $imagefile;
             }
             foreach (array_reverse($this->parent_configs) as $parent_config) {
                 // base first, the immediate parent last
                 if ($imagefile = $this->image_exists("{$parent_config->dir}/pix/{$image}")) {
                     return $imagefile;
                 }
             }
             return null;
         } else {
             if (strpos($component, '_') === false) {
                 $component = 'mod_' . $component;
             }
             list($type, $plugin) = explode('_', $component, 2);
             if ($imagefile = $this->image_exists("{$this->dir}/pix_plugins/{$type}/{$plugin}/{$image}")) {
                 return $imagefile;
             }
             foreach (array_reverse($this->parent_configs) as $parent_config) {
                 // base first, the immediate parent last
                 if ($imagefile = $this->image_exists("{$parent_config->dir}/pix_plugins/{$type}/{$plugin}/{$image}")) {
                     return $imagefile;
                 }
             }
             if ($imagefile = $this->image_exists("{$CFG->dataroot}/pix_plugins/{$type}/{$plugin}/{$image}")) {
                 return $imagefile;
             }
             $dir = get_plugin_directory($type, $plugin);
             if ($imagefile = $this->image_exists("{$dir}/pix/{$image}")) {
                 return $imagefile;
             }
             return null;
         }
     }
 }