DataObjects/Core_person.php
[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         return $url.'/'.$this->id .'/'.$expires.'/'.
553             hash('sha256',
554                 serialize(
555                     array($url, $expires, $this->passwd)
556                 )
557             );
558         
559     }
560     
561     function validateAutoLogin($called)
562     {
563         $bits = explode("/",$called);
564         $hash = array_pop($bits);
565         $time = array_pop($bits);
566         $id = array_pop($bits);
567         $u = DB_DataObject::Factory($this->tableName());
568         $u->get($id);
569         $url = implode("/", $bits);
570         var_dump($time);
571         
572         if ($time < time()) {
573             return false;
574         }
575         if ($hash == hash('sha256', serialize(array($url, $time, $u->email, $u->passwd)))) {
576             $u->login();
577             return $u;
578         }
579         return false;
580     }
581     
582     
583     function checkTwoFactorAuthentication($val)
584     {
585         
586         
587         // also used in login
588         require_once 'System.php';
589         
590         if(
591             empty($this->id) ||
592             empty($this->oath_key)
593         ) {
594             return false;
595         }
596         
597         $oathtool = System::which('oathtool');
598         
599         if (!$oathtool) {
600             return false;
601         }
602         
603         $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
604         
605         $password = exec($cmd);
606         
607         return ($password == $val) ? true : false;
608     }
609     
610     function checkPassword($val)
611     {
612         if (substr($this->passwd,0,1) == '$') {
613             if (function_exists('pasword_verify')) {
614                 return password_verify($val, $this->passwd);
615             }
616             return crypt($val,$this->passwd) == $this->passwd ;
617         }
618         // old style md5 passwords...- cant be used with courier....
619         return md5($val) == $this->passwd;
620     }
621     
622     function setPassword($value) 
623     {
624         if (function_exists('pasword_hash')) {
625             return password_hash($value);
626         }
627         
628         $salt='';
629         while(strlen($salt)<9) {
630             $salt.=chr(rand(64,126));
631             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
632         }
633         $this->passwd = crypt($value, '$1$'. $salt. '$');
634        
635        
636     }      
637     
638     function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
639     {
640         require_once 'Text/Password.php';
641         $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
642         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
643         $this->setPassword($this->rawPasswd);
644         return $this->rawPasswd;
645     }
646     
647     function company()
648     {
649         if (empty($this->company_id)) {
650             return false;
651         }
652         $x = DB_DataObject::factory('core_company');
653         $x->autoJoin();
654         $x->get($this->company_id);
655         return $x;
656     }
657     function loadCompany()
658     {
659         $this->company = $this->company();
660     }
661     
662     function active()
663     { 
664         return $this->active;
665     }
666     function authUserName($n) // set username prior to acheck user exists query.
667     {
668         
669         $this->whereAdd('LENGTH(passwd) > 1'); 
670         $this->email = $n;
671     }
672     function lang()
673     {
674         if (!func_num_args()) {
675             return $this->lang;
676         }
677         $ar = func_get_args();
678         $val = array_shift($ar);
679         if ($val == $this->lang) {
680             return;
681         }
682         $uu = clone($this);
683         $this->lang = $val;
684         $this->update($uu);
685         return $this->lang;
686     }
687             
688     
689     function authUserArray()
690     {
691         $aur = $this->toArray();
692         
693         if ($this->id < 1) {
694             return $aur;
695         }
696         
697         //DB_DataObject::debugLevel(1);
698         $c = DB_Dataobject::factory('core_company');
699         $im = DB_Dataobject::factory('Images');
700         $c->joinAdd($im, 'LEFT');
701         $c->selectAdd();
702         $c->selectAs($c, 'company_id_%s');
703         $c->selectAs($im, 'company_id_logo_id_%s');
704         $c->id = $this->company_id;
705         $c->limit(1);
706         $c->find(true);
707         
708         $aur = array_merge( $c->toArray(),$aur);
709         
710         if (empty($c->company_id_logo_id_id))  {
711                  
712             $im = DB_Dataobject::factory('Images');
713             $im->ontable = DB_DataObject::factory('core_company')->tableName();
714             $im->onid = $c->id;
715             $im->imgtype = 'LOGO';
716             $im->limit(1);
717             $im->selectAdd();
718             $im->selectAs($im,  'company_id_logo_id_%s');
719             if ($im->find(true)) {
720                 
721                 foreach($im->toArray() as $k=>$v) {
722                     if (!preg_match('/^company_id_logo_id_/', $k)) {
723                         continue;
724                     }
725                     $aur[$k] = $v;
726                 }
727             }
728         }
729       
730         // perms + groups.
731         $aur['perms']  = $this->getPerms();
732         $g = DB_DataObject::Factory('core_group_member');
733         $aur['groups']  = $g->listGroupMembership($this, 'name');
734         
735         $aur['passwd'] = '';
736         $aur['dailykey'] = '';
737         $aur['oath_key'] = '';
738         
739         $aur['oath_key_enable'] = !empty($this->oath_key);
740         $aur['require_oath'] = 1;
741         
742         $s = DB_DataObject::Factory('core_setting');
743         $oath_require = $s->lookup('core', 'two_factor_auth_required');
744         $aur['require_oath'] = $oath_require ?  $oath_require->val : 0;
745         
746         $aur['core_person_settings'] = array();
747                 
748         $core_person_settings = DB_DataObject::factory('core_person_settings');
749         $core_person_settings->setFrom(array(
750             'person_id' => $this->id
751         ));
752         
753         $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
754         
755         return $aur;
756     }
757     
758     //   ----------PERMS------  ----------------
759     function getPerms() 
760     {
761          //DB_DataObject::debugLevel(1);
762         // find out all the groups they are a member of.. + Default..
763         
764         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
765         
766         $g = DB_DataObject::Factory('core_group_right');
767         if (!$g->count()) {
768             $g->genDefault();
769         }
770         
771         if ($this->id < 0) {
772             return $g->adminRights(); // system is not set up - so they get full rights.
773         }
774         //DB_DataObject::debugLevel(1);
775         $g = DB_DataObject::Factory('core_group_member');
776         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
777         if (!$g->count()) {
778             // add the current user to the admin group..
779             $g = DB_DataObject::Factory('core_group');
780             if ($g->get('name', 'Administrators')) {
781                 $gm = DB_DataObject::Factory('core_group_member');
782                 $gm->group_id = $g->id;
783                 $gm->user_id = $this->id;
784                 $gm->insert();
785             }
786             
787         }
788         
789         // ------ STANDARD PERMISSION HANDLING.
790         $isOwner = $this->company()->comptype == 'OWNER';
791         $g = DB_DataObject::Factory('core_group_member');
792         $grps = $g->listGroupMembership($this);
793        //var_dump($grps);
794         $isAdmin = $g->inAdmin;   //???  what???
795         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
796         // the load all the perms for those groups, and add them all together..
797         // then load all those 
798         $g = DB_DataObject::Factory('core_group_right');
799         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
800         //echo '<PRE>';print_r($ret);
801         return $ret;
802          
803         
804     }
805     /**
806      *Basic group fetching - probably needs to filter by type eventually.
807      *
808      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
809      */
810     
811     function groups($what=false)
812     {
813         $g = DB_DataObject::Factory('core_group_member');
814         $grps = $g->listGroupMembership($this);
815         $g = DB_DataObject::Factory('core_group');
816         $g->whereAddIn('id', $grps, 'int');
817         return $g->fetchAll($what);
818         
819     }
820     
821     
822     
823     function hasPerm($name, $lvl) 
824     {
825         static $pcache = array();
826         
827         if (!isset($pcache[$this->id])) {
828             $pcache[$this->id] = $this->getPerms();
829         }
830         
831        // echo "<PRE>";print_r($pcache[$au->id]);
832        // var_dump($pcache[$au->id]);
833         if (empty($pcache[$this->id][$name])) {
834             return false;
835         }
836         
837         return strpos($pcache[$this->id][$name], $lvl) > -1;
838         
839     }    
840     
841     //  ------------ROO HOOKS------------------------------------
842     function applyFilters($q, $au, $roo)
843     {
844         //DB_DataObject::DebugLevel(1);
845         if(!empty($q['_to_qr_code'])){
846             $person = DB_DataObject::factory('Core_person');
847             $person->id = $q['id']; 
848             
849             if(!$person->find(true)) {
850                 $roo->jerr('_invalid_person');
851             }
852             
853             $hash = $this->generateOathKey();
854             
855             $_SESSION[__CLASS__] = 
856                 isset($_SESSION[__CLASS__]) ? 
857                     $_SESSION[__CLASS__] : array();
858             $_SESSION[__CLASS__]['oath'] = 
859                 isset($_SESSION[__CLASS__]['oath']) ? 
860                     $_SESSION[__CLASS__]['oath'] : array();
861                 
862             $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
863
864             $qrcode = $person->generateQRCode($hash);
865             
866             if(empty($qrcode)){
867                 $roo->jerr('Fail to generate QR Code');
868             }
869             
870             $roo->jdata(array(
871                 'secret' => $hash,
872                 'image' => $qrcode,
873                 'issuer' => $person->qrCodeIssuer()
874             ));
875         }
876         
877         if(!empty($q['two_factor_auth_code'])) {
878             $person = DB_DataObject::factory('core_person');
879             $person->get($q['id']);
880             $o = clone($person);
881             $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
882             
883             if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
884                 $person->update($o);
885                 unset($_SESSION[__CLASS__]['oath'][$person->id]);
886                 $roo->jok('DONE');
887             }
888             
889             $roo->jerr('_invalid_auth_code');
890         }
891         
892         if(!empty($q['oath_key_disable'])) {
893             $person = DB_DataObject::factory('core_person');
894             $person->get($q['id']);
895             
896             $o = clone($person);
897             
898             $person->oath_key = '';
899             $person->update($o);
900             
901             $roo->jok('DONE');
902         }
903         
904         if (!empty($q['query']['is_owner'])) {
905             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
906         }
907         
908         if (!empty($q['query']['person_not_internal'])) {
909             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
910         }
911         
912         if (!empty($q['query']['person_internal_only_all'])) {
913             
914             
915             // must be internal and not current user (need for distribution list)
916             // user has a projectdirectory entry and role is not blank.
917             //DB_DataObject::DebugLevel(1);
918             $pd = DB_DataObject::factory('ProjectDirectory');
919             $pd->whereAdd("role != ''");
920             $pd->selectAdd();
921             $pd->selectAdd('distinct(person_id) as person_id');
922             $roled = $pd->fetchAll('person_id');
923             $rs = $roled  ? "  OR
924                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
925                     " : '';
926             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
927             
928         }
929         // -- for distribution
930         if (!empty($q['query']['person_internal_only'])) {
931             // must be internal and not current user (need for distribution list)
932             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
933             
934             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
935             //    ".id  != ".$au->id);
936             $this->whereAdd("{$this->tableName()}.id != {$au->id}");
937         } 
938         
939         if (!empty($q['query']['comptype_or_company_id'])) {
940            // DB_DataObject::debugLevel(1);
941             $bits = explode(',', $q['query']['comptype_or_company_id']);
942             $id = (int) array_pop($bits);
943             $ct = $this->escape($bits[0]);
944             
945             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
946             
947         }
948         
949         
950         // staff list..
951         if (!empty($q['query']['person_inactive'])) {
952            // DB_Dataobject::debugLevel(1);
953             $this->active = 1;
954         }
955         $tn_p = $this->tableName();
956         $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
957         $tn_g = DB_DataObject::Factory('core_group')->tableName();
958
959         ///---------------- Group views --------
960         if (!empty($q['query']['in_group'])) {
961             // DB_DataObject::debugLevel(1);
962             $ing = (int) $q['query']['in_group'];
963             if ($q['query']['in_group'] == -1) {
964              
965                 // list all staff who are not in a group.
966                 $this->whereAdd("{$this->tableName()}.id NOT IN (
967                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
968                         $tn_g ON $tn_g.id = $tn_gm.group_id)");
969                 
970             } else {
971                 
972                 $this->whereAdd("$tn_p.id IN (
973                     SELECT distinct(user_id) FROM $tn_gm
974                         WHERE group_id = $ing
975                     )");
976                }
977             
978         }
979         
980         if(!empty($q['in_group_name'])){
981             
982             $v = $this->escape($q['in_group_name']);
983             
984             $this->whereAdd("
985                 $tn_p.id IN (
986                     SELECT 
987                         DISTINCT(user_id) FROM $tn_gm
988                     LEFT JOIN
989                         $tn_g
990                     ON
991                         $tn_g.id = $tn_gm.group_id
992                     WHERE 
993                         $tn_g.name = '{$v}'
994                 )"
995             );
996         }
997         
998         // #2307 Search Country!!
999         if (!empty($q['query']['in_country'])) {
1000             // DB_DataObject::debugLevel(1);
1001             $inc = $q['query']['in_country'];
1002             $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1003         }
1004         
1005         if (!empty($q['query']['not_in_directory'])) { 
1006             // it's a Person list..
1007             // DB_DATaobjecT::debugLevel(1);
1008             
1009             // specific to project directory which is single comp. login
1010             //
1011             $owncomp = DB_DataObject::Factory('core_company');
1012             $owncomp->get('comptype', 'OWNER');
1013             if ($q['company_id'] == $owncomp->id) {
1014                 $this->active =1;
1015             }
1016             
1017             
1018
1019             if ( $q['query']['not_in_directory'] > -1) {
1020                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1021                 // can list current - so that it does not break!!!
1022                 $this->whereAdd("$tn_p.id NOT IN 
1023                     ( SELECT distinct person_id FROM $tn_pd WHERE
1024                         project_id = " . $q['query']['not_in_directory'] . " AND 
1025                         company_id = " . $this->company_id . ')');
1026             }
1027         }
1028            
1029         if (!empty($q['query']['role'])) { 
1030             // it's a Person list..
1031             // DB_DATaobjecT::debugLevel(1);
1032             
1033             // specific to project directory which is single comp. login
1034             //
1035             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1036                 // can list current - so that it does not break!!!
1037             $this->whereAdd("$tn_p.id IN 
1038                     ( SELECT distinct person_id FROM $tn_pd WHERE
1039                         role = '". $this->escape($q['query']['role']) ."'
1040             )");
1041         
1042         }
1043         
1044         
1045         if (!empty($q['query']['project_member_of'])) {
1046                // this is also a flag to return if they are a member..
1047             //DB_DataObject::debugLevel(1);
1048             $do = DB_DataObject::factory('ProjectDirectory');
1049             $do->project_id = $q['query']['project_member_of'];
1050             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1051             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1052             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
1053                 
1054                 
1055             if (!empty($q['query']['project_member_filter'])) {
1056                 $this->having('is_member !=0');
1057             
1058             }
1059             
1060         }
1061         
1062         if(!empty($q['query']['name'])){
1063             $this->whereAdd("
1064                 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1065             ");
1066         }
1067          if(!empty($q['query']['name_starts'])){
1068             $this->whereAdd("
1069                 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1070             ");
1071         }
1072         
1073         if (!empty($q['query']['search'])) {
1074             
1075             // use our magic search builder...
1076             
1077              require_once 'Text/SearchParser.php';
1078             $x = new Text_SearchParser($q['query']['search']);
1079             
1080             $props = array(
1081                     "$tn_p.name",
1082                     "$tn_p.email",
1083                     "$tn_p.role",
1084                     "$tn_p.phone",
1085                     "$tn_p.remarks",
1086                     "join_company_id_id.name"
1087             );
1088             $tbcols = $this->table();
1089             foreach(array('firstname','lastname') as $k) {
1090                 if (isset($tbcols[$k])) {
1091                     $props[] = "{$tn_p}.{$k}";
1092                 }
1093             }
1094             
1095             
1096             
1097             
1098             $str =  $x->toSQL(array(
1099                 'default' => $props,
1100                 'map' => array(
1101                     'company' => 'join_company_id_id.name',
1102                     //'country' => 'Clipping.country',
1103                     //  'media' => 'Clipping.media_name',
1104                 ),
1105                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1106
1107             ));
1108             
1109             
1110             $this->whereAdd($str); /*
1111                         $tn_p.name LIKE '%$s%'  OR
1112                         $tn_p.email LIKE '%$s%'  OR
1113                         $tn_p.role LIKE '%$s%'  OR
1114                         $tn_p.phone LIKE '%$s%' OR
1115                         $tn_p.remarks LIKE '%$s%' 
1116                         
1117                     ");*/
1118         }
1119         
1120         // project directory rules -- this may distrupt things.
1121         $p = DB_DataObject::factory('ProjectDirectory');
1122         // if project directories are set up, then we can apply project query rules..
1123         if ($p->count()) {
1124             $p->autoJoin();
1125             $pids = $p->projects($au);
1126             if (isset($q['query']['project_id'])) {   
1127                 $pid = (int)$q['query']['project_id'];
1128                 if (!in_array($pid, $pids)) {
1129                     $roo->jerr("Project not in users valid projects");
1130                 }
1131                 $pids = array($pid);
1132             }
1133             // project roles..
1134             //if (empty($q['_anyrole'])) {  // should be project_directry_role
1135             //    $p->whereAdd("{$p->tableName()}.role != ''");
1136             // }
1137             if (!empty($q['query']['role'])) {  // should be project_directry_role
1138                 $role = $this->escape($q['query']['role']); 
1139                
1140                 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1141                  
1142             }
1143             
1144             if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1145                 $peps = $p->people($pids);
1146                 $this->whereAddIn("{$tn}.id", $peps, 'int');
1147             }
1148         }    
1149         
1150         // fixme - this needs a more generic fix - it was from the mtrack_person code...
1151         if (isset($q['query']['ticket_id'])) {  
1152             // find out what state the ticket is in.
1153             $t = DB_DataObject::Factory('mtrack_ticket');
1154             $t->autoJoin();
1155             $t->get($q['query']['ticket_id']);
1156             
1157             if (!$this->checkPerm('S', $au)) {
1158                 $roo->jerr("permssion denied to query state of ticket");
1159             }
1160             
1161             $p = DB_DataObject::factory('ProjectDirectory');
1162             $pids = array($t->project_id);
1163            
1164             $peps = $p->people($pids);
1165             
1166             $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1167             
1168             //$this->whereAdd('join_prole != ''");
1169             
1170         }
1171         
1172         /*
1173          * Seems we never expose oath_key / passwd, so...
1174          */
1175         
1176         if($this->tableName() == 'core_person'){
1177             $this->_extra_cols = array('length_passwd', 'length_oath_key');
1178         
1179             $this->selectAdd("
1180                 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1181                 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1182             ");
1183         }
1184         if (isset($q['_with_group_membership'])) {
1185             $this->selectAddGroupMemberships();
1186         }
1187         
1188     }
1189     
1190     function selectAddGroupMemberships()
1191     {
1192         $this->selectAdd("
1193             
1194             COALESCE((
1195                 SELECT
1196                     GROUP_CONCAT(  core_group.name separator  '\n')
1197                 FROM
1198                     core_group_member
1199                 LEFT JOIN
1200                     core_group
1201                 ON
1202                     core_group.id = core_group_member.group_id
1203                 WHERE
1204                     core_group_member.user_id = core_person.id
1205             ), '')  as member_of");
1206     }
1207     
1208     function setFromRoo($ar, $roo)
1209     {
1210         $this->setFrom($ar); 
1211         
1212         if(!empty($ar['_enable_oath_key'])){
1213             $oath_key = $this->generateOathKey();
1214         }
1215         
1216         if (!empty($ar['passwd1'])) {
1217             $this->setPassword($ar['passwd1']);
1218         }
1219         
1220         if (    $this->id &&
1221                 ($this->email == $roo->old->email)&&
1222                 ($this->company_id == $roo->old->company_id)
1223             ) {
1224             return true;
1225         }
1226         if (empty($this->email)) {
1227             return true;
1228         }
1229         // this only applies to our owner company..
1230         $c = $this->company();
1231         if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1232             return true;
1233         }
1234         
1235         
1236         $xx = DB_Dataobject::factory($this->tableName());
1237         $xx->setFrom(array(
1238             'email' => $this->email,
1239            // 'company_id' => $x->company_id
1240         ));
1241         
1242         if ($xx->count()) {
1243             return "Duplicate Email found";
1244         }
1245         
1246         return true;
1247     }
1248     /**
1249      *
1250      * before Delete - delete significant dependancies..
1251      * this is called after checkPerm..
1252      */
1253     
1254     function beforeDelete($dependants_array, $roo)
1255     {
1256         //delete group membership except for admin group..
1257         // if they are a member of admin group do not delete anything.
1258         $default_admin = false;
1259         
1260         $e = DB_DataObject::Factory('Events');
1261         $e->whereAdd('person_id = ' . $this->id);
1262         
1263         $g = DB_DataObject::Factory('core_group');
1264         $g->get('name', 'Administrators');  // select * from core_group where name = 'Administrators'
1265         
1266         $p = DB_DataObject::Factory('core_group_member');
1267         $p->setFrom(array(
1268             'user_id' => $this->id,
1269             'group_id' => $g->id
1270         ));
1271
1272         if ($p->count()) {
1273            $roo->jerr("Please remove this user from the Administrator group before deleting");
1274         }
1275  
1276          
1277         $p = DB_DataObject::Factory('core_group_member');
1278         $p->user_id = $this->id;
1279         $mem = $p->fetchAll();  // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1280         $e->logDeletedRecord($mem);
1281                 
1282         foreach($mem as $p) { 
1283             $p->delete();
1284         }  
1285         
1286         $e = DB_DataObject::Factory('Events');        
1287         $e->person_id = $this->id;
1288         $eve = $e->fetchAll();  // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1289
1290         $e->logDeletedRecord($eve);
1291         foreach($eve as $e) { 
1292             $e->delete();
1293         }  
1294         
1295         
1296         // anything else?  
1297         
1298     }
1299     
1300     
1301     /***
1302      * Check if the a user has access to modify this item.
1303      * @param String $lvl Level (eg. Core.Projects)
1304      * @param Pman_Core_DataObjects_Person $au The authenticated user.
1305      * @param boolean $changes alllow changes???
1306      *
1307      * @return false if no access..
1308      */
1309     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1310     {
1311          
1312        // do we have an empty system..
1313         if ($au && $au->id == -1) {
1314             return true;
1315         }
1316         // if not authenticated... do not allow in???
1317         if (!$au ) {
1318             return false;
1319         }
1320         
1321         // determine if it's staff!!!
1322         $owncomp = DB_DataObject::Factory('core_company');
1323         $owncomp->get('comptype', 'OWNER');
1324         $isStaff = ($au->company_id ==  $owncomp->id);
1325        
1326        
1327         if (!$isStaff) {
1328             
1329             // - can not change company!!!
1330             if ($changes && 
1331                 isset($changes['company_id']) && 
1332                 $changes['company_id'] != $au->company_id) {
1333                 return false;
1334             }
1335             // can only set new emails..
1336             if ($changes && 
1337                     !empty($this->email) && 
1338                     isset($changes['email']) && 
1339                     $changes['email'] != $this->email) {
1340                 return false;
1341             }
1342             
1343             
1344             // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1345             // ???? do we want this?
1346             
1347             // edit self... - what about other staff members...
1348             
1349             //return $this->company_id == $au->company_id;
1350         }
1351         
1352          
1353         // yes, only owner company can mess with this...
1354         
1355         
1356         
1357     
1358         switch ($lvl) {
1359             // extra case change passwod?
1360             case 'P': //??? password
1361                 // standard perms -- for editing + if the user is dowing them selves..
1362                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1363                 return $ret || $au->id == $this->id;
1364             
1365             default:                
1366                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1367         
1368         }
1369         return false;
1370     }
1371     
1372     function beforeInsert($req, $roo)
1373     {
1374         $p = DB_DataObject::factory('core_person');
1375         if ($roo->authUser->id > -1 ||  $p->count() > 1) {
1376             return;
1377         }
1378         $c = DB_DataObject::Factory('core_company');
1379         $tc = $c->count();
1380         
1381         if (!$tc || $tc> 1) {
1382             $roo->jerr("can not create initial user as multiple companies already exist");
1383         }
1384         $c->find(true);
1385         $this->company_id = $c->id;
1386         $this->email = trim($this->email);
1387         
1388     }
1389     
1390     function onInsert($req, $roo)
1391     {
1392          
1393         $p = DB_DataObject::factory('core_person');
1394         if ($roo->authUser->id < 0 && $p->count() == 1) {
1395             // this seems a bit risky...
1396             
1397             $g = DB_DataObject::factory('core_group');
1398             $g->initGroups();
1399             
1400             $g->type = 0;
1401             $g->get('name', 'Administrators');
1402             
1403             $p = DB_DataObject::factory('core_group_member');
1404             $p->group_id = $g->id;
1405             $p->user_id = $this->id;     
1406             if (!$p->count()) {
1407                 $p->insert();
1408                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1409             }
1410             $this->login();
1411         }
1412         if (!empty($req['project_id_addto'])) {
1413             $pd = DB_DataObject::factory('ProjectDirectory');
1414             $pd->project_id = $req['project_id_addto'];
1415             $pd->person_id = $this->id; 
1416             $pd->ispm =0;
1417             $pd->office_id = $this->office_id;
1418             $pd->company_id = $this->company_id;
1419             $pd->insert();
1420         }
1421         
1422     }
1423     
1424     function importFromArray($roo, $persons, $opts)
1425     {
1426         if (empty($opts['prefix'])) {
1427             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1428         }
1429         
1430         if (!is_array($persons) || empty($persons)) {
1431             $roo->jerr("error in the person data. - empty on not valid");
1432         }
1433         DB_DataObject::factory('core_group')->initGroups();
1434         
1435         foreach($persons as $person){
1436             $p = DB_DataObject::factory('core_person');
1437             if($p->get('name', $person['name'])){
1438                 continue;
1439             }
1440             $p->setFrom($person);
1441             
1442             $companies = DB_DataObject::factory('core_company');
1443             if(!$companies->get('comptype', 'OWNER')){
1444                 $roo->jerr("Missing OWNER companies!");
1445             }
1446             $p->company_id = $companies->pid();
1447             // strip the 'spaces etc.. make lowercase..
1448             $name = strtolower(str_replace(' ', '', $person['name']));
1449             $p->setPassword("{$opts['prefix']}{$name}");
1450             $p->insert();
1451             // set up groups
1452             // if $person->groups is set.. then
1453             // add this person to that group eg. groups : [ 'Administrator' ] 
1454             if(!empty($person['groups'])){
1455                 $groups = DB_DataObject::factory('core_group');
1456                 if(!$groups->get('name', $person['groups'])){
1457                     $roo->jerr("Missing groups : {$person['groups']}");
1458                 }
1459                 $gm = DB_DataObject::factory('core_group_member');
1460                 $gm->change($p, $groups, true);
1461             }
1462             
1463             $p->onInsert(array(), $roo);
1464         }
1465     }
1466     
1467     // this is for the To: "{getEmailName()}" <email@address>
1468     // not good for Dear XXXX, - use {person.firstname} for that.
1469     function getEmailName()
1470     {
1471         $name = array();
1472         
1473         if(!empty($this->honor)){
1474             array_push($name, $this->honor);
1475         }
1476         
1477         if(!empty($this->name)){
1478             array_push($name, $this->name);
1479             
1480             return implode(' ', $name);
1481         }
1482         
1483         if(!empty($this->firstname) || !empty($this->lastname)){
1484             array_push($name, $this->firstname);
1485             array_push($name, $this->lastname);
1486             
1487             $name = array_filter($name);
1488             
1489             return implode(' ', $name);
1490         }
1491         
1492         return $this->email;
1493     }
1494     
1495     function sesPrefix()
1496     {
1497         $ff= HTML_FlexyFramework::get();
1498         
1499         $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1500         
1501         $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1502         
1503         $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1504
1505         return $sesPrefix;
1506     }
1507     
1508     function loginPublic() // used where???
1509     {
1510         $this->isAuth(); // force session start..
1511          
1512         $db = $this->getDatabaseConnection();
1513         
1514         $ff = HTML_FlexyFramework::get();
1515         
1516         if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1517             return false;
1518         }
1519         
1520         $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1521         
1522         $p = DB_DAtaObject::Factory($this->tableName());
1523         $p->get($this->pid());
1524         
1525         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1526         
1527         return true;
1528     }
1529     
1530     function beforeUpdate($old, $q, $roo)
1531     {
1532         $this->email = trim($this->email);
1533     }
1534     
1535     function generateOathKey()
1536     {
1537         require 'Base32.php';
1538         
1539         $base32 = new Base32();
1540         
1541         return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1542     }
1543     
1544     function generateQRCode($hash)
1545     {
1546         if(
1547             empty($this->email) &&
1548             empty($hash)
1549         ){
1550             return false;
1551         }
1552         
1553         $issuer = rawurlencode($this->qrCodeIssuer());
1554         
1555         $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1556         
1557         require_once 'Image/QRCode.php';
1558         
1559         $qrcode = new Image_QRCode();
1560         
1561         $image = $qrcode->makeCode($uri, array(
1562             'output_type' => 'return'
1563         ));
1564         
1565         ob_start();
1566         imagepng($image);
1567         $base64 = base64_encode(ob_get_contents());
1568         ob_end_clean();
1569         
1570         return "data:image/png;base64,{$base64}";
1571     }
1572     
1573     function qrCodeIssuer()
1574     {
1575         $pg= HTML_FlexyFramework::get()->page;
1576         
1577         $issuer = (empty($pg->company->name)) ?  'ROOJS' : "{$pg->company->name}";
1578         
1579         return $issuer;
1580     }
1581     
1582     static function test_ADMIN_PASSWORD_RESET($pg, $to)
1583     {
1584         $ff = HTML_FlexyFramework::get();
1585         $person = DB_DataObject::Factory('core_person');
1586         $person->id = -1;
1587         
1588         return array(
1589             'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1590             'person' => $person,
1591             'authFrom' => 'FAKE_LINK',
1592             'authKey' => 'FAKE_KEY',
1593
1594             'rcpts' => $to->email,
1595         );
1596         
1597         return $content;
1598     }
1599     
1600     
1601  }