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