mahara.php 42.3 KB
Newer Older
1 2
<?php
/**
Nigel McNie's avatar
Nigel McNie committed
3
 * This program is part of Mahara
4
 *
5 6 7 8
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
9
 *
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 * @package    mahara
 * @subpackage core
 * @author     Penny Leach <penny@catalyst.net.nz>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006,2007 Catalyst IT Ltd http://catalyst.net.nz
 * @copyright  (C) portions from Moodle, (C) Martin Dougiamas http://dougiamas.com
25 26
 */

27
defined('INTERNAL') || die();
28

29 30 31 32 33 34 35
/** 
 * work around silly php settings
 * and broken setup stuff about the install
 * and raise a warning/fail depending on severity
 */
function ensure_sanity() {

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
    // PHP version
    if (version_compare(phpversion(), '5.1.0') < 0) {
        throw new ConfigSanityException(get_string('phpversion', 'error'));
    }

    // Various required extensions
    if (!extension_loaded('json')) {
        throw new ConfigSanityException(get_string('jsonextensionnotloaded', 'error'));
    }
    if (!extension_loaded('pgsql') && !extension_loaded('mysqli')) {
        throw new ConfigSanityException(get_string('dbextensionnotloaded', 'error'));
    }
    if (!extension_loaded('libxml')) {
        throw new ConfigSanityException(get_string('libxmlextensionnotloaded', 'error'));
    }
    if (!extension_loaded('gd')) {
        throw new ConfigSanityException(get_string('gdextensionnotloaded', 'error'));
    }
    if (!extension_loaded('session')) {
        throw new ConfigSanityException(get_string('sessionextensionnotloaded', 'error'));
    }

58 59
    // register globals workaround
    if (ini_get_bool('register_globals')) {
60
        log_environ(get_string('registerglobals', 'error'));
61
        $massivearray = array_keys(array_merge($_POST, $_GET, $_COOKIE, $_SERVER, $_REQUEST, $_FILES));
62 63 64 65 66 67 68
        foreach ($massivearray as $tounset) {
            unset($GLOBALS[$tounset]);
        }
    }

    // magic_quotes_gpc workaround
    if (ini_get_bool('magic_quotes_gpc')) {
69
        log_environ(get_string('magicquotesgpc', 'error'));
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        function stripslashes_deep($value) {
            $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);
            return $value;
        }
        $_POST = array_map('stripslashes_deep', $_POST);
        $_GET = array_map('stripslashes_deep', $_GET);
        $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
        $_REQUEST = array_map('stripslashes_deep', $_REQUEST);

        $servervars = array('REQUEST_URI','QUERY_STRING','HTTP_REFERER','PATH_INFO','PHP_SELF','PATH_TRANSLATED');
        foreach ($servervars as $tocheck) {
            if (array_key_exists($tocheck,$_SERVER) && !empty($_SERVER[$tocheck])) {
                $_SERVER[$tocheck] = stripslashes($_SERVER[$tocheck]);
            }
        }
    }

89
    if (ini_get_bool('magic_quotes_runtime')) {
90 91 92 93 94 95 96 97 98
        // Turn of magic_quotes_runtime. Anyone with this on deserves a slap in the face
        set_magic_quotes_runtime(0);
        log_environ(get_string('magicquotesruntime', 'error'));
    }

    if (ini_get_bool('magic_quotes_sybase')) {
        // See above comment re. magic_quotes_runtime
        @ini_set('magic_quotes_sybase', 0);
        log_environ(get_string('magicquotessybase', 'error'));
99 100
    }

101 102 103
    if (ini_get_bool('safe_mode')) {
        // We don't run with safe mode
        throw new ConfigSanityException(get_string('safemodeon', 'error'));
104 105
    }

106 107 108 109 110 111 112
    // Other things that might be worth checking:
    //    memory limit
    //    file_uploads (off|on)
    //    upload_max_filesize
    //    allow_url_fopen (only if we use this)
    //

113
    // dataroot inside document root.
114 115
    if (strpos(get_config('dataroot'), get_config('docroot')) !== false) {
        throw new ConfigSanityException(get_string('datarootinsidedocroot', 'error'));
116 117
    }

118 119
    // dataroot not writable..
    if (!check_dir_exists(get_config('dataroot')) || !is_writable(get_config('dataroot'))) {
120
        throw new ConfigSanityException(get_string('datarootnotwritable', 'error', get_config('dataroot')));
121
    }
122

123 124 125 126 127 128
    if (
        !check_dir_exists(get_config('dataroot') . 'smarty/compile') ||
        !check_dir_exists(get_config('dataroot') . 'smarty/cache') ||
        !check_dir_exists(get_config('dataroot') . 'templates')) {
        throw new ConfigSanityException(get_string('couldnotmakedatadirectories', 'error'));
    }
129 130
}

131 132 133 134 135
/**
 * Check to see if the internal plugins are installed. Die if they are not.
 */
function ensure_internal_plugins_exist() {
    // Internal things installed
136
    if (get_config('installed')) {
137 138 139 140 141 142 143 144
        foreach (plugin_types() as $type) {
            if (!record_exists($type . '_installed', 'name', 'internal')) {
                throw new ConfigSanityException(get_string($type . 'notinstalled'));
            }
        }
    }
}

