cae47c02af83d3af504c6a74a58325bf94d67a22
[atutor.git] / mods / mahara / new_account.php
1 <?php\r
2 \r
3 /*\r
4     This belongs to the ATutor+Mahara module. It is called from index.php when\r
5     the user does not have a Mahara account associated with ATutor.  This script\r
6     automatically creates a new Mahara account for the user and saves the login\r
7     information with ATutor.  If the user already has a Mahara account, the script\r
8     simply adds the login information to ATutor and reassigns an automatically\r
9     generated password for Mahara.\r
10 \r
11     Most of the necessary code is copied and modified from init.php and\r
12     register.php of Mahara.\r
13 \r
14     by: Boon-Hau Teh\r
15 */\r
16 \r
17 $_user_location = 'public';\r
18 \r
19 if (!defined('new_account')) { exit; }\r
20 if (!defined('AT_INCLUDE_PATH')) { exit; }\r
21 \r
22 $sql = 'SELECT * FROM '.TABLE_PREFIX.'members WHERE member_id="'.$_SESSION['member_id'].'"';\r
23 $result = mysql_query($sql, $db);\r
24 $row = mysql_fetch_assoc($result);\r
25 \r
26 $registration->username     = $row['login'];\r
27 $registration->firstname    = $row['first_name'];\r
28 $registration->lastname     = $row['last_name'];\r
29 $registration->password     = $row['password'];\r
30 $registration->email        = $row['email'];\r
31 \r
32 define (MAHARA_PATH, $_config['mahara']);\r
33 \r
34 /******************from init.php*************************/\r
35 define('INTERNAL', 1);\r
36 define('PUBLIC', 1);\r
37 define('SECTION_PLUGINTYPE', 'core');\r
38 define('SECTION_PLUGINNAME', 'site');\r
39 define('SECTION_PAGE', 'register');\r
40 \r
41 $CFG = new StdClass;\r
42 $CFG->docroot = MAHARA_PATH;\r
43 \r
44 // Figure out our include path\r
45 if (!empty($_SERVER['MAHARA_LIBDIR'])) {\r
46     $CFG->libroot = $_SERVER['MAHARA_LIBDIR'];\r
47 } else {\r
48     $CFG->libroot = MAHARA_PATH. 'lib/';\r
49 }\r
50 set_include_path($CFG->libroot . PATH_SEPARATOR . $CFG->libroot . 'pear/' . PATH_SEPARATOR . get_include_path());\r
51 \r
52 // Set up error handling\r
53 require(MAHARA_PATH.'lib/errors.php');\r
54 \r
55 if (!is_readable($CFG->docroot . 'config.php')) {\r
56     // @todo Later, this will redirect to the installer script. For now, we\r
57     // just log and exit.\r
58     log_environ(_AT('MAHARA_ERROR_INSTALL'));\r
59     header('Location: '.AT_BASE_HREF);\r
60 }\r
61 \r
62 require(MAHARA_PATH.'config.php');\r
63 $CFG = (object)array_merge((array)$cfg, (array)$CFG);\r
64 \r
65 // Fix up paths in $CFG\r
66 foreach (array('docroot', 'dataroot') as $path) {\r
67     $CFG->{$path} = (substr($CFG->{$path}, -1) != DIRECTORY_SEPARATOR) ? $CFG->{$path} . DIRECTORY_SEPARATOR : $CFG->{$path};\r
68 }\r
69 \r
70 // xmldb stuff\r
71 $CFG->xmldbdisablenextprevchecking = true;\r
72 $CFG->xmldbdisablecommentchecking = true;\r
73 \r
74 // ensure directorypermissions is set\r
75 if (empty($CFG->directorypermissions)) {\r
76     $CFG->directorypermissions = 0700;\r
77 }\r
78 \r
79 // core libraries\r
80 require(MAHARA_PATH.'lib/mahara.php');\r
81 ensure_sanity();\r
82 require(MAHARA_PATH.'auth/internal/lib.php');\r
83 require(MAHARA_PATH.'lib/dml.php');\r
84 require(MAHARA_PATH.'lib/ddl.php');\r
85 require(MAHARA_PATH.'lib/activity.php');\r
86 require(MAHARA_PATH.'lib/user.php');\r
87 require(MAHARA_PATH.'lib/web.php');\r
88 \r
89 // Database access functions\r
90 require(MAHARA_PATH.'lib/adodb/adodb-exceptions.inc.php');\r
91 require(MAHARA_PATH.'lib/adodb/adodb.inc.php');\r
92 \r
93 try {\r
94     // ADODB does not provide the raw driver error message if the connection\r
95     // fails for some reason, so we use output buffering to catch whatever\r
96     // the error is instead.\r
97     ob_start();\r
98     \r
99     $db = &ADONewConnection($CFG->dbtype);\r
100     $dbgenerator = null;\r
101     if (empty($CFG->dbhost)) {\r
102         $CFG->dbhost = '';\r
103     }\r
104     else if (!empty($CFG->dbport)) {\r
105         $CFG->dbhost .= ':'.$CFG->dbport;\r
106     }\r
107     if (!empty($CFG->dbpersist)) {    // Use persistent connection (default)\r
108         $dbconnected = $db->PConnect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);\r
109     } \r
110     else {                                                     // Use single connection\r
111         $dbconnected = $db->Connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);\r
112     }\r
113 \r
114     $db->SetFetchMode(ADODB_FETCH_ASSOC);\r
115     configure_dbconnection();\r
116     ensure_internal_plugins_exist();\r
117 \r
118     ob_end_clean();\r
119 }\r
120 catch (Exception $e) {\r
121     $errormessage = ob_get_contents();\r
122     if (!$errormessage) {\r
123         $errormessage = $e->getMessage();\r
124     }\r
125     ob_end_clean();\r
126     $errormessage = get_string('dbconnfailed', 'error') . $errormessage;\r
127     throw new ConfigSanityException($errormessage);\r
128 }\r
129 try {\r
130     db_ignore_sql_exceptions(true);\r
131     load_config();\r
132     db_ignore_sql_exceptions(false);\r
133\r
134 catch (SQLException $e) {\r
135     db_ignore_sql_exceptions(false);\r
136 }\r
137 \r
138 \r
139 // Only do authentication once we know the page theme, so that the login form\r
140 // can have the correct theming.\r
141 require_once(MAHARA_PATH.'auth/lib.php');\r
142 $USER    = new LiveUser();\r
143 /***************end from init.php*************************/\r
144 \r
145 \r
146 /*~~~~~~~~~modified from register.php~~~~~~~~~~*/\r
147 $random_password = substr(md5($registration->password.rand(100000, 999999)), 2, 8);\r
148 \r
149 /*-- from register_submit function --*/\r
150 $registration->salt         = substr(md5(rand(1000000, 9999999)), 2, 8);\r
151 $registration->password     = AuthInternal::encrypt_password($random_password, $registration->salt);\r
152 $registration->expiry       = NULL;\r
153 /*-----------------------------------*/\r
154 \r
155 \r
156 // Check if user already exists in Mahara\r
157 if ($data_record = get_record('usr', 'username', $registration->username)) {\r
158     $registration -> id = $data_record -> id;\r
159     update_record('usr', $registration, 'username');\r
160 } else {\r
161     create_registered_user();   // Send register info to create a new account\r
162 }\r
163 \r
164 // Reconnect to ATutor Database\r
165 $db_atutor = @mysql_connect(DB_HOST . ':' . DB_PORT, DB_USER, DB_PASSWORD);\r
166 if (!$db_atutor) {\r
167     /* AT_ERROR_NO_DB_CONNECT */\r
168     require_once(AT_INCLUDE_PATH . 'classes/ErrorHandler/ErrorHandler.class.php');\r
169     $err =& new ErrorHandler();\r
170     trigger_error('VITAL#Unable to connect to db.', E_USER_ERROR);\r
171     exit;\r
172 }\r
173 if (!@mysql_select_db(DB_NAME, $db_atutor)) {\r
174     require_once(AT_INCLUDE_PATH . 'classes/ErrorHandler/ErrorHandler.class.php');\r
175     $err =& new ErrorHandler();\r
176     trigger_error('VITAL#DB connection established, but database "'.DB_NAME.'" cannot be selected.',\r
177                     E_USER_ERROR);\r
178     exit;\r
179 }\r
180 \r
181 // Store data into ATutor Databse\r
182 $sql = "INSERT INTO ".TABLE_PREFIX."mahara SET at_login='".$_SESSION['login']."', username='".$registration->username."', password='".$random_password."'";\r
183 if (!mysql_query($sql, $db_atutor))\r
184     exit;              // in case there's some external error; prevent being caught in an infinite loop\r
185 \r
186 \r
187 /**\r
188  * This function is copied and modified from register.php of Mahara\r
189  *\r
190  * @param array profilefields    Array of values from registration form. In this module, we're not using a form so we don't pass anything\r
191  * @return boolean               Returns true if function exits without any problems\r
192  */\r
193 function create_registered_user($profilefields=array()) {\r
194     global $registration, $USER;\r
195 \r
196     db_begin();\r
197 \r
198     // Move the user record to the usr table from the registration table\r
199     $registrationid = $registration->id;\r
200     unset($registration->id);\r
201     unset($registration->expiry);\r
202     if ($expirytime = get_config('defaultaccountlifetime')) {\r
203         $registration->expiry = db_format_timestamp(time() + $expirytime);\r
204     }\r
205     $registration->lastlogin = db_format_timestamp(time());\r
206 \r
207     $user = new User();\r
208     $user->username         = $registration->username;\r
209     $user->password         = $registration->password;\r
210     $user->salt             = $registration->salt;\r
211     $user->passwordchange   = 0;\r
212     $user->active           = 1;\r
213     $user->authinstance     = $authinstance->id;\r
214     $user->firstname        = $registration->firstname;\r
215     $user->lastname         = $registration->lastname;\r
216     $user->email            = $registration->email;\r
217     $user->commit();\r
218 \r
219     $registration->id = $user->id;\r
220 \r
221     // Insert standard stuff as artefacts\r
222     set_profile_field($user->id, 'email', $registration->email);\r
223     set_profile_field($user->id, 'firstname', $registration->firstname);\r
224     set_profile_field($user->id, 'lastname', $registration->lastname);\r
225     if (!empty($registration->lang) && $registration->lang != 'default') {\r
226         set_account_preference($user->id, 'lang', $registration->lang);\r
227     }\r
228 \r
229     // Set mandatory profile fields \r
230     foreach(ArtefactTypeProfile::get_mandatory_fields() as $field => $type) {\r
231         // @todo here and above, use the method for getting "always mandatory" fields\r
232         if (in_array($field, array('firstname', 'lastname', 'email'))) {\r
233             continue;\r
234         }\r
235         set_profile_field($user->id, $field, $profilefields[$field]);\r
236     }\r
237 \r
238     db_commit();\r
239     handle_event('createuser', $registration);\r
240 \r
241     return true;\r
242 }\r
243 \r
244 ?>