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