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