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