PageRenderTime 60ms CodeModel.GetById 9ms app.highlight 42ms RepoModel.GetById 1ms app.codeStats 0ms

/elgg/mod/openid_client/openid_include.php

https://bitbucket.org/rhizomatik/lorea_production/
PHP | 542 lines | 396 code | 98 blank | 48 comment | 55 complexity | 784d29601c0fa88dfacd0d2c46c31ad3 MD5 | raw file
  1<?php
  2/**
  3 * An Elgg 1.x compatible store implementation 
  4 */
  5 
  6 /**
  7 * Require base class for creating a new interface.
  8 */
  9 
 10require_once 'Auth/Yadis/Email.php';
 11require_once 'Auth/OpenID.php';
 12require_once 'Auth/OpenID/Interface.php';
 13require_once 'Auth/OpenID/Consumer.php';
 14try {
 15                include_once "Auth/OpenID/HMACSHA1.php";
 16} catch(Exception $e) {
 17                // new way :P
 18                require_once "Auth/OpenID/HMAC.php";
 19}
 20require_once 'Auth/OpenID/Nonce.php';
 21require_once 'Auth/OpenID/SReg.php';
 22
 23class OpenID_ElggStore extends Auth_OpenID_OpenIDStore {
 24
 25    function resetAssociations () {
 26        openid_client_delete_entities('object', 'openid_client::association');
 27    }
 28    function resetNonces () {
 29        openid_client_delete_entities('object', 'openid_client::nonce');
 30    }
 31    function getAssociation ($server_url, $handle = null) {
 32        if (isset($handle)) {
 33            $meta_array = array(
 34                        'server_url'    => $server_url,
 35                        'handle'        => $handle
 36            );
 37            $assocs = get_entities_from_metadata_multi($meta_array, 'object', 'openid_client::association');
 38        } else {
 39            $assocs = get_entities_from_metadata('server_url', $server_url, 'object','openid_client::association');
 40        }
 41        
 42        if (!$assocs || (count($assocs) == 0)) {
 43            return null;
 44        } else {
 45            $associations = array();
 46
 47            foreach ($assocs as $assoc_row) {
 48                $assoc = new Auth_OpenID_Association($assoc_row->handle,
 49                                                     base64_decode($assoc_row->secret),
 50                                                     $assoc_row->issued,
 51                                                     $assoc_row->lifetime,
 52                                                     $assoc_row->assoc_type);
 53
 54                if ($assoc->getExpiresIn() == 0) {
 55                    OpenID_ElggStore::removeAssociation($server_url, $assoc->handle);
 56                } else {
 57                    $associations[] = array($assoc->issued, $assoc);
 58                }
 59            }
 60
 61            if ($associations) {
 62                $issued = array();
 63                $assocs = array();
 64                foreach ($associations as $key => $assoc) {
 65                    $issued[$key] = $assoc[0];
 66                    $assocs[$key] = $assoc[1];
 67                }
 68
 69                array_multisort($issued, SORT_DESC, $assocs, SORT_DESC,
 70                                $associations);
 71
 72                // return the most recently issued one.
 73                list($issued, $assoc) = $associations[0];
 74                return $assoc;
 75            } else {
 76                return null;
 77            }
 78        }
 79    }
 80    
 81    function removeAssociation ($server_url, $handle) {
 82        if (isset($handle)) {
 83            $meta_array = array(
 84                        'server_url'    => $server_url,
 85                        'handle'        => $handle
 86            );
 87            $entities = get_entities_from_metadata_multi($meta_array, 'object', 'openid_client::association');
 88        } else {
 89            $entities = get_entities_from_metadata('server_url', $server_url, 'object','openid_client::association');
 90        }
 91        foreach ($entities as $entity) {
 92			openid_client_delete_entity($entity);
 93		}
 94	}
 95    function reset () {
 96        OpenID_ElggStore::resetAssociations ();
 97        OpenID_ElggStore::resetNonces ();
 98    }
 99        
100    function storeAssociation ($server_url, $association) {
101        
102        // Initialise a new ElggObject
103		$association_obj = new ElggObject();
104		
105		$association_obj->subtype = 'openid_client::association';
106		$association_obj->owner_guid = 0;
107		$association_obj->container_guid = 0;
108		$association_obj->title = 'association';
109		$association_obj->access_id = 2;		
110		
111		if ($association_obj->save()) {		
112    		$association_obj->server_url = $server_url;
113    		$association_obj->handle = $association->handle;
114            $association_obj->secret = base64_encode($association->secret);
115            $association_obj->issued = $association->issued;
116            $association_obj->lifetime = $association->lifetime;
117            $association_obj->assoc_type = $association->assoc_type;
118    		return true;
119		} else {
120    		return false;
121		}
122	}
123		
124    function useNonce ( $server_url,  $timestamp,  $salt) {
125        global $Auth_OpenID_SKEW;
126
127        if ( abs($timestamp - time()) > $Auth_OpenID_SKEW ) {
128            return false;
129        }
130        
131        // check to see if the nonce already exists
132        
133        $meta_array = array(
134                        'server_url'    => $server_url,
135                        'timestamp'     => $timestamp,
136                        'salt'          => $salt
137        );
138        
139        $entities = get_entities_from_metadata_multi($meta_array, 'object', 'openid_client::nonce');
140        
141        if ($entities) {
142            // bad - this nonce is already in use
143            return false;
144        } else {        
145            // Initialise a new ElggObject
146    		$nonce_obj = new ElggObject();
147    		
148    		$nonce_obj->subtype = 'openid_client::nonce';
149    		$nonce_obj->owner_guid = 0;
150    		$nonce_obj->container_guid = 0;
151    		$nonce_obj->title = 'nonce';
152    		$nonce_obj->access_id = 2;
153    		
154    		if ($nonce_obj->save()) {
155        		$nonce_obj->server_url = $server_url;
156        		$nonce_obj->timestamp = $timestamp;
157        		$nonce_obj->salt = $salt;
158        		return true;
159    		} else {
160        		return false;
161    		}
162		}
163	}
164	
165	function getNoSyncStatus($user) {
166    	if (isset($user) && isset($user->openid_client_nosync_status)) {
167        	return $user->openid_client_nosync_status;
168    	} else {
169        	return false;
170    	}
171	}
172	
173	function addNoSyncStatus($user) {
174    	$user->openid_client_nosync_status = 1;
175	}    	
176}
177
178function openid_client_create_invitation($prefix,$username,$ident,$email,$fullname) {
179    error_log("start create invitation");
180    $invite = new ElggObject();
181		
182	$invite->subtype = "openid_invitation";
183	$invite->owner_guid = 0;
184	$invite->container_guid = 0;
185	$invite->title = 'invitation';
186	$invite->access_id = 2;
187        error_log("middle create invitation");
188	if ($invite->save()) {
189        error_log("end create invitation");
190    	$invite->new_owner = $ident;
191    	$invite->name = $fullname;
192    	$invite->email = $email;
193    	$invite->username = $username;	
194    	$invite->code = $prefix . substr(base_convert(md5(time() . $username), 16, 36), 0, 7);
195    	$invite->added = time();
196    	return $invite;
197	} else {
198    	return null;
199	}
200}
201
202function openid_client_get_invitation($code) {
203    $invitations = get_entities_from_metadata('code', $code, 'object','openid_invitation');
204    if ($invitations) {
205        return $invitations[0];
206    } else {
207        return null;
208    }    
209}
210
211function openid_client_remove_invitation($code) {
212    $invitations = get_entities_from_metadata('code', $code, 'object','openid_invitation');
213    if ($invitations) {
214        foreach ($invitations as $invitation) {
215			openid_client_delete_entity($invitation);
216		}
217    }    
218}
219
220function openid_client_get_invitation_by_username($username) {
221    $invitations = get_entities_from_metadata('username', $username, 'object','openid_invitation');
222    if ($invitations) {
223        return $invitations[0];
224    } else {
225        return null;
226    }    
227}
228
229function openid_client_send_activate_confirmation_message($details) {
230    
231	global $CONFIG;
232	
233	// not sure where these should really come from
234	$from_name = $CONFIG->site->name;
235	$from_email = $CONFIG->site->email;
236	
237	$subject = sprintf(elgg_echo('openid_client:activate_confirmation_subject'),$CONFIG->sitename);
238	$url = $CONFIG->wwwroot . "mod/openid_client/actions/confirm.php?code=" . $details->code;
239
240	$message = wordwrap(sprintf(elgg_echo('openid_client:activate_confirmation_body'),$details->name,$CONFIG->sitename,$url, $CONFIG->sitename));
241	openid_client_email_user($details->name, $details->email, $from_name, $from_email, $subject,$message);
242}
243
244function openid_client_send_change_confirmation_message($details) {
245	global $CONFIG;
246	
247	// not sure where these should really come from
248	$from_name = 'System administrator';
249	$from_email = 'kevin@radagast.biz';
250	
251	$subject = sprintf(elgg_echo('openid_client:change_confirmation_subject'),$CONFIG->sitename);
252	$url = $CONFIG->wwwroot . "mod/openid_client/actions/confirm.php?code=" . $details->code;
253	$message = wordwrap(sprintf(elgg_echo('openid_client:change_confirmation_body'),
254	    $details->name,$CONFIG->sitename,$url, $CONFIG->sitename));
255	openid_client_email_user($details->name, $details->email, $from_name, $from_email, $subject,$message);
256}
257
258$emailLabel = elgg_echo('openid_client:email_label');
259$nameLabel = elgg_echo('openid_client:name_label');
260$submitLabel = elgg_echo('openid_client:submit_label');
261$cancelLabel = elgg_echo('openid_client:cancel_label');
262
263function openid_client_generate_sync_form($new_email,$new_name, $user, $email_confirmation) {
264	
265	return elgg_view_layout('one_column',elgg_view_title(elgg_echo('openid_client:sync_title')) . elgg_view("openid_client/forms/sync", 
266	    array(
267	        'userid'                => $user->getGUID(),
268	        'new_email'             => $new_email,
269	        'new_name'              => $new_name,
270	        'email_confirmation'    => $email_confirmation
271        )));	
272}
273
274
275function openid_client_generate_missing_data_form($openid_url,$email,$fullname,$email_confirmation,$details) {
276
277	return elgg_view_layout('one_column',elgg_view_title(elgg_echo('openid_client:missing_title')) . elgg_view("openid_client/forms/missing", 
278	    array(
279	        'openid_url'            => $openid_url,
280	        'email'                 => $email,
281	        'fullname'              => $fullname,
282	        'email_confirmation'    => $email_confirmation,
283	        'openid_code'                 => $details->code
284        )));
285}
286
287function openid_client_check_email_confirmation($openid_url) {
288	global $CONFIG;
289	
290	$done = false;	
291	$email_confirmation = false;
292	$greenlist = datalist_get('openid_client_greenlist');
293	$yellowlist = datalist_get('openid_client_yellowlist');
294	
295	if ($greenlist) {		
296		foreach (explode("\n",$greenlist) as $entry ) {
297			if (fnmatch($entry,$openid_url)) {
298				$email_confirmation = false;
299				$done = true;
300				break;
301			}
302		}
303	}
304	if (!$done && $yellowlist) {		
305		foreach (explode("\n",$yellowlist) as $entry ) {
306			if (fnmatch($entry,$openid_url)) {
307				$email_confirmation = true;
308				break;
309			}
310		}
311	}
312	return $email_confirmation;
313}
314
315function openid_client_create_openid_user($openid_url,$email, $fullname, $email_confirmation) {
316	
317	global $messages;
318	
319	if ($email && openid_client_get_user_by_email($email)) {
320		register_error(sprintf(elgg_echo('openid_client:create_email_in_use'),$email));
321		return null;
322	} else {
323					    
324	    $user = new ElggUser();
325		$user->email = $email;
326		$user->name = $fullname;
327		$user->access_id = 2;
328		$user->subtype = 'openid';
329
330		$user->username = randomString(8);
331		
332		if ($user->save()) {
333    				
334    		$id = $user->getGUID();
335    		
336    		$user = get_user($id);
337    			
338    		$user->alias = $openid_url;
339    
340    		$user->username = "openid_".$id;
341    		
342    		if ($email_confirmation) {
343    			$user->active = 'no';
344    		} else {
345    			$user->active = 'yes';
346    		}
347    		
348                create_metadata($id, 'contactemail', $email, 'text', $id, ACCESS_PRIVATE);
349
350    		$r = $user->save();
351                // Turn on email notifications by default
352                set_user_notification_setting($user->getGUID(), 'email', true);
353		
354		    return $user;
355	    } else {
356    	    register_error(elgg_echo('openid_client:user_creation_failed'));
357    	    forward();
358    	    return null;
359	    }
360	}						
361} 
362
363/**
364 * Send a notification via email.
365 */
366function openid_client_email_user($to_name, $to_email, $from_name, $from_email, $subject, $message)
367{	
368    $to = "$to_name <$to_email>";
369	
370	$headers = "From: $from_name <$from_email>\r\n";
371			
372	return mail($to, $subject, $message, $headers);
373}   
374
375// should really be added to users.php
376
377/**
378 * Get user by email
379 *
380 * @param string $email The user's email address
381 * @return ElggUser|false Depending on success
382 */
383function openid_client_get_user_by_email($email)
384{
385	global $CONFIG;
386	
387	$email = sanitise_string($email);
388	$row = get_data_row("SELECT * from {$CONFIG->dbprefix}users_entity where email='$email'");
389	if ($row)
390		return new ElggUser($row); 
391	
392	return false;
393}
394
395// modified from Elgg 1.0 sessions.php
396
397/**
398* Log in
399*
400* @param user entity $user
401* @param true|false $persistent
402* @return true|false
403*/
404function do_login($user, $persistent = false) {
405             
406    $_SESSION['user'] = $user;
407    $_SESSION['guid'] = $user->getGUID();
408    $_SESSION['id'] = $_SESSION['guid'];
409    $_SESSION['username'] = $user->username;
410    $_SESSION['name'] = $user->name;
411    
412    $code = (md5($user->name . $user->username . time() . rand()));
413    $user->code = md5($code);
414    $user->save();
415    
416    $_SESSION['code'] = $code;
417    //if (!empty($persistent)) {
418    
419    setcookie("elggperm", $code, (time()+(86400 * 30)),"/");
420    
421    //}
422    // set_login_fields($user->id);
423
424    return true; 
425   
426}
427
428// copied over from old elgglib
429
430/**
431 * Validates an email to make sure it makes sense and adheres
432 * to the email filter if it's set.
433 *
434 * @param string $address The email address to validate.
435 * @return boolean
436 */
437function openid_validate_email($address) {
438
439    global $CONFIG;
440    
441    if (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.
442                  '@'.
443                  '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
444                  '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
445                  $address)) {
446                      
447                      if ($CONFIG->emailfilter != "") {
448                          $domain = substr($address,strpos($address,"@")+1);
449                          if (substr_count($CONFIG->emailfilter, $domain) == 0) {
450                              return false;
451                          }
452                      }
453                      
454                      return true;
455                      
456                  } else {
457                      return false;
458                  }
459}
460
461
462function randomString($length)
463{
464    // Generate random 32 charecter string
465    $string = md5(time());
466
467    // Position Limiting
468    $highest_startpoint = 32-$length;
469
470    // Take a random starting point in the randomly
471    // Generated String, not going any higher then $highest_startpoint
472    $randomString = substr($string,rand(0,$highest_startpoint),$length);
473
474    return $randomString;
475
476}
477
478function openid_client_delete_entities($type = "", $subtype = "", $owner_guid = 0)
479	{
480		$entities = get_entities($type, $subtype, $owner_guid, "time_created desc", 0);
481		
482		foreach ($entities as $entity) {
483			openid_client_delete_entity($entity);
484		}
485		
486		return true;
487	}
488	
489function openid_client_delete_entity($entity)
490{
491    global $CONFIG;
492    	
493    $entity->clearMetadata();
494    $entity->clearAnnotations();
495    $guid = $entity->getGUID();
496	delete_data("DELETE from {$CONFIG->dbprefix}entities where guid={$guid}");
497}
498
499function is_admin($user_id = 0) {
500    if (!$user_id) {
501        if (isloggedin()) {
502            $user_id = $_SESSION['user']->getGUID();
503        } else {
504            return false;
505        }
506    }
507    
508    return get_metadata_byname($user_id, 'admin');    
509}
510
511if (!function_exists('fnmatch')) {
512function fnmatch($pattern, $string) {
513   for ($op = 0, $npattern = '', $n = 0, $l = strlen($pattern); $n < $l; $n++) {
514       switch ($c = $pattern[$n]) {
515           case '\\':
516               $npattern .= '\\' . @$pattern[++$n];
517           break;
518           case '.': case '+': case '^': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '<': case '>': case '|':
519               $npattern .= '\\' . $c;
520           break;
521           case '?': case '*':
522               $npattern .= '.' . $c;
523           break;
524           case '[': case ']': default:
525               $npattern .= $c;
526               if ($c == '[') {
527                   $op++;
528               } else if ($c == ']') {
529                   if ($op == 0) return false;
530                   $op--;
531               }
532           break;
533       }
534   }
535
536   if ($op != 0) return false;
537
538   return preg_match('/' . $npattern . '/i', $string);
539}
540}
541
542?>