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