145
function get_string($identifier, $section='mahara') {
146 147 148 149 150

    $variables = func_get_args();
    if (count($variables) > 2) { // we have some stuff we need to sprintf
        array_shift($variables);
        array_shift($variables); //shift off the first two.
151 152
    }
    else {
153 154 155
        $variables = array();
    }
    
156 157 158 159 160 161 162 163
    return get_string_location($identifier, $section, $variables);
}

// get a string without sprintfing it.
function get_raw_string($identifier, $section='mahara') {
    // For a raw string we don't want to format any arguments using
    // sprintf, so the replace function passed to get_string_location
    // should just return the first argument and ignore the second.
164 165
    return get_string_location($identifier, $section, array(), 
                               create_function('$string, $args','return $string;'));
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
}


/**
 * This function gets a language string identified by $identifier from
 * an appropriate location, and formats the string and any arguments
 * in $variables using the function $replacefunc.
 *
 * @param string   $identifier
 * @param string   $section
 * @param array    $variables
 * @param function $replacefunc
 * @return string
 */
function get_string_location($identifier, $section, $variables, $replacefunc='format_langstring') {

    $langconfigstrs = array('parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
                            'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
                            'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
Richard Mansfield's avatar
Richard Mansfield committed
185
                            'strfdaymonthyearshort', 'thislanguage');
186 187 188 189 190

    if (in_array($identifier, $langconfigstrs)) {
        $section = 'langconfig';
    }

191 192 193 194 195 196
    $lang = current_language();

    // Define the locations of language strings for this section
    $docroot = get_config('docroot');
    $locations = array();
    
197
    if (false === strpos($section, '.')) {
198 199 200 201
        $locations[] = $docroot . 'lang/';
    }
    else {
        $extras = plugin_types(); // more later..
202
        foreach ($extras as $tocheck) {
203
            if (strpos($section,$tocheck . '.') === 0) {
Nigel McNie's avatar
Nigel McNie committed
204
                $pluginname = substr($section ,strlen($tocheck) + 1);
205
                $locations[] = $docroot . $tocheck . '/' . $pluginname . '/lang/';
206 207 208
            }
        }
    }
209

210 211 212
    // First check all the normal locations for the string in the current language
    foreach ($locations as $location) {
        //if local directory not found, or particular string does not exist in local direcotry
213
        $langfile = $location . $lang . '/' . $section . '.php';
Penny Leach's avatar
Penny Leach committed
214
        if (is_readable($langfile)) {
215
            if ($result = get_string_from_file($identifier, $langfile)) {
216
                return $replacefunc($result, $variables);
217 218 219 220 221 222 223
            }
        }
    }

    // If the preferred language was English (utf8) we can abort now
    // saving some checks beacuse it's the only "root" lang
    if ($lang == 'en.utf8') {
224
        return '[[' . $identifier . '/' . $section . ']]';
225 226 227 228
    }

    // Is a parent language defined?  If so, try to find this string in a parent language file
    foreach ($locations as $location) {
229
        $langfile = $location . $lang . '/langconfig.php';
Penny Leach's avatar
Penny Leach committed
230
        if (is_readable($langfile)) {
231
            if ($parentlang = get_string_from_file('parentlanguage', $langfile)) {
232
                $langfile = $location . $parentlang . '/' . $section . '.php';
Penny Leach's avatar
Penny Leach committed
233
                if (is_readable($langfile)) {
234
                    if ($result = get_string_from_file($identifier, $langfile)) {
235
                        return $replacefunc($result, $variables);
236 237 238 239 240 241 242 243 244
                    }
                }
            }
        }
    }

    /// Our only remaining option is to try English
    foreach ($locations as $location) {
        //if local_en not found, or string not found in local_en
245
        $langfile = $location . 'en.utf8/' . $section . '.php';
Penny Leach's avatar
Penny Leach committed
246
        if (is_readable($langfile)) {
247
            if ($result = get_string_from_file($identifier, $langfile)) {
248
                return $replacefunc($result, $variables);
249 250 251 252
            }
        }
    }

253
    return '[[' . $identifier . '/' . $section . ']]';  // Last resort
254
}
255 256


257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
/**
 * Return a list of available languages
 *
 */
function get_languages() {
    $langs = array();
    $langbase = get_config('docroot') . 'lang/';
    if (!$langdir = opendir($langbase)) {
        throw new Exception('Unable to read language directory '.$langbase);
    }
    while (false !== ($subdir = readdir($langdir))) {
        $langfile = $langbase . $subdir . '/langconfig.php';
        if ($subdir != "." && $subdir != ".." && is_readable($langfile)) {
            if ($langname = get_string_from_file('thislanguage',$langfile)) {
                $langs[$subdir] = $langname;
            }
        }
    }
    closedir($langdir);
    return $langs;
}

/**
 * Return a list of available themes
 * Need to add the theme names sometime; for now use get_string().
 *
 */
function get_themes() {
    $themes = array();
    $themebase = get_config('docroot') . 'theme/';
    if (!$themedir = opendir($themebase)) {
        throw new Exception('Unable to read theme directory '.$themebase);
    }
    while (false !== ($subdir = readdir($themedir))) {
        // Where do we get theme names from?
        if ($subdir != "." && $subdir != "..") {
            $themes[$subdir] = get_string($subdir);
        }
    }
    closedir($themedir);
    return $themes;
}


301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
/**
 * This function is only used from {@link get_string()}.
 *
 * @internal Only used from get_string, not meant to be public API
 * @param string $identifier ?
 * @param string $langfile ?
 * @param string $destination ?
 * @return string|false ?
 * @staticvar array $strings Localized strings
 * @access private
 * @todo Finish documenting this function.
 */
