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