initialize session if not done already
[Pman.Core] / DataObjects / Core_person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7
8 class Pman_Core_DataObjects_Core_person extends DB_DataObject 
9 {
10     ###START_AUTOCODE
11     /* the code below is auto generated do not remove the above tag */
12
13     public $__table = 'core_person';                          // table name
14     public $id;                              // int(11)  not_null primary_key auto_increment
15     public $email;                           // string(128)  not_null
16     public $alt_email;
17     
18     public $company_id;                      // int(11)  
19     public $office_id;                       // int(11)  
20     public $name;                            // string(128)  not_null
21     public $firstname;                            // string(128)  not_null
22     public $lastname;                            // string(128)  not_null
23     public $phone;                           // string(32)  not_null
24     public $fax;                             // string(32)  not_null
25     
26     public $role;                            // string(32)  not_null
27     public $remarks;                         // blob(65535)  not_null blob
28     public $passwd;                          // string(64)  not_null
29     public $owner_id;                        // int(11)  not_null
30     public $lang;                            // string(8)  
31     public $no_reset_sent;                   // int(11)  
32     public $action_type;                     // string(32)  
33     public $project_id;                      // int(11)
34
35     
36     public $active;                          // int(11)  not_null
37     public $deleted_by;                      // int(11)  not_null
38     public $deleted_dt;                      // datetime(19)  binary
39
40
41     public $name_facebook; // VARCHAR(128) NULL;
42     public $url_blog; // VARCHAR(256) NULL ;
43     public $url_twitter; // VARCHAR(256) NULL ;
44     public $url_linkedin; // VARCHAR(256) NULL ;
45     public $linkedin_id; // VARCHAR(256) NULL ;
46     
47     public $phone_mobile; // varchar(32)  NOT NULL  DEFAULT '';
48     public $phone_direct; // varchar(32)  NOT NULL  DEFAULT '';
49     public $countries; // VARCHAR(128) NULL;
50     
51     public $language;
52     
53     /* the code above is auto generated do not remove the tag below */
54     ###END_AUTOCODE
55     
56     static $authUser = false;
57     
58  
59     function owner()
60     {
61         // this might be a Person in some old code? 
62         $p = DB_DataObject::Factory('core_person');
63         $p->get($this->owner_id);
64         return $p;
65     }
66     
67     /**
68      *
69      *
70      *
71      *
72      *  FIXME !!!! -- USE Pman_Core_Mailer !!!!!
73      *
74      *
75      *
76      *  
77      */
78     function buildMail($templateFile, $args)
79     {
80           
81         $args = (array) $args;
82         $content  = clone($this);
83         
84         foreach((array)$args as $k=>$v) {
85             $content->$k = $v;
86         }
87         
88         $ff = HTML_FlexyFramework::get();
89         
90         
91         //?? is this really the place for this???
92         if (
93                 !$ff->cli && 
94                 empty($args['no_auth']) &&
95                 !in_array($templateFile, array(
96                     // templates that can be sent without authentication.
97                      'password_reset' ,
98                      'password_welcome'
99                  ))
100             ) {
101             
102             $content->authUser = $this->getAuthUser();
103             if (!$content->authUser) {
104                 return PEAR::raiseError("Not authenticated");
105             }
106         }
107         
108         // should handle x-forwarded...
109         
110         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
111             $_SERVER["HTTP_HOST"] :
112             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
113             
114         /* use the regex compiler, as it doesnt parse <tags */
115         
116         $tops = array(
117             'compiler'    => 'Flexy',
118             'nonHTML' => true,
119             'filters' => array('SimpleTags','Mail'),
120             //     'debug'=>1,
121         );
122         
123         
124         
125         if (!empty($args['templateDir'])) {
126             $tops['templateDir'] = $args['templateDir'];
127         }
128         
129         
130         
131         require_once 'HTML/Template/Flexy.php';
132         $template = new HTML_Template_Flexy( $tops );
133         $template->compile("mail/$templateFile.txt");
134         
135         /* use variables from this object to ouput data. */
136         $mailtext = $template->bufferedOutputObject($content);
137         
138         $htmlbody = false;
139         // if a html file with the same name exists, use that as the body
140         // I've no idea where this code went, it was here before..
141         if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
142             $tops['nonHTML'] = false;
143             $template = new HTML_Template_Flexy( $tops );
144             $template->compile("mail/$templateFile.html");
145             $htmlbody = $template->bufferedOutputObject($content);
146             
147         }
148         
149         
150         
151         //echo "<PRE>";print_R($mailtext);
152         //print_R($mailtext);exit;
153         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
154         require_once 'Mail/mimeDecode.php';
155         require_once 'Mail.php';
156         
157         $decoder = new Mail_mimeDecode($mailtext);
158         $parts = $decoder->getSendArray();
159         
160         if (is_a($parts,'PEAR_Error')) {
161             return $parts;
162             //echo "PROBLEM: {$parts->message}";
163             //exit;
164         } 
165         list($recipents,$headers,$body) = $parts;
166         $recipents = array($this->email);
167         if (!empty($content->bcc) && is_array($content->bcc)) {
168             $recipents =array_merge($recipents, $content->bcc);
169         }
170         $headers['Date'] = date('r');
171         
172         if ($htmlbody !== false) {
173             require_once 'Mail/mime.php';
174             $mime = new Mail_mime(array('eol' => "\n"));
175             $mime->setTXTBody($body);
176             $mime->setHTMLBody($htmlbody);
177             // I think there might be code in mediaoutreach toEmail somewhere
178             // h embeds images here..
179             $body = $mime->get();
180             $headers = $mime->headers($headers);
181         }
182         
183         return array(
184             'recipients' => $recipents,
185             'headers'    => $headers,
186             'body'      => $body
187         );
188     }
189     
190     
191     /**
192      * send a template
193      * - user must be authenticate or args[no_auth] = true
194      *   or template = password_[reset|welcome]
195      * 
196      */
197     function sendTemplate($templateFile, $args)
198     {
199         $ar = $this->buildMail($templateFile, $args);
200       
201         //print_r($recipents);exit;
202         $mailOptions = PEAR::getStaticProperty('Mail','options');
203         $mail = Mail::factory("SMTP",$mailOptions);
204         
205         if (PEAR::isError($mail)) {
206             return $mail;
207         } 
208         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
209         $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
210         error_reporting($oe);
211        
212         return $ret;
213     }
214     
215   
216     
217     
218     function getEmailFrom()
219     {
220         if (empty($this->name)) {
221             return $this->email;
222         }
223         
224         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
225     }
226     
227     function toEventString() 
228     {
229         return empty($this->name) ? $this->email : $this->name;
230     } 
231     
232     function verifyAuth()
233     { 
234         $ff= HTML_FlexyFramework::get();
235         if (!empty($ff->Pman['auth_comptype']) &&
236             (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
237            ){
238             
239             $sesPrefix = $this->sesPrefix();
240        
241             self::$authUser = false;
242             $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
243             
244             return false;
245             
246             //$ff->page->jerr("Login not permited to outside companies");
247         }
248         return true;
249         
250     }    
251    
252    
253     //   ---------------- authentication / passwords and keys stuff  ----------------
254     function isAuth()
255     {
256         // do not start a session if we are using http auth...
257         // we have a situation where the app is behind a http access and is also login
258         // need to work out a way to handle that.
259         
260         $session_started = false;
261         if (php_sapi_name() != "cli" && empty($_SERVER['PHP_AUTH_USER']) && empty($_COOKIE['PHPSESSID'])) {
262             $session_started = false;
263             @session_start();
264         }
265         
266         
267        
268         $ff= HTML_FlexyFramework::get();
269        
270         $sesPrefix = $this->sesPrefix();
271         
272         if (self::$authUser) {
273             return self::$authUser;
274         }
275         
276         
277         if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
278             // in session...
279             $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
280             $u = DB_DataObject::factory($this->tableName());
281             $u->autoJoin();
282             if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
283                 if ($u->verifyAuth()) {
284                     self::$authUser = $u;
285                     return true;
286                 }
287             }
288             unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
289             unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
290             setcookie('Pman.timeout', -1, time() + (30*60), '/');
291             return false;
292         }
293         
294         // http basic auth..
295         $u = DB_DataObject::factory($this->tableName());
296         
297         if (empty($_COOKIE['PHPSESSID']) // http auth requests should not have this...
298             &&
299             !empty($_SERVER['PHP_AUTH_USER']) 
300             &&
301             !empty($_SERVER['PHP_AUTH_PW'])
302             &&
303             $u->get('email', $_SERVER['PHP_AUTH_USER'])
304             &&
305             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
306            ) {
307             // logged in via http auth
308             // http auth will not need session... 
309             //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
310             self::$authUser = $u;
311             return true; 
312         }
313         
314         // at this point all http auth stuff is done, so we can init session
315        if (php_sapi_name() != "cli" && !$session_started) {
316             @session_start();
317         }
318         
319         //die("test init");
320         if (!$this->canInitializeSystem()) {
321           //  die("can not init");
322             return false;
323         }
324         
325         
326         $auto_auth_allow = false;
327         if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
328             $auto_auth_allow  = true;
329         }
330         if  ( !empty($ff->Pman['local_autoauth'])
331              &&
332                 !empty($_SERVER['SERVER_ADDR']) &&
333                 !empty($_SERVER['REMOTE_ADDR']) &&
334                 (
335                     (
336                        $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
337                        $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
338                    )
339                    ||
340                    (
341                        $_SERVER['SERVER_ADDR'] == '::1' &&
342                        $_SERVER['REMOTE_ADDR'] == '::1'
343                    )
344                 )
345                 
346             ){
347             $auto_auth_allow  = true;
348         }
349         
350         
351         if (empty($_SERVER['PATH_INFO']) ||  $_SERVER['PATH_INFO'] == '/Login') {
352             $auto_auth_allow  = false;
353         }
354          //var_dump($auto_auth_allow);
355         // local auth - 
356         $default_admin = false;
357         if ($auto_auth_allow) {
358             $group = DB_DataObject::factory('core_group');
359             $group->get('name', 'Administrators');
360             
361             $member = DB_DataObject::factory('core_group_member');
362             $member->autoJoin();
363             $member->group_id = $group->id;
364             $member->whereAdd("
365                 join_user_id_id.id IS NOT NULL
366             ");
367             if($member->find(true)){
368                 $default_admin = DB_DataObject::factory($this->tableName());
369                 $default_admin->autoJoin();
370                 if(!$default_admin->get($member->user_id)){
371                     $default_admin = false;
372                 }
373             }
374         }
375         
376         //var_dump($ff->Pman['local_autoauth']);         var_dump($_SERVER); exit;
377         $u = DB_DataObject::factory($this->tableName());
378         $u->autoJoin();
379         $ff = HTML_FlexyFramework::get();
380         
381         if ($auto_auth_allow && 
382             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
383         ) {
384             
385             $user = $default_admin ? $default_admin->toArray() : $u->toArray();
386             
387             // if we request other URLS.. then we get auto logged in..
388             self::$authUser = $default_admin ? $default_admin : $u;;
389             //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
390             return true;
391         }
392         
393         //var_dump(session_id());
394         //var_dump($_SESSION[__CLASS__]);
395         
396         //if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
397         //    return false;
398         //}
399         //die("got this far?");
400         // not in session or not matched...
401         $u = DB_DataObject::factory($this->tableName());
402         $u->whereAdd(' LENGTH(passwd) > 0');
403         $n = $u->count();
404         if (empty($_SESSION[get_class($this)]) || !is_array($_SESSION[get_class($this)])) { 
405             $_SESSION[get_class($this)] = array();
406         }
407         $_SESSION[get_class($this)][$sesPrefix .'-empty']  = $n;
408         if (class_exists('PEAR')) {
409             $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
410             if ($error) {
411                 die($error->toString()); // not really a good thing to do...
412             }
413         }
414         if (!$n){ // authenticated as there are no users in the system...
415              return true;
416         }
417          return false;
418         
419     }
420     
421     function canInitializeSystem()
422     {
423         
424         return !strcasecmp(get_class($this) , __CLASS__);
425     }
426     
427     function getAuthUser()
428     {
429         if (!$this->isAuth()) {
430             return false;
431         }
432         
433         $ff= HTML_FlexyFramework::get();
434         
435         $sesPrefix = $this->sesPrefix();
436         
437         //var_dump(array(get_class($this),$sesPrefix .'-auth'));
438        
439         if (self::$authUser) {
440              
441             if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
442                 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
443                 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
444             }
445             // not really sure why it's cloned..
446             return   clone (self::$authUser);
447              
448             
449         }
450         
451         
452         
453         if (!$this->canInitializeSystem()) {
454             return false;
455         }
456         
457         
458         
459         if (empty(   $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
460             $u = DB_DataObject::factory($this->tableName());
461             $u->whereAdd(' LENGTH(passwd) > 0');
462             $_SESSION[get_class($this)][$sesPrefix .'-empty']  = $u->count();
463         }
464                 
465              
466         if (
467             isset(   $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) && 
468             $_SESSION[get_class($this)][$sesPrefix .'-empty']  < 1
469         ) {
470             
471             // fake person - open system..
472             //$ce = DB_DataObject::factory('core_enum');
473             //$ce->initEnums();
474             
475             
476             $u = DB_DataObject::factory($this->tableName());
477             $u->id = -1;
478             
479             // if a company has been created fill that in in company_id_id
480             $c = DB_DAtaObject::factory('core_company')->lookupOwner();
481             if ($c) {
482                 $u->company_id_id = $c->pid();
483                 $u->company_id = $c->pid();
484             }
485             
486             return $u;
487             
488         }
489         return false;
490     }     
491     function login()
492     {
493         $this->isAuth(); // force session start..
494         if (!$this->verifyAuth()) { // check for company valid..
495             return false;
496         }
497         
498         // open up iptables at login..
499         $dbname = $this->databaseNickname();
500         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
501          
502         // refresh admin group if we are logged in as one..
503         //DB_DataObject::debugLevel(1);
504         $g = DB_DataObject::factory('core_group');
505         $g->type = 0;
506         $g->get('name', 'Administrators');
507         $gm = DB_DataObject::Factory('core_group_member');
508         if (in_array($g->id,$gm->listGroupMembership($this))) {
509             // refresh admin groups.
510             $gr = DB_DataObject::Factory('core_group_right');
511             $gr->applyDefs($g, 0);
512         }
513         
514         $sesPrefix = $this->sesPrefix();
515         
516         // we should not store the whole data in the session - otherwise it get's huge.
517         $p = DB_DAtaObject::Factory($this->tableName());
518         $p->get($this->pid());
519         
520         $d = $p->toArray();
521         
522         $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
523         setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
524         
525         //var_dump(array(get_class($this),$sesPrefix .'-auth'));
526         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
527         
528         $pp = DB_DAtaObject::Factory($this->tableName());
529         $pp->get($this->pid());
530         $pp->autoJoin();
531         
532         self::$authUser = $pp;
533         // ensure it's written so that ajax calls can fetch it..
534         
535         
536         
537     }
538     function logout()
539     {
540         $this->isAuth(); // force session start..
541         
542         $sesPrefix = $this->sesPrefix();
543         $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
544         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
545         self::$authUser = false;
546         
547     }    
548     function genPassKey ($t) 
549     {
550         return md5($this->email . $t. $this->passwd);
551     }
552     function simpleAuthKey($m = 0)
553     {
554         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
555         
556         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
557     }
558     /**
559      * When we generate autologin urls:
560      * eg. /Somesite/Test/12
561      * it will generate:
562      * /Somesite/Test/12/{datetime}/{sha256(url + expires_datetime + password)}
563      *
564      * eg. genAutoLoginURL($sub, $expires)
565      */
566     function genAutoLoginURL($url, $expires = false)  
567     {
568         $expires = $expires  === false ? strtotime("NOW + 1 WEEK") : $expires;
569         //echo serialize(array($url, $expires, $this->email, $this->passwd));
570         //echo hash('sha256', serialize(array($url, $expires, $this->email, $this->passwd)));
571         
572         return $url.'/'.$this->id .'/'.$expires.'/'.
573             hash('sha256',
574                 serialize(
575                     array($url, $expires, $this->email,$this->passwd)
576                 )
577             );
578         
579     }
580     
581     function validateAutoLogin($called)
582     {
583         $bits = explode("/",$called);
584         if (count($bits) < 4) {
585             return false; // unrelated.
586         }
587         $hash = array_pop($bits);
588         $time = array_pop($bits);
589         
590         $id = array_pop($bits);
591         if (!is_numeric($time) || !is_numeric($id)) {
592             return false; // wrong format.
593         }
594         $u = DB_DataObject::Factory($this->tableName());
595         $u->get($id);
596         $url = implode("/", $bits);
597         if ($time < time()) {
598             return "Expired";
599         }
600         //echo serialize(array('/'.$url, $time, $u->email, $u->passwd));
601         //echo hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)));
602         if ($hash == hash('sha256', serialize(array('/'.$url, $time*1, $u->email, $u->passwd)))) {
603             $u->login();
604             return $u;
605         }
606         return false;
607     }
608     
609     
610     function checkTwoFactorAuthentication($val)
611     {
612         
613         
614         // also used in login
615         require_once 'System.php';
616         
617         if(
618             empty($this->id) ||
619             empty($this->oath_key)
620         ) {
621             return false;
622         }
623         
624         $oathtool = System::which('oathtool');
625         
626         if (!$oathtool) {
627             return false;
628         }
629         
630         $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
631         
632         $password = exec($cmd);
633         
634         return ($password == $val) ? true : false;
635     }
636     
637     function checkPassword($val)
638     {
639         if (substr($this->passwd,0,1) == '$') {
640             if (function_exists('pasword_verify')) {
641                 return password_verify($val, $this->passwd);
642             }
643             return crypt($val,$this->passwd) == $this->passwd ;
644         }
645         // old style md5 passwords...- cant be used with courier....
646         return md5($val) == $this->passwd;
647     }
648     
649     function setPassword($value) 
650     {
651         if (function_exists('pasword_hash')) {
652             return password_hash($value);
653         }
654         
655         $salt='';
656         while(strlen($salt)<9) {
657             $salt.=chr(rand(64,126));
658             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
659         }
660         $this->passwd = crypt($value, '$1$'. $salt. '$');
661        
662        
663     }      
664     
665     function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
666     {
667         require_once 'Text/Password.php';
668         $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
669         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
670         $this->setPassword($this->rawPasswd);
671         return $this->rawPasswd;
672     }
673     
674     function company()
675     {
676         if (empty($this->company_id)) {
677             return false;
678         }
679         $x = DB_DataObject::factory('core_company');
680         $x->autoJoin();
681         $x->get($this->company_id);
682         return $x;
683     }
684     function loadCompany()
685     {
686         $this->company = $this->company();
687     }
688     
689     function active()
690     { 
691         return $this->active;
692     }
693     function authUserName($n) // set username prior to acheck user exists query.
694     {
695         
696         $this->whereAdd('LENGTH(passwd) > 1'); 
697         $this->email = $n;
698     }
699     function lang()
700     {
701         if (!func_num_args()) {
702             return $this->lang;
703         }
704         $ar = func_get_args();
705         $val = array_shift($ar);
706         if ($val == $this->lang) {
707             return;
708         }
709         $uu = clone($this);
710         $this->lang = $val;
711         $this->update($uu);
712         return $this->lang;
713     }
714             
715     
716     function authUserArray()
717     {
718         $aur = $this->toArray();
719         
720         if ($this->id < 1) {
721             return $aur;
722         }
723         
724         //DB_DataObject::debugLevel(1);
725         $c = DB_Dataobject::factory('core_company');
726         $im = DB_Dataobject::factory('Images');
727         $c->joinAdd($im, 'LEFT');
728         $c->selectAdd();
729         $c->selectAs($c, 'company_id_%s');
730         $c->selectAs($im, 'company_id_logo_id_%s');
731         $c->id = $this->company_id;
732         $c->limit(1);
733         $c->find(true);
734         
735         $aur = array_merge( $c->toArray(),$aur);
736         
737         if (empty($c->company_id_logo_id_id))  {
738                  
739             $im = DB_Dataobject::factory('Images');
740             $im->ontable = DB_DataObject::factory('core_company')->tableName();
741             $im->onid = $c->id;
742             $im->imgtype = 'LOGO';
743             $im->limit(1);
744             $im->selectAdd();
745             $im->selectAs($im,  'company_id_logo_id_%s');
746             if ($im->find(true)) {
747                 
748                 foreach($im->toArray() as $k=>$v) {
749                     if (!preg_match('/^company_id_logo_id_/', $k)) {
750                         continue;
751                     }
752                     $aur[$k] = $v;
753                 }
754             }
755         }
756       
757         // perms + groups.
758         $aur['perms']  = $this->getPerms();
759         $g = DB_DataObject::Factory('core_group_member');
760         $aur['groups']  = $g->listGroupMembership($this, 'name');
761         
762         $aur['passwd'] = '';
763         $aur['dailykey'] = '';
764         $aur['oath_key'] = '';
765         
766         $aur['oath_key_enable'] = !empty($this->oath_key);
767         $aur['require_oath'] = 1;
768         
769         $s = DB_DataObject::Factory('core_setting');
770         $oath_require = $s->lookup('core', 'two_factor_auth_required');
771         $aur['require_oath'] = $oath_require ?  $oath_require->val : 0;
772         
773         $aur['core_person_settings'] = array();
774                 
775         $core_person_settings = DB_DataObject::factory('core_person_settings');
776         $core_person_settings->setFrom(array(
777             'person_id' => $this->id
778         ));
779         
780         $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
781         
782         return $aur;
783     }
784     
785     //   ----------PERMS------  ----------------
786     function getPerms() 
787     {
788          //DB_DataObject::debugLevel(1);
789         // find out all the groups they are a member of.. + Default..
790         
791         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
792         
793         $g = DB_DataObject::Factory('core_group_right');
794         if (!$g->count()) {
795             $g->genDefault();
796         }
797         
798         if ($this->id < 0) {
799             return $g->adminRights(); // system is not set up - so they get full rights.
800         }
801         //DB_DataObject::debugLevel(1);
802         $g = DB_DataObject::Factory('core_group_member');
803         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
804         if (!$g->count()) {
805             // add the current user to the admin group..
806             $g = DB_DataObject::Factory('core_group');
807             if ($g->get('name', 'Administrators')) {
808                 $gm = DB_DataObject::Factory('core_group_member');
809                 $gm->group_id = $g->id;
810                 $gm->user_id = $this->id;
811                 $gm->insert();
812             }
813             
814         }
815         
816         // ------ STANDARD PERMISSION HANDLING.
817         $isOwner = $this->company()->comptype == 'OWNER';
818         $g = DB_DataObject::Factory('core_group_member');
819         $grps = $g->listGroupMembership($this);
820        //var_dump($grps);
821         $isAdmin = $g->inAdmin;   //???  what???
822         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
823         // the load all the perms for those groups, and add them all together..
824         // then load all those 
825         $g = DB_DataObject::Factory('core_group_right');
826         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
827         //echo '<PRE>';print_r($ret);
828         return $ret;
829          
830         
831     }
832     /**
833      *Basic group fetching - probably needs to filter by type eventually.
834      *
835      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
836      */
837     
838     function groups($what=false)
839     {
840         $g = DB_DataObject::Factory('core_group_member');
841         $grps = $g->listGroupMembership($this);
842         $g = DB_DataObject::Factory('core_group');
843         $g->whereAddIn('id', $grps, 'int');
844         return $g->fetchAll($what);
845         
846     }
847     
848     
849     
850     function hasPerm($name, $lvl) 
851     {
852         static $pcache = array();
853         
854         if (!isset($pcache[$this->id])) {
855             $pcache[$this->id] = $this->getPerms();
856         }
857         
858        // echo "<PRE>";print_r($pcache[$au->id]);
859        // var_dump($pcache[$au->id]);
860         if (empty($pcache[$this->id][$name])) {
861             return false;
862         }
863         
864         return strpos($pcache[$this->id][$name], $lvl) > -1;
865         
866     }    
867     
868     //  ------------ROO HOOKS------------------------------------
869     function applyFilters($q, $au, $roo)
870     {
871         //DB_DataObject::DebugLevel(1);
872         if(!empty($q['_to_qr_code'])){
873             $person = DB_DataObject::factory('Core_person');
874             $person->id = $q['id']; 
875             
876             if(!$person->find(true)) {
877                 $roo->jerr('_invalid_person');
878             }
879             
880             $hash = $this->generateOathKey();
881             
882             $_SESSION[__CLASS__] = 
883                 isset($_SESSION[__CLASS__]) ? 
884                     $_SESSION[__CLASS__] : array();
885             $_SESSION[__CLASS__]['oath'] = 
886                 isset($_SESSION[__CLASS__]['oath']) ? 
887                     $_SESSION[__CLASS__]['oath'] : array();
888                 
889             $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
890
891             $qrcode = $person->generateQRCode($hash);
892             
893             if(empty($qrcode)){
894                 $roo->jerr('Fail to generate QR Code');
895             }
896             
897             $roo->jdata(array(
898                 'secret' => $hash,
899                 'image' => $qrcode,
900                 'issuer' => $person->qrCodeIssuer()
901             ));
902         }
903         
904         if(!empty($q['two_factor_auth_code'])) {
905             $person = DB_DataObject::factory('core_person');
906             $person->get($q['id']);
907             $o = clone($person);
908             $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
909             
910             if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
911                 $person->update($o);
912                 unset($_SESSION[__CLASS__]['oath'][$person->id]);
913                 $roo->jok('DONE');
914             }
915             
916             $roo->jerr('_invalid_auth_code');
917         }
918         
919         if(!empty($q['oath_key_disable'])) {
920             $person = DB_DataObject::factory('core_person');
921             $person->get($q['id']);
922             
923             $o = clone($person);
924             
925             $person->oath_key = '';
926             $person->update($o);
927             
928             $roo->jok('DONE');
929         }
930         
931         if (!empty($q['query']['is_owner'])) {
932             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
933         }
934         
935         if (!empty($q['query']['person_not_internal'])) {
936             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
937         }
938         
939         if (!empty($q['query']['person_internal_only_all'])) {
940             
941             
942             // must be internal and not current user (need for distribution list)
943             // user has a projectdirectory entry and role is not blank.
944             //DB_DataObject::DebugLevel(1);
945             $pd = DB_DataObject::factory('ProjectDirectory');
946             $pd->whereAdd("role != ''");
947             $pd->selectAdd();
948             $pd->selectAdd('distinct(person_id) as person_id');
949             $roled = $pd->fetchAll('person_id');
950             $rs = $roled  ? "  OR
951                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
952                     " : '';
953             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
954             
955         }
956         // -- for distribution
957         if (!empty($q['query']['person_internal_only'])) {
958             // must be internal and not current user (need for distribution list)
959             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
960             
961             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
962             //    ".id  != ".$au->id);
963             $this->whereAdd("{$this->tableName()}.id != {$au->id}");
964         } 
965         
966         if (!empty($q['query']['comptype_or_company_id'])) {
967            // DB_DataObject::debugLevel(1);
968             $bits = explode(',', $q['query']['comptype_or_company_id']);
969             $id = (int) array_pop($bits);
970             $ct = $this->escape($bits[0]);
971             
972             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
973             
974         }
975         
976         
977         // staff list..
978         if (!empty($q['query']['person_inactive'])) {
979            // DB_Dataobject::debugLevel(1);
980             $this->active = 1;
981         }
982         $tn_p = $this->tableName();
983         $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
984         $tn_g = DB_DataObject::Factory('core_group')->tableName();
985
986         ///---------------- Group views --------
987         if (!empty($q['query']['in_group'])) {
988             // DB_DataObject::debugLevel(1);
989             $ing = (int) $q['query']['in_group'];
990             if ($q['query']['in_group'] == -1) {
991              
992                 // list all staff who are not in a group.
993                 $this->whereAdd("{$this->tableName()}.id NOT IN (
994                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
995                         $tn_g ON $tn_g.id = $tn_gm.group_id)");
996                 
997             } else {
998                 
999                 $this->whereAdd("$tn_p.id IN (
1000                     SELECT distinct(user_id) FROM $tn_gm
1001                         WHERE group_id = $ing
1002                     )");
1003                }
1004             
1005         }
1006         
1007         if(!empty($q['in_group_name'])){
1008             
1009             $v = $this->escape($q['in_group_name']);
1010             
1011             $this->whereAdd("
1012                 $tn_p.id IN (
1013                     SELECT 
1014                         DISTINCT(user_id) FROM $tn_gm
1015                     LEFT JOIN
1016                         $tn_g
1017                     ON
1018                         $tn_g.id = $tn_gm.group_id
1019                     WHERE 
1020                         $tn_g.name = '{$v}'
1021                 )"
1022             );
1023         }
1024         if(!empty($q['in_group_starts'])){
1025             
1026             $v = $this->escape($q['in_group_starts']);
1027             
1028             $this->whereAdd("
1029                 $tn_p.id IN (
1030                     SELECT 
1031                         DISTINCT(user_id) FROM $tn_gm
1032                     LEFT JOIN
1033                         $tn_g
1034                     ON
1035                         $tn_g.id = $tn_gm.group_id
1036                     WHERE 
1037                         $tn_g.name LIKE '{$v}%'
1038                 )"
1039             );
1040         }
1041         
1042         
1043         
1044         // #2307 Search Country!!
1045         if (!empty($q['query']['in_country'])) {
1046             // DB_DataObject::debugLevel(1);
1047             $inc = $q['query']['in_country'];
1048             $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1049         }
1050         
1051         if (!empty($q['query']['not_in_directory'])) { 
1052             // it's a Person list..
1053             // DB_DATaobjecT::debugLevel(1);
1054             
1055             // specific to project directory which is single comp. login
1056             //
1057             $owncomp = DB_DataObject::Factory('core_company');
1058             $owncomp->get('comptype', 'OWNER');
1059             if ($q['company_id'] == $owncomp->id) {
1060                 $this->active =1;
1061             }
1062             
1063             
1064
1065             if ( $q['query']['not_in_directory'] > -1) {
1066                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1067                 // can list current - so that it does not break!!!
1068                 $this->whereAdd("$tn_p.id NOT IN 
1069                     ( SELECT distinct person_id FROM $tn_pd WHERE
1070                         project_id = " . $q['query']['not_in_directory'] . " AND 
1071                         company_id = " . $this->company_id . ')');
1072             }
1073         }
1074            
1075         if (!empty($q['query']['role'])) { 
1076             // it's a Person list..
1077             // DB_DATaobjecT::debugLevel(1);
1078             
1079             // specific to project directory which is single comp. login
1080             //
1081             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1082                 // can list current - so that it does not break!!!
1083             $this->whereAdd("$tn_p.id IN 
1084                     ( SELECT distinct person_id FROM $tn_pd WHERE
1085                         role = '". $this->escape($q['query']['role']) ."'
1086             )");
1087         
1088         }
1089         
1090         
1091         if (!empty($q['query']['project_member_of'])) {
1092                // this is also a flag to return if they are a member..
1093             //DB_DataObject::debugLevel(1);
1094             $do = DB_DataObject::factory('ProjectDirectory');
1095             $do->project_id = $q['query']['project_member_of'];
1096             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1097             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1098             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
1099                 
1100                 
1101             if (!empty($q['query']['project_member_filter'])) {
1102                 $this->having('is_member !=0');
1103             
1104             }
1105             
1106         }
1107         
1108         if(!empty($q['query']['name'])){
1109             $this->whereAdd("
1110                 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1111             ");
1112         }
1113         
1114          if(!empty($q['query']['name_or_email'])){
1115             $v = $this->escape($q['query']['name_or_email']);
1116             $this->whereAdd("
1117                 {$this->tableName()}.name LIKE '%{$v}%'
1118                 OR
1119                 {$this->tableName()}.email LIKE '%{$v}%'
1120             ");
1121         }
1122          if(!empty($q['query']['name_starts'])){
1123             $this->whereAdd("
1124                 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1125             ");
1126         }
1127         
1128         if (!empty($q['query']['search'])) {
1129             
1130             // use our magic search builder...
1131             
1132              require_once 'Text/SearchParser.php';
1133             $x = new Text_SearchParser($q['query']['search']);
1134             
1135             $props = array(
1136                     "$tn_p.name",
1137                     "$tn_p.email",
1138                     "$tn_p.role",
1139                     "$tn_p.phone",
1140                     "$tn_p.remarks",
1141                     "join_company_id_id.name"
1142             );
1143             $tbcols = $this->table();
1144             foreach(array('firstname','lastname') as $k) {
1145                 if (isset($tbcols[$k])) {
1146                     $props[] = "{$tn_p}.{$k}";
1147                 }
1148             }
1149             
1150             
1151             
1152             
1153             $str =  $x->toSQL(array(
1154                 'default' => $props,
1155                 'map' => array(
1156                     'company' => 'join_company_id_id.name',
1157                     //'country' => 'Clipping.country',
1158                     //  'media' => 'Clipping.media_name',
1159                 ),
1160                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1161
1162             ));
1163             
1164             
1165             $this->whereAdd($str); /*
1166                         $tn_p.name LIKE '%$s%'  OR
1167                         $tn_p.email LIKE '%$s%'  OR
1168                         $tn_p.role LIKE '%$s%'  OR
1169                         $tn_p.phone LIKE '%$s%' OR
1170                         $tn_p.remarks LIKE '%$s%' 
1171                         
1172                     ");*/
1173         }
1174         
1175         // project directory rules -- this may distrupt things.
1176         $p = DB_DataObject::factory('ProjectDirectory');
1177         // if project directories are set up, then we can apply project query rules..
1178         if ($p->count()) {
1179             $p->autoJoin();
1180             $pids = $p->projects($au);
1181             if (isset($q['query']['project_id'])) {   
1182                 $pid = (int)$q['query']['project_id'];
1183                 if (!in_array($pid, $pids)) {
1184                     $roo->jerr("Project not in users valid projects");
1185                 }
1186                 $pids = array($pid);
1187             }
1188             // project roles..
1189             //if (empty($q['_anyrole'])) {  // should be project_directry_role
1190             //    $p->whereAdd("{$p->tableName()}.role != ''");
1191             // }
1192             if (!empty($q['query']['role'])) {  // should be project_directry_role
1193                 $role = $this->escape($q['query']['role']); 
1194                
1195                 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1196                  
1197             }
1198             
1199             if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1200                 $peps = $p->people($pids);
1201                 $this->whereAddIn("{$this->tableName()}.id", $peps, 'int');
1202             }
1203         }    
1204         
1205         // fixme - this needs a more generic fix - it was from the mtrack_person code...
1206         if (isset($q['query']['ticket_id'])) {  
1207             // find out what state the ticket is in.
1208             $t = DB_DataObject::Factory('mtrack_ticket');
1209             $t->autoJoin();
1210             $t->get($q['query']['ticket_id']);
1211             
1212             if (!$this->checkPerm('S', $au)) {
1213                 $roo->jerr("permssion denied to query state of ticket");
1214             }
1215             
1216             $p = DB_DataObject::factory('ProjectDirectory');
1217             $pids = array($t->project_id);
1218            
1219             $peps = $p->people($pids);
1220             
1221             $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1222             
1223             //$this->whereAdd('join_prole != ''");
1224             
1225         }
1226         
1227         /*
1228          * Seems we never expose oath_key / passwd, so...
1229          */
1230         
1231         if($this->tableName() == 'core_person'){
1232             $this->_extra_cols = array('length_passwd', 'length_oath_key');
1233         
1234             $this->selectAdd("
1235                 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1236                 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1237             ");
1238         }
1239         if (isset($q['_with_group_membership'])) {
1240             $this->selectAddGroupMemberships();
1241         }
1242         
1243     }
1244     
1245     function selectAddGroupMemberships()
1246     {
1247         $this->selectAdd("
1248             
1249             COALESCE((
1250                 SELECT
1251                     GROUP_CONCAT(  CASE WHEN core_group.display_name = '' THEN core_group.name ELSE core_group.display_name  END  separator  '\n')
1252                 FROM
1253                     core_group_member
1254                 LEFT JOIN
1255                     core_group
1256                 ON
1257                     core_group.id = core_group_member.group_id
1258                 WHERE
1259                     core_group_member.user_id = core_person.id
1260                 ORDER BY
1261                     core_group.display_name ASC
1262             ), '')  as member_of");
1263     }
1264     
1265     function setFromRoo($ar, $roo)
1266     {
1267         $this->setFrom($ar); 
1268         
1269         if(!empty($ar['_enable_oath_key'])){
1270             $oath_key = $this->generateOathKey();
1271         }
1272         
1273         if (!empty($ar['passwd1'])) {
1274             $this->setPassword($ar['passwd1']);
1275         }
1276         
1277         if (    $this->id &&
1278                 ($this->email == $roo->old->email)&&
1279                 ($this->company_id == $roo->old->company_id)
1280             ) {
1281             return true;
1282         }
1283         if (empty($this->email)) {
1284             return true;
1285         }
1286         // this only applies to our owner company..
1287         $c = $this->company();
1288         if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1289             return true;
1290         }
1291         
1292         
1293         $xx = DB_Dataobject::factory($this->tableName());
1294         $xx->setFrom(array(
1295             'email' => $this->email,
1296            // 'company_id' => $x->company_id
1297         ));
1298         
1299         if ($xx->count()) {
1300             return "Duplicate Email found";
1301         }
1302         
1303         return true;
1304     }
1305     /**
1306      *
1307      * before Delete - delete significant dependancies..
1308      * this is called after checkPerm..
1309      */
1310     
1311     function beforeDelete($dependants_array, $roo)
1312     {
1313         //delete group membership except for admin group..
1314         // if they are a member of admin group do not delete anything.
1315         $default_admin = false;
1316         
1317         $e = DB_DataObject::Factory('Events');
1318         $e->whereAdd('person_id = ' . $this->id);
1319         
1320         $g = DB_DataObject::Factory('core_group');
1321         $g->get('name', 'Administrators');  // select * from core_group where name = 'Administrators'
1322         
1323         $p = DB_DataObject::Factory('core_group_member');
1324         $p->setFrom(array(
1325             'user_id' => $this->id,
1326             'group_id' => $g->id
1327         ));
1328
1329         if ($p->count()) {
1330            $roo->jerr("Please remove this user from the Administrator group before deleting");
1331         }
1332  
1333          
1334         $p = DB_DataObject::Factory('core_group_member');
1335         $p->user_id = $this->id;
1336         $mem = $p->fetchAll();  // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1337         $e->logDeletedRecord($mem);
1338                 
1339         foreach($mem as $p) { 
1340             $p->delete();
1341         }  
1342         
1343         $e = DB_DataObject::Factory('Events');        
1344         $e->person_id = $this->id;
1345         $eve = $e->fetchAll();  // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1346
1347         $e->logDeletedRecord($eve);
1348         foreach($eve as $e) { 
1349             $e->delete();
1350         }  
1351         
1352         
1353         // anything else?  
1354         
1355     }
1356     
1357     
1358     /***
1359      * Check if the a user has access to modify this item.
1360      * @param String $lvl Level (eg. Core.Projects)
1361      * @param Pman_Core_DataObjects_Person $au The authenticated user.
1362      * @param boolean $changes alllow changes???
1363      *
1364      * @return false if no access..
1365      */
1366     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1367     {
1368          
1369        // do we have an empty system..
1370         if ($au && $au->id == -1) {
1371             return true;
1372         }
1373         // if not authenticated... do not allow in???
1374         if (!$au ) {
1375             return false;
1376         }
1377         
1378         // determine if it's staff!!!
1379         $owncomp = DB_DataObject::Factory('core_company');
1380         $owncomp->get('comptype', 'OWNER');
1381         $isStaff = ($au->company_id ==  $owncomp->id);
1382        
1383        
1384         if (!$isStaff) {
1385             
1386             // - can not change company!!!
1387             if ($changes && 
1388                 isset($changes['company_id']) && 
1389                 $changes['company_id'] != $au->company_id) {
1390                 return false;
1391             }
1392             // can only set new emails..
1393             if ($changes && 
1394                     !empty($this->email) && 
1395                     isset($changes['email']) && 
1396                     $changes['email'] != $this->email) {
1397                 return false;
1398             }
1399             
1400             
1401             // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1402             // ???? do we want this?
1403             
1404             // edit self... - what about other staff members...
1405             
1406             //return $this->company_id == $au->company_id;
1407         }
1408         
1409          
1410         // yes, only owner company can mess with this...
1411         
1412         
1413         
1414     
1415         switch ($lvl) {
1416             // extra case change passwod?
1417             case 'P': //??? password
1418                 // standard perms -- for editing + if the user is dowing them selves..
1419                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1420                 return $ret || $au->id == $this->id;
1421             
1422             default:                
1423                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1424         
1425         }
1426         return false;
1427     }
1428     
1429     function beforeInsert($req, $roo)
1430     {
1431         $p = DB_DataObject::factory('core_person');
1432         if ($roo->authUser->id > -1 ||  $p->count() > 1) {
1433             return;
1434         }
1435         $c = DB_DataObject::Factory('core_company');
1436         $tc = $c->count();
1437         
1438         if (!$tc || $tc> 1) {
1439             $roo->jerr("can not create initial user as multiple companies already exist");
1440         }
1441         $c->find(true);
1442         $this->company_id = $c->id;
1443         $this->email = trim($this->email);
1444         
1445     }
1446     
1447     function onInsert($req, $roo)
1448     {
1449          
1450         $p = DB_DataObject::factory('core_person');
1451         if ($roo->authUser->id < 0 && $p->count() == 1) {
1452             // this seems a bit risky...
1453             
1454             $g = DB_DataObject::factory('core_group');
1455             $g->initGroups();
1456             
1457             $g->type = 0;
1458             $g->get('name', 'Administrators');
1459             
1460             $p = DB_DataObject::factory('core_group_member');
1461             $p->group_id = $g->id;
1462             $p->user_id = $this->id;     
1463             if (!$p->count()) {
1464                 $p->insert();
1465                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1466             }
1467             $this->login();
1468         }
1469         if (!empty($req['project_id_addto'])) {
1470             $pd = DB_DataObject::factory('ProjectDirectory');
1471             $pd->project_id = $req['project_id_addto'];
1472             $pd->person_id = $this->id; 
1473             $pd->ispm =0;
1474             $pd->office_id = $this->office_id;
1475             $pd->company_id = $this->company_id;
1476             $pd->insert();
1477         }
1478         
1479     }
1480     
1481     function importFromArray($roo, $persons, $opts)
1482     {
1483         if (empty($opts['prefix'])) {
1484             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1485         }
1486         
1487         if (!is_array($persons) || empty($persons)) {
1488             $roo->jerr("error in the person data. - empty on not valid");
1489         }
1490         DB_DataObject::factory('core_group')->initGroups();
1491         
1492         foreach($persons as $person){
1493             $p = DB_DataObject::factory('core_person');
1494             if($p->get('name', $person['name'])){
1495                 continue;
1496             }
1497             $p->setFrom($person);
1498             
1499             $companies = DB_DataObject::factory('core_company');
1500             if(!$companies->get('comptype', 'OWNER')){
1501                 $roo->jerr("Missing OWNER companies!");
1502             }
1503             $p->company_id = $companies->pid();
1504             // strip the 'spaces etc.. make lowercase..
1505             $name = strtolower(str_replace(' ', '', $person['name']));
1506             $p->setPassword("{$opts['prefix']}{$name}");
1507             $p->insert();
1508             // set up groups
1509             // if $person->groups is set.. then
1510             // add this person to that group eg. groups : [ 'Administrator' ] 
1511             if(!empty($person['groups'])){
1512                 $groups = DB_DataObject::factory('core_group');
1513                 if(!$groups->get('name', $person['groups'])){
1514                     $roo->jerr("Missing groups : {$person['groups']}");
1515                 }
1516                 $gm = DB_DataObject::factory('core_group_member');
1517                 $gm->change($p, $groups, true);
1518             }
1519             
1520             $p->onInsert(array(), $roo);
1521         }
1522     }
1523     
1524     // this is for the To: "{getEmailName()}" <email@address>
1525     // not good for Dear XXXX, - use {person.firstname} for that.
1526     function getEmailName()
1527     {
1528         $name = array();
1529         
1530         if(!empty($this->honor)){
1531             array_push($name, $this->honor);
1532         }
1533         
1534         if(!empty($this->name)){
1535             array_push($name, $this->name);
1536             
1537             return implode(' ', $name);
1538         }
1539         
1540         if(!empty($this->firstname) || !empty($this->lastname)){
1541             array_push($name, $this->firstname);
1542             array_push($name, $this->lastname);
1543             
1544             $name = array_filter($name);
1545             
1546             return implode(' ', $name);
1547         }
1548         
1549         return $this->email;
1550     }
1551     
1552     function sesPrefix()
1553     {
1554         $ff= HTML_FlexyFramework::get();
1555         
1556         $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1557         
1558         $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1559         
1560         $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1561
1562         return $sesPrefix;
1563     }
1564     
1565     function loginPublic() // used where???
1566     {
1567         $this->isAuth(); // force session start..
1568          
1569         $db = $this->getDatabaseConnection();
1570         
1571         $ff = HTML_FlexyFramework::get();
1572         
1573         if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1574             return false;
1575         }
1576         
1577         $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1578         
1579         $p = DB_DAtaObject::Factory($this->tableName());
1580         $p->get($this->pid());
1581         
1582         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1583         
1584         return true;
1585     }
1586     
1587     function beforeUpdate($old, $q, $roo)
1588     {
1589         $this->email = trim($this->email);
1590     }
1591     
1592     function generateOathKey()
1593     {
1594         require 'Base32.php';
1595         
1596         $base32 = new Base32();
1597         
1598         return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1599     }
1600     
1601     function generateQRCode($hash)
1602     {
1603         if(
1604             empty($this->email) &&
1605             empty($hash)
1606         ){
1607             return false;
1608         }
1609         
1610         $issuer = rawurlencode($this->qrCodeIssuer());
1611         
1612         $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1613         
1614         require_once 'Image/QRCode.php';
1615         
1616         $qrcode = new Image_QRCode();
1617         
1618         $image = $qrcode->makeCode($uri, array(
1619             'output_type' => 'return'
1620         ));
1621         
1622         ob_start();
1623         imagepng($image);
1624         $base64 = base64_encode(ob_get_contents());
1625         ob_end_clean();
1626         
1627         return "data:image/png;base64,{$base64}";
1628     }
1629     
1630     function qrCodeIssuer()
1631     {
1632         $pg= HTML_FlexyFramework::get()->page;
1633         
1634         $issuer = (empty($pg->company->name)) ?  'ROOJS' : "{$pg->company->name}";
1635         
1636         return $issuer;
1637     }
1638     
1639     static function test_ADMIN_PASSWORD_RESET($pg, $to)
1640     {
1641         $ff = HTML_FlexyFramework::get();
1642         $person = DB_DataObject::Factory('core_person');
1643         $person->id = -1;
1644         
1645         return array(
1646             'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1647             'person' => $person,
1648             'authFrom' => 'FAKE_LINK',
1649             'authKey' => 'FAKE_KEY',
1650
1651             'rcpts' => $to->email,
1652         );
1653         
1654         return $content;
1655     }
1656     
1657     
1658  }