function get_string_from_file($identifier, $langfile) {

    static $strings;    // Keep the strings cached in memory.

    if (empty($strings[$langfile])) {
        $string = array();
        include ($langfile);
        $strings[$langfile] = $string;
    } else {
        $string = &$strings[$langfile];
    }

    if (!isset ($string[$identifier])) {
        return false;
    }

    return $string[$identifier];
}

/**
 * This function makes the return value of ini_get consistent if you are
 * setting server directives through the .htaccess file in apache.
 * Current behavior for value set from php.ini On = 1, Off = [blank]
 * Current behavior for value set from .htaccess On = On, Off = Off
 * Contributed by jdell @ unr.edu
 *
339
 * @param string $ini_get_arg setting to look for
340 341 342 343 344 345 346 347 348 349 350
 * @return bool
 */
function ini_get_bool($ini_get_arg) {
    $temp = ini_get($ini_get_arg);

    if ($temp == '1' or strtolower($temp) == 'on') {
        return true;
    }
    return false;
}

351 352 353 354 355 356 357 358 359 360 361
/**
 * This function loads up the basic $CFG
 * from the database table
 * note that it doesn't load plugin config
 * as not every page needs them
 * @return boolean false if the assignment fails (generally if the databse is not installed)
 */
function load_config() {
    global $CFG;
    
    try {
362
        $dbconfig = get_records_array('config');
363
    } 
364
    catch (SQLException $e) {
365 366 367 368
        return false;
    }
    
    foreach ($dbconfig as $cfg) {
369
        if (isset($CFG->{$cfg->field}) && $CFG->{$cfg->field} != $cfg->value) {
Penny Leach's avatar
Penny Leach committed
370
            // @todo warn that we're overriding db config with $CFG
371 372 373 374 375 376 377 378 379
            continue;
        }
        $CFG->{$cfg->field} = $cfg->value;
    }

    return true;
}

/**
380 381 382 383 384 385
 * This function returns a value from $CFG
 * or null if it is not found
 * 
 * @param string $key config setting to look for 
 * @return mixed
 */
386 387 388 389 390 391 392 393
function get_config($key) {
    global $CFG;
    if (array_key_exists($key,$CFG)) {
        return $CFG->$key;
    }
    return null;
}

394 395 396 397 398 399 400 401 402

/**
 * This function sets a config variable
 * both in $CFG and in the database
 *
 * @param string $key config field to set
 * @param string $value config value
 */
function set_config($key, $value) {
403 404 405 406
    global $CFG;

    if (get_record('config', 'field', $key)) {
        if (set_field('config', 'value', $value, 'field', $key)) {
Penny Leach's avatar
Penny Leach committed
407 408 409 410 411 412 413
            $status = true;
        }
    } 
    else {
        $config = new StdClass;
        $config->field = $key;
        $config->value = $value;
414
        $status = insert_record('config', $config);
Penny Leach's avatar
Penny Leach committed
415 416 417
    }

    if (!empty($status)) {
418 419 420
        $CFG->{$key} = $value;
        return true;
    }
Penny Leach's avatar
Penny Leach committed
421

422 423 424 425 426 427 428 429 430 431 432 433 434 435
    return false;
}

/**
 * This function returns a value for $CFG for a plugin
 * or null if it is not found
 * note that it may go and look in the database
 *
 * @param string $plugintype eg artefact
 * @param string $pluginname eg blog
 * @param string $key the config setting to look for
 */
function get_config_plugin($plugintype, $pluginname, $key) {
    global $CFG;
436

437 438 439 440 441 442 443
    if (array_key_exists('plugin',$CFG)
        && array_key_exists($plugintype,$CFG->plugin)
        && array_key_exists($pluginname,$CFG->plugin->{$plugintype})
        && array_key_exists($key,$CFG->plugin->{$plugintype}->{$pluginname})) {
        return  $CFG->plugin->{$plugintype}->{$pluginname}->{$key};
    }
    
444 445 446
    // @todo: an optimisation might be to get all fields related to the plugin instead, as
    // it may be quite likely that if one config item is requested for a plugin another
    // might be.
447
    if (!$value = get_field($plugintype . '_config', 'value', 'plugin', $pluginname, 'field', $key)) {
448
        $value = null;
449 450
    }

451 452 453 454
    $CFG->plugin->{$plugintype}->{$pluginname}->{$key} = $value;
    return $value;
}

Penny Leach's avatar
Penny Leach committed
455
function set_config_plugin($plugintype, $pluginname, $key, $value) {
456
    global $CFG;
457
    $table = $plugintype . '_config';
Penny Leach's avatar
Penny Leach committed
458

459 460 461
    if (false !== get_field($table, 'value', 'plugin', $pluginname, 'field', $key)) {
        //if (set_field($table, 'value', $key, 'plugin', $pluginname, 'field', $value)) {
        if (set_field($table, 'value', $value, 'plugin', $pluginname, 'field', $key)) {
Penny Leach's avatar
Penny Leach committed
462 463 464 465 466 467 468 469
            $status = true;
        }
    }
    else {
        $pconfig = new StdClass;
        $pconfig->plugin = $pluginname;
        $pconfig->field  = $key;
        $pconfig->value  = $value;
470
        $status = insert_record($table, $pconfig);
Penny Leach's avatar
Penny Leach committed
471 472 473 474 475 476 477 478
    }
    if ($status) {
        $CFG->plugin->{$plugintype}->{$pluginname}->{$key} = $value;
        return true;
    }
    return false;
}

