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