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