479
/**
480 481 482 483 484
 * This function prints an array or object
 * wrapped inside <pre></pre>
 * 
 * @param $mixed value to print
 */
485 486 487 488 489 490
function print_object($mixed) {
    echo '<pre>';
    print_r($mixed);
    echo '</pre>';
}

491
/**
492 493 494 495 496 497
 * This function returns the current 
 * language to use, either for a given user
 * or sitewide, or the default
 * 
 * @return string
 */
498 499
function current_language() {
    global $USER, $CFG;
500
    if ($USER instanceof User && null !== ($lang = $USER->get_account_preference('lang'))) {
501
        return $lang;
502 503 504 505 506 507 508
    }
    if (!empty($CFG->lang)) {
        return $CFG->lang;
    }
    return 'en.utf8';
}

509
/**
510 511 512 513 514 515
 * Helper function to sprintf language strings
 * with a variable number of arguments
 * 
 * @param string $string raw string to use
 * @param array $args arguments to sprintf
 */
516 517 518 519
function format_langstring($string,$args) {
    return call_user_func_array('sprintf',array_merge(array($string),$args));
}

520 521 522 523 524 525 526 527 528 529 530 531 532
/**
 * Helper function to figure out whether an array is an array or a hash
 * @param array $array array to check
 * @return bool true if the array is a hash
 */
function is_hash($array) {
    if (!is_array($array)) {
        return false;
    }
    $diff = array_diff_assoc($array,array_values($array));
    return !empty($diff);
}

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
/**
 * Function to check if a directory exists and optionally create it.
 *
 * @param string absolute directory path
 * @param boolean create directory if does not exist
 * @param boolean create directory recursively
 *
 * @return boolean true if directory exists or created
 */
function check_dir_exists($dir, $create=true, $recursive=true) {

    $status = true;

    if(!is_dir($dir)) {
        if (!$create) {
            $status = false;
        } else {
            umask(0000); 
551
            $status = @mkdir($dir, 0777, true);
Nigel McNie's avatar
Nigel McNie committed
552
            // @todo has the umask been clobbered at this point, and is this a bad thing?
553 554 555 556 557
        }
    }
    return $status;
}

Penny Leach's avatar
Penny Leach committed
558 559 560
/**
 * Function to require a plugin file. This is to avoid doing 
 * require and include directly with variables.
561
 *
Penny Leach's avatar
Penny Leach committed
562 563
 * This function is the one safe point to require plugin files.
 * so USE it :)
564
 *
Penny Leach's avatar
Penny Leach committed
565 566 567 568 569 570
 * @param string $plugintype the type of plugin (eg artefact)
 * @param string $pluginname the name of the plugin (eg blog)
 * @param string $filename the name of the file to include within the plugin structure
 * @param string $function (optional, defaults to require) the require/include function to use
 * @param string $nonfatal (optional, defaults to false) just returns false if the file doesn't exist
 */
571
function safe_require($plugintype, $pluginname, $filename='lib.php', $function='require_once', $nonfatal=false) {
572 573 574 575
    $plugintypes = plugin_types();
    if (!in_array($plugintype, $plugintypes)) {
        throw new Exception("\"$plugintype\" is not a valid plugin type");
    }
576 577
    require_once(get_config('docroot') . $plugintype . '/lib.php');

578
    if (!in_array($function,array('require', 'include', 'require_once', 'include_once'))) {
Penny Leach's avatar
Penny Leach committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
        if (!empty($nonfatal)) {
            return false;
        }
        throw new Exception ('invalid require type');
    }

    $fullpath = get_config('docroot') . $plugintype . '/' . $pluginname . '/' . $filename;
    if (!$realpath = realpath($fullpath)) {
        if (!empty($nonfatal)) {
            return false;
        }
        throw new Exception ("File $fullpath did not exist");
    }

    if (strpos($realpath, get_config('docroot') !== 0)) {
        if (!empty($nonfatal)) {
            return false;
        }
        throw new Exception ("File $fullpath was outside document root!");
    }

    if ($function == 'require') { return require($realpath); }
    if ($function == 'include') { return include($realpath); }
    if ($function == 'require_once') { return require_once($realpath); }
    if ($function == 'include_once') { return include_once($realpath); }
    
}

607 608 609 610 611 612 613
/**
 * This function returns the list of plugintypes we currently care about
 * @return array of names
 */
function plugin_types() {
    static $pluginstocheck;
    if (empty($pluginstocheck)) {
614
        $pluginstocheck = array('artefact', 'auth', 'notification', 'search');
615 616 617 618
    }
    return $pluginstocheck;
}

619 620 621 622 623 624 625
/** 
 * This return returns the names of plugins installed 
 * for the given plugin type.
 * 
 * @param string $plugintype type of plugin
 */
function plugins_installed($plugintype) {
626
    return get_records_array($plugintype . '_installed');
627 628
}

629 630 631 632 633 634 635 636 637 638 639
/**
 * Helper to call a static method when you do not know the name of the class
 * you want to call the method on. PHP5 does not support $class::method().
 */
function call_static_method($class, $method) {
    $args = func_get_args();
    array_shift($args);
    array_shift($args);
    return call_user_func_array(array($class, $method), $args);
}

