1<?php
2
3/**
4 * Attempt to load the class before PHP fails with an error.
5 * This method is called automatically in case you are trying to use a class which hasn't been defined yet.
6 *
7 * We look for the undefined class in the following folders:
8 * - /system/classes/*.php
9 * - /system/handlers/*.php
10 * - /user/classes/*.php
11 * - /user/handlers/*.php
12 * - /user/sites/x.y.z/classes/*.php
13 * - /user/sites/x.y.z/handlers/*.php
14 *
15 * @param string $class_name Class called by the user
16 */
17function habari_autoload( $class_name )
18{
19	static $files = null;
20
21	$success = false;
22	$class_file = strtolower( $class_name ) . '.php';
23
24	if ( empty( $files ) ) {
25		$files = array();
26		$dirs = array(
27			HABARI_PATH . '/system/classes',
28			HABARI_PATH . '/system/handlers',
29			HABARI_PATH . '/user/classes',
30			HABARI_PATH . '/user/handlers',
31		);
32
33		// For each directory, save the available files in the $files array.
34		foreach ( $dirs as $dir ) {
35			$glob = glob( $dir . '/*.php' );
36			if ( $glob === false || empty( $glob ) ) continue;
37			$fnames = array_map( create_function( '$a', 'return strtolower(basename($a));' ), $glob );
38			$files = array_merge( $files, array_combine( $fnames, $glob ) );
39		}
40
41		// Load the Site class, a requirement to get files from a multisite directory.
42		if ( isset( $files['site.php'] ) ) {
43			require( $files['site.php'] );
44		}
45
46		// Verify if this Habari instance is a multisite.
47		if ( ( $site_user_dir = Site::get_dir( 'user' ) ) != HABARI_PATH . '/user' ) {
48			// We are dealing with a site defined in /user/sites/x.y.z
49			// Add the available files in that directory in the $files array.
50			$glob_classes = glob( $site_user_dir . '/classes/*.php' );
51			$glob_handlers = glob( $site_user_dir . '/handlers/*.php' );
52			$glob = array_merge( $glob_classes, $glob_handlers );
53			if ( $glob !== false && !empty( $glob ) ) {
54				$fnames = array_map( create_function( '$a', 'return strtolower(basename($a));' ), $glob );
55				$files = array_merge( $files, array_combine( $fnames, $glob ) );
56			}
57		}
58	}
59
60	// Search in the available files for the undefined class file.
61	if ( isset( $files[$class_file] ) ) {
62		require( $files[$class_file] );
63		// If the class has a static method named __static(), execute it now, on initial load.
64		if ( class_exists( $class_name, false ) && method_exists( $class_name, '__static' ) ) {
65			call_user_func( array( $class_name, '__static' ) );
66		}
67		$success = true;
68	}
69}
70
71?>
72