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