640 641 642 643 644
function generate_class_name() {
    $args = func_get_args();
    return 'Plugin' . implode('', array_map('ucfirst', $args));
}

645 646 647 648
function generate_artefact_class_name($type) {
    return 'ArtefactType' . ucfirst($type);
}

649 650 651 652 653
/**
 * Fires an event which can be handled by different parts of the system
 */
function handle_event($event, $data) {
    if (!$e = get_record('event_type', 'name', $event)) {
Martyn Smith's avatar
Martyn Smith committed
654
        throw new Exception("Invalid event");
Penny Leach's avatar
Penny Leach committed
655
    }
656 657 658 659

    // this is here because the core can't listen to events
    // @todo, this is VERY ugly, and someone should fix it
    if ($event == 'createuser') {
660
        activity_set_defaults($data->id);
661 662
    }

Penny Leach's avatar
Penny Leach committed
663 664
    $plugintypes = plugin_types();
    foreach ($plugintypes as $name) {
665
        if ($subs = get_records_array($name . '_event_subscription', 'event', $event)) {
Penny Leach's avatar
Penny Leach committed
666
            foreach ($subs as $sub) {
667
                safe_require($name, $sub->plugin);
Penny Leach's avatar
Penny Leach committed
668 669
                $classname = 'Plugin' . ucfirst($name) . ucfirst($sub->plugin);
                try {
670
                    call_static_method($classname, $sub->callfunction, $event, $data);
Penny Leach's avatar
Penny Leach committed
671 672 673 674 675 676 677 678 679 680
                }
                catch (Exception $e) {
                    log_warn("Event $event caused an exception from plugin $classname "
                             . "with function $sub->callfunction. Continuing with event handlers");
                }
            }
        }
    }
}

681 682 683 684 685 686 687 688 689 690 691 692 693 694
/**
 * function to convert an array of objects to 
 * an array containing one field per place
 * 
 * @param array $array input array
 * @param mixed $field field to look for in each object
 */
function mixed_array_to_field_array($array, $field) {
    $repl_fun = create_function('$n, $field', '$n = (object)$n; return $n->{$field};');
    $fields = array_pad(array(), count($array), $field);
    return array_map($repl_fun, $array, $fields);
}


Penny Leach's avatar
Penny Leach committed
695 696
/** 
 * Adds stuff to the log
697
 * @todo write this function
Penny Leach's avatar
Penny Leach committed
698 699 700 701 702 703 704 705 706 707 708 709
 *
 * @param string $plugintype plugin type or core
 * @param string $pluginname plugin name or core component (eg 'view')
 * @param string $action action string (like 'add')
 * @param int $user id of user making the action
 * @param int $id relevant id (ie, profile view would have id of profile owner)
 * 
 */
function add_to_log($plugintype, $pluginname, $action, $user, $id=0) {

}

710 711 712 713
/**
 * Used by XMLDB
 */
function debugging ($message, $level) {
714
    log_debug($message);
715 716 717 718 719 720
}
function xmldb_dbg($message) {
    log_warn($message);
}
define('DEBUG_DEVELOPER', 'whocares');

721 722 723
/** 
 * Base class for all plugintypes.
 */
724
class Plugin {
725
    
726 727
    /**
     * This function returns an array of crons it wants to have run
728
     * Each item should be a StdClass object containing - 
729 730 731 732
     * - callfunction (static function on the Plugin Class)
     * - any or all of minute, hour, day, month, dayofweek 
     * (will default to * if not supplied)
     */
733 734 735 736
    public static function get_cron() {
        return array();
    }

737 738 739 740 741 742 743
    /** 
     * This function returns an array of events to subscribe to
     * by unique name. 
     * If an event the plugin is trying to subscribe to is unknown by the
     * core, an exception will be thrown.
     * @return array
     */
744 745 746 747
    public static function get_event_subscriptions() {
        return array();
    }

748 749 750 751 752 753 754

    /**
     * This function will be run after every upgrade to the plugin.
     * 
     * @param int $fromversion version upgrading from (or 0 if installing)
     */
    public static function postinst($fromversion) {
755 756
        return true;
    }
757

758 759 760 761 762
    /**
     * Whether this plugin has admin plugin config options.
     * If you return true here, you must supply a valid pieform
     * in {@link get_config}
     */
763 764 765
    public static function has_config() {
        return false;
    }
766 767
}

768 769 770 771 772 773 774 775 776 777
/**
 * formats a unix timestamp to a nice date format.
 * 
 * @param int $date unix timestamp to format
 * @param string $formatkey language key to fetch the format from
 * (see langconfig.php or the top of {@link get_string_location}
 * for supported keys
 */

function format_date($date, $formatkey='strftimedatetime') {
778 779 780
    if (empty($date)) {
        return get_string('strftimenotspecified');
    }
781 782 783
    return strftime(get_string($formatkey), $date);
}

784 785 786
/**
 * Returns a random string suitable for registration/change password requests
 *
787
 * @param int $length The length of the key to return
788 789
 * @return string
 */
