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