790 791 792 793
function get_random_key($length=16) {
    if ($length < 1) {
        throw new IllegalArgumentException('Length must be a positive number');
    }
794 795 796 797 798 799 800
    $pool = array_merge(
        range('A', 'Z'),
        range('a', 'z'),
        range(0, 9)
    );
    shuffle($pool);
    $result = '';
801
    for ($i = 0; $i < $length; $i++) {
802 803 804 805 806
        $result .= $pool[$i];
    }
    return $result;
}

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
/**
 * Given a form, an array of values with 'password1' and 'password2'
 * indices and a user, validate that the user can change their password to
 * the one in $values.
 *
 * This provides one place where validation of passwords can be done. This is
 * used by:
 *  - registration
 *  - user forgot password
 *  - user changing password on their account page
 *  - user forced to change their password by the <kbd>passwordchange</kbd>
 *    flag on the <kbd>usr</kbd> table.
 *
 * The password is checked for:
 *  - Being in valid form according to the rules of the authentication method
 *    for the user
 *  - Not being an easy password (a blacklist of strings, NOT a length check or
 *     similar), including being the user's username
 *  - Both values being equal
 *
827 828 829
 * @param Pieform $form         The form to validate
 * @param array $values         The values passed through
 * @param string $authplugin    The authentication plugin that the user uses
830
 */
831 832
function password_validate(Pieform $form, $values, $username, $institution) {
    $authtype  = auth_get_authtype_for_institution($institution);
833
    $authclass = 'Auth' . ucfirst($authtype);
834
    safe_require('auth', $authtype);
835
    if (!$form->get_error('password1') && !call_static_method($authclass, 'is_password_valid', ($values['password1']))) {
836
        $form->set_error('password1', get_string('passwordinvalidform', "auth.$authtype"));
837 838 839
    }

    $suckypasswords = array(
840
        'mahara', 'password', $username
841 842 843 844 845 846 847 848
    );
    if (!$form->get_error('password1') && in_array($values['password1'], $suckypasswords)) {
        $form->set_error('password1', get_string('passwordtooeasy'));
    }

    if (!$form->get_error('password1') && $values['password1'] != $values['password2']) {
        $form->set_error('password2', get_string('passwordsdonotmatch'));
    }
Nigel McNie's avatar
Nigel McNie committed
849 850

    // No Mike, that's a _BAD_ Mike! :)
851
    if ($values['password1'] == 'mike01' || $values['password1'] == 'mike012') {
Nigel McNie's avatar
Nigel McNie committed
852 853 854 855 856 857
        if (!$form->get_property('jsform')) {
            die_info('<img src="'
                . theme_get_image_url('images/sidebox1_corner_botright.gif')
                . '" alt="(C) 2007 MSS Enterprises"></p>');
        }
    }
858 859
}

860

861 862 863 864
//
// Pieform related functions
//

865 866 867
/**
 * Configures a default form
 */
868
function pieform_configure() {
869
    global $USER;
870
    return array(
871 872
        'method'    => 'post',
        'action'    => '',
873
        'autofocus' => true,
874
        'renderer'  => 'maharatable',
Nigel McNie's avatar
Nigel McNie committed
875
        'elementclasses' => true,
876 877 878 879 880 881
        'jserrorcallback'       => 'formError',
        'globaljserrorcallback' => 'formGlobalError',
        'jssuccesscallback'     => 'formSuccess',
        'presubmitcallback'     => 'formStartProcessing',
        'postsubmitcallback'    => 'formStopProcessing',
        'jserrormessage' => get_string('errorprocessingform'),
882 883
        'configdirs' => get_config('libroot') . 'form/',
        'elements'   => array(
884
            'sesskey' => array(
885
                'type'  => 'hidden',
886
                'value' => $USER->get('sesskey')
887 888 889 890 891
            )
        )
    );
}

892 893 894 895 896
function pieform_validate(Pieform $form, $values) {
    global $USER;
    if (!isset($values['sesskey'])) {
        throw new UserException('No session key');
    }
897
    if ($USER && $USER->get('sesskey') != $values['sesskey']) {
898 899 900 901 902
        throw new UserException('Invalid session key');
    }

    // Check to make sure the user has not been suspended, so that they cannot
    // perform any action
903 904 905 906 907 908 909
    if ($USER) {
        $record = get_record_sql('SELECT suspendedctime, suspendedreason
            FROM ' . get_config('dbprefix') . 'usr
            WHERE id = ?', array($USER->get('id')));
        if ($record && $record->suspendedctime) {
            throw new UserException(get_string('accountsuspended', 'mahara', $record->suspendedctime, $record->suspendedreason));
        }
910 911 912
    }
}

913
function pieform_element_calendar_configure($element) {
914 915 916
    $element['jsroot'] = '/js/jscalendar/';
    $element['themefile'] = get_config('themeurl') . 'style/calendar.css';
    $element['imagefile'] = get_config('themeurl') . 'calendar.gif';
917
    $element['language'] = 'en'; // @todo: language file names for the js calendar may need to be changed
918 919 920
    return $element;
}

921 922 923 924 925
function pieform_element_textarea_configure($element) {
    $element['resizable'] = true;
    return $element;
}

926 927 928 929 930 931 932 933 934 935
/**
 * Given a view id, and a user id (defaults to currently logged in user if not
 * specified) will return wether this user is allowed to look at this view.
 *
 * @param integer $view_id      View ID to check
 * @param integer $user_id      User trying to look at the view (defaults to
 * currently logged in user, or null if user isn't logged in)
 *
 * @returns boolean Wether the specified user can look at the specified view.
 */
Martyn Smith's avatar
Martyn Smith committed
936
function can_view_view($view_id, $user_id=null) {
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    global $USER;
    $now = time();
    $dbnow = db_format_timestamp($now);
    $prefix = get_config('dbprefix');

    if ($user_id === null) {
        $user_id = $USER->get('id');
    }

    $view_data = get_records_sql_array('
        SELECT
            v.title,
            v.owner,
            ' . db_format_tsfield('v.startdate','startdate') . ',
            ' . db_format_tsfield('v.stopdate','stopdate') . ',
            a.accesstype,
953
            v.submittedto,
954 955 956 957 958 959 960 961 962 963 964 965 966 967
            ' . db_format_tsfield('a.startdate','access_startdate') . ',
            ' . db_format_tsfield('a.stopdate','access_stopdate') . '
        FROM
            ' . $prefix . 'view v
            LEFT OUTER JOIN ' . $prefix . 'view_access a ON v.id=a.view
        WHERE v.id=?
    ', array($view_id));

    if(!$view_data) {
        throw new ViewNotFoundException("View id=$view_id doesn't exist");
    }

    $view_record = array( 'access' => array() );

Martyn Smith's avatar
Martyn Smith committed
968
    log_debug('Can you look at this view? (you are user ' . $user_id . ' trying to look at view ' . $view_id . ')');
969 970 971 972 973 974

    foreach ( $view_data as $row ) {
        $view_record['title'] = $row->title;
        $view_record['owner'] = $row->owner;
        $view_record['startdate'] = $row->startdate;
        $view_record['stopdate'] = $row->stopdate;
975
        $view_record['submittedto'] = $row->submittedto;
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991

        if (!isset($row->accesstype)) {
            continue;
        }
        
        $view_record['access'][$row->accesstype] = array(
            'startdate' => $row->access_startdate,
            'stopdate' => $row->access_stopdate,
        );
    }

    if ($USER->is_logged_in() && $view_record['owner'] == $user_id) {
        log_debug('Yes - you own this view');
        return true;
    }

992 993 994 995 996
    if ($view_record['submittedto'] && record_exists('community_member', 'community', $view_record['submittedto'], 'member', $user_id, 'tutor', 1)) {
        log_debug('Yes - View is submitted for assesment to a community you are a tutor in');
        return true;
    }

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    // check public
    if (
        isset($view_record['access']['public'])
        && (    
            $view_record['access']['public']['startdate'] == null
            || $view_record['access']['public']['startdate'] < $now
        )
        && (
            $view_record['access']['public']['stopdate'] == null
            || $view_record['access']['public']['stopdate'] > $now
        )
Martyn Smith's avatar
Martyn Smith committed
1008
    ) {
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

        log_debug('Yes - View is public');
        return true;
    }

    // everything below this point requires that you be logged in
    if (!$USER->is_logged_in()) {
        log_debug('No - you are not logged in');
        return false;
    }

    // check logged in
    if (
        isset($view_record['access']['loggedin'])
        && (    
            $view_record['access']['loggedin']['startdate'] == null
            || $view_record['access']['loggedin']['startdate'] < $now
        )
        && (
            $view_record['access']['loggedin']['stopdate'] == null
            || $view_record['access']['loggedin']['stopdate'] > $now
        )
Martyn Smith's avatar
Martyn Smith committed
1031
    ) {
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

        log_debug('Yes - View is available to logged in users');
        return true;
    }

    // check friends access
    if (
        isset($view_record['access']['friends'])
        && (    
            $view_record['access']['friends']['startdate'] == null
            || $view_record['access']['friends']['startdate'] < $now
        )
        && (
            $view_record['access']['friends']['stopdate'] == null
            || $view_record['access']['friends']['stopdate'] > $now
        )
        && get_field_sql(
            'SELECT COUNT(*) FROM ' . $prefix . 'usr_friend f WHERE (usr1=? AND usr2=?) OR (usr1=? AND usr2=?)',
            array( $view_record['owner'], $user_id, $user_id, $view_record['owner'] )
        )
Martyn Smith's avatar
Martyn Smith committed
1052
    ) {
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        log_debug('Yes - View is available to friends of the owner');
        return true;
    }

    // check user access
    if (get_field_sql(
        'SELECT
            a.view
        FROM 
            ' . $prefix . 'view_access_usr a
        WHERE
            a.view=? AND a.usr=?
Martyn Smith's avatar
Martyn Smith committed
1065 1066
            AND ( a.startdate < ? OR a.startdate IS NULL )
            AND ( a.stopdate > ?  OR a.stopdate  IS NULL )
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        LIMIT 1',
        array( $view_id, $user_id, $dbnow, $dbnow )
        )
    ) {
        log_debug('Yes - View is available to your user');
        return true;
    }

    // check group access
    if (get_field_sql(
        'SELECT
            a.view
        FROM 
            ' . $prefix . 'view_access_group a
            INNER JOIN ' . $prefix . 'usr_group g ON a.grp = g.id
            INNER JOIN ' . $prefix . 'usr_group_member m ON g.id = m.grp
        WHERE
            a.view=? AND m.member=?
Martyn Smith's avatar
Martyn Smith committed
1085 1086
            AND ( a.startdate < ? OR a.startdate IS NULL )
            AND ( a.stopdate > ?  OR a.stopdate  IS NULL )
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        LIMIT 1',
        array( $view_id, $user_id, $dbnow, $dbnow )
        )
    ) {
        log_debug('Yes - View is available to one of the owners groups');
        return true;
    }

    // check community access
    if (get_field_sql(
        'SELECT
            a.view
        FROM
            ' . $prefix . 'view_access_community a
            INNER JOIN ' . $prefix . 'community c ON a.community = c.id
            INNER JOIN ' . $prefix . 'community_member m ON c.id=m.community
        WHERE
            a.view=? AND m.member=?
Martyn Smith's avatar
Martyn Smith committed
1105 1106
            AND ( a.startdate < ? OR a.startdate IS NULL )
            AND ( a.stopdate > ?  OR a.stopdate  IS NULL )
1107 1108 1109 1110 1111 1112 1113 1114 1115
            AND ( a.tutoronly = 0 OR m.tutor = 1 )
        LIMIT 1',
        array( $view_id, $user_id, $dbnow, $dbnow )
        )
    ) {
        log_debug('Yes - View is available to a specific community');
        return true;
    }

1116 1117 1118 1119 1120 1121
    // check admin
    if (get_field('usr', 'admin', 'id', $user_id)) {
        log_debug('Yes - You are a site administrator');
        return true;
    }

1122 1123 1124 1125 1126

    log_debug('No - nothing matched');
    return false;
}

Penny Leach's avatar
Penny Leach committed
1127 1128 1129 1130 1131 1132
/**
 * get the views that a user can see belonging
 * to the given users
 *
 * @param array $users users to fetch views owned by
 * @param int $userlooking (optional, defaults to logged in user)
1133 1134 1135
 * @param int $limit grab this many views. (setting this null means get all)
 *
 * @return array Associative array keyed by userid, of arrays of view ids
Penny Leach's avatar
Penny Leach committed
1136 1137 1138 1139 1140 1141
 */
function get_views($users, $userlooking=null, $limit=5) {
    $userlooking = optional_userid($userlooking);
    if (is_int($users)) {
        $users = array($users);
    }
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183

    $list = array();

    if(count($users) == 0) {
        return $list;
    }

    $users = array_flip($users);

    $prefix = get_config('dbprefix');
    $dbnow  = db_format_timestamp(time());

    if ($friends = get_records_sql_array(
        'SELECT
            CASE WHEN usr1=? THEN usr2 ELSE usr1 END AS id
        FROM
            ' . $prefix . 'usr_friend f
        WHERE
            ( usr1=? AND usr2 IN (' . join(',',array_map('db_quote', array_keys($users))) . ') )
            OR
            ( usr2=? AND usr1 IN (' . join(',',array_map('db_quote', array_keys($users))) . ') )
        ',
        array($userlooking,$userlooking,$userlooking)
    )) {
        foreach ( $friends as $user_id ) {
            $users[$user_id->id] = 'friend';
        }
    }

    // public, logged in, or friends' views
    if ($results = get_records_sql_array(
        'SELECT
            v.*,
            ' . db_format_tsfield('atime') . ',
            ' . db_format_tsfield('mtime') . ',
            ' . db_format_tsfield('ctime') . '
        FROM 
            ' . $prefix . 'view v
            INNER JOIN ' . $prefix . 'view_access a ON
                v.id=a.view
                AND (
                    accesstype IN (\'public\',\'loggedin\')
1184 1185 1186 1187 1188 1189 1190 1191 1192
            ' . (
                    count(preg_grep('/^friend$/', $users)) > 0
                    ?  'OR (
                            accesstype = \'friends\'
                            AND v.owner IN (' . join(',',array_map('db_quote', array_keys(preg_grep('/^friend$/', $users)))) . ')
                        )'
                    : ''
                )
            . '
1193 1194 1195 1196
                )
        WHERE
            v.owner IN (' . join(',',array_map('db_quote', array_keys($users))) . ')
            AND ( v.startdate IS NULL OR v.startdate < ? )
Martyn Smith's avatar
Martyn Smith committed
1197
            AND ( v.stopdate IS NULL OR v.stopdate > ? )
1198 1199 1200 1201 1202 1203 1204 1205
        ',
        array( $dbnow, $dbnow )
        )
    ) {
        foreach ($results as &$row) {
            $list[$row->owner][$row->id] = $row;
        }
    }
Martyn Smith's avatar
Martyn Smith committed
1206 1207

    // bail if we've filled all users to the limit
1208 1209 1210 1211
    if (_get_views_trim_list($list, $users, $limit)) {
        return $list;
    }

Martyn Smith's avatar
Martyn Smith committed
1212
    // check individual user access
1213 1214 1215 1216 1217 1218 1219 1220
    if ($results = get_records_sql_array(
        'SELECT
            v.*,
            ' . db_format_tsfield('atime') . ',
            ' . db_format_tsfield('mtime') . ',
            ' . db_format_tsfield('ctime') . '
        FROM 
            ' . $prefix . 'view v
1221
            INNER JOIN ' . $prefix . 'view_access_usr a ON v.id=a.view AND a.usr=?
1222 1223 1224
        WHERE
            v.owner IN (' . join(',',array_map('db_quote', array_keys($users))) . ')
            AND ( v.startdate IS NULL OR v.startdate < ? )
Martyn Smith's avatar
Martyn Smith committed
1225
            AND ( v.stopdate IS NULL OR v.stopdate > ? )
1226 1227 1228 1229 1230 1231 1232 1233 1234
        ',
        array($userlooking, $dbnow, $dbnow)
        )
    ) {
        foreach ($results as &$row) {
            $list[$row->owner][$row->id] = $row;
        }
    }

Martyn Smith's avatar
Martyn Smith committed