DataObjects/Person.php
[Pman.Core] / DataObjects / Person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 require_once 'DB/DataObject.php';
6
7
8 class Pman_Core_DataObjects_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 = '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     
46     public $phone_mobile; // varchar(32)  NOT NULL  DEFAULT '';
47     public $phone_direct; // varchar(32)  NOT NULL  DEFAULT '';
48     
49     /* the code above is auto generated do not remove the tag below */
50     ###END_AUTOCODE
51     
52     function owner()
53     {
54         $p = DB_DataObject::Factory('Person');
55         $p->get($this->owner_id);
56         return $p;
57     }
58     
59     /**
60      *
61      *
62      *
63      *
64      *  FIXME !!!! -- USE Pman_Core_Mailer !!!!!
65      *
66      *
67      *
68      *  
69      */
70     function buildMail($templateFile, $args)
71     {
72           
73         $args = (array) $args;
74         $content  = clone($this);
75         
76         foreach((array)$args as $k=>$v) {
77             $content->$k = $v;
78         }
79         
80         $ff = HTML_FlexyFramework::get();
81         
82         
83         //?? is this really the place for this???
84         if (
85                 !$ff->cli && 
86                 empty($args['no_auth']) &&
87                 !in_array($templateFile, array(
88                     // templates that can be sent without authentication.
89                      'password_reset' ,
90                      'password_welcome'
91                  ))
92             ) {
93             
94             $content->authUser = $this->getAuthUser();
95             if (!$content->authUser) {
96                 return PEAR::raiseError("Not authenticated");
97             }
98         }
99         
100         // should handle x-forwarded...
101         
102         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
103             $_SERVER["HTTP_HOST"] :
104             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
105             
106         /* use the regex compiler, as it doesnt parse <tags */
107         
108         $tops = array(
109             'compiler'    => 'Flexy',
110             'nonHTML' => true,
111             'filters' => array('SimpleTags','Mail'),
112             //     'debug'=>1,
113         );
114         
115         
116         
117         if (!empty($args['templateDir'])) {
118             $tops['templateDir'] = $args['templateDir'];
119         }
120         
121         
122         
123         require_once 'HTML/Template/Flexy.php';
124         $template = new HTML_Template_Flexy( $tops );
125         $template->compile("mail/$templateFile.txt");
126         
127         /* use variables from this object to ouput data. */
128         $mailtext = $template->bufferedOutputObject($content);
129         
130         $htmlbody = false;
131         // if a html file with the same name exists, use that as the body
132         // I've no idea where this code went, it was here before..
133         if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
134             $tops['nonHTML'] = false;
135             $template = new HTML_Template_Flexy( $tops );
136             $template->compile("mail/$templateFile.html");
137             $htmlbody = $template->bufferedOutputObject($content);
138             
139         }
140         
141         
142         
143         //echo "<PRE>";print_R($mailtext);
144         //print_R($mailtext);exit;
145         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
146         require_once 'Mail/mimeDecode.php';
147         require_once 'Mail.php';
148         
149         $decoder = new Mail_mimeDecode($mailtext);
150         $parts = $decoder->getSendArray();
151         
152         if (PEAR::isError($parts)) {
153             return $parts;
154             //echo "PROBLEM: {$parts->message}";
155             //exit;
156         } 
157         list($recipents,$headers,$body) = $parts;
158         $recipents = array($this->email);
159         if (!empty($content->bcc) && is_array($content->bcc)) {
160             $recipents =array_merge($recipents, $content->bcc);
161         }
162         $headers['Date'] = date('r');
163         
164         if ($htmlbody !== false) {
165             require_once 'Mail/mime.php';
166             $mime = new Mail_mime(array('eol' => "\n"));
167             $mime->setTXTBody($body);
168             $mime->setHTMLBody($htmlbody);
169             // I think there might be code in mediaoutreach toEmail somewhere
170             // h embeds images here..
171             $body = $mime->get();
172             $headers = $mime->headers($headers);
173             
174         }
175         
176          
177         
178         return array(
179             'recipients' => $recipents,
180             'headers'    => $headers,
181             'body'      => $body
182         );
183         
184         
185     }
186     
187     
188     /**
189      * send a template
190      * - user must be authenticate or args[no_auth] = true
191      *   or template = password_[reset|welcome]
192      * 
193      */
194     function sendTemplate($templateFile, $args)
195     {
196         
197         $ar = $this->buildMail($templateFile, $args);
198       
199         
200         //print_r($recipents);exit;
201         $mailOptions = PEAR::getStaticProperty('Mail','options');
202         $mail = Mail::factory("SMTP",$mailOptions);
203         
204         if (PEAR::isError($mail)) {
205             return $mail;
206         } 
207         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
208         $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
209         error_reporting($oe);
210        
211         return $ret;
212     
213     }
214     
215   
216     
217     
218     function getEmailFrom()
219     {
220         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
221     }
222     function toEventString() 
223     {
224         return empty($this->name) ? $this->email : $this->name;
225     } 
226     function verifyAuth()
227     { 
228         $ff= HTML_FlexyFramework::get();
229         if (!empty($ff->Pman['auth_comptype']) &&
230             (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
231            ){
232             
233             // force a logout - without a check on the isAuth - as this is called from there..
234             $db = $this->getDatabaseConnection();
235             $sesPrefix = $ff->appNameShort .'-'.get_class($this) .'-'.$db->dsn['database'] ;
236             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
237             return false;
238             
239             $ff->page->jerr("Login not permited to outside companies");
240         }
241         return true;
242         
243     }    
244    
245    
246     //   ---------------- authentication / passwords and keys stuff  ----------------
247     function isAuth()
248     {
249         $db = $this->getDatabaseConnection();
250         // we combine db + project names,
251         // otherwise if projects use different 'auth' objects
252         // then we get unserialize issues.
253         $ff= HTML_FlexyFramework::get();
254         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
255         
256         
257         @session_start();
258          
259         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
260             // in session...
261             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
262             
263             $u = DB_DataObject::factory('Person');
264             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
265               
266                 return $u->verifyAuth();
267                 
268    
269                 return true;
270             }
271             
272             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
273             
274         }
275         // local auth - 
276         $default_admin = false;
277         if (!empty($ff->Pman['local_autoauth']) && 
278             ($ff->Pman['local_autoauth'] === true) &&
279             (!empty($_SERVER['SERVER_ADDR'])) &&
280             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
281             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
282         ) {
283             $group = DB_DataObject::factory('Groups');
284             $group->get('name', 'Administrators');
285             
286             $member = DB_DataObject::factory('group_members');
287             $member->group_id = $group->id;
288             if($member->find(true)){
289                 $default_admin = DB_DataObject::factory('Person');
290                 if(!$default_admin->get($member->user_id)){
291                     $default_admin = false;
292                 }
293             }
294         }
295         
296         $u = DB_DataObject::factory('Person');
297         $ff = HTML_FlexyFramework::get();
298         if (!empty($ff->Pman['local_autoauth']) && 
299             (!empty($_SERVER['SERVER_ADDR'])) &&
300             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
301             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
302             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
303         ) {
304             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($default_admin ? $default_admin : $u);
305             return true;
306         }
307            
308         // http basic auth..
309         $u = DB_DataObject::factory('Person');
310
311         if (!empty($_SERVER['PHP_AUTH_USER']) 
312             &&
313             !empty($_SERVER['PHP_AUTH_PW'])
314             &&
315             $u->get('email', $_SERVER['PHP_AUTH_USER'])
316             &&
317             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
318            ) {
319             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
320             return true; 
321         }
322         
323         if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
324             return false;
325         }
326         
327         // not in session or not matched...
328         $u = DB_DataObject::factory('Person');
329         $u->whereAdd(' LENGTH(passwd) > 0');
330         $n = $u->count();
331         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
332         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
333         if ($error) {
334             die($error->toString()); // not really a good thing to do...
335         }
336         if (!$n){ // authenticated as there are no users in the system...
337             return true;
338         }
339         
340         return false;
341         
342     }
343     function getAuthUser()
344     {
345         if (!$this->isAuth()) {
346             return false;
347         }
348         $db = $this->getDatabaseConnection();
349         
350         $ff= HTML_FlexyFramework::get();
351         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
352
353         
354         
355         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
356             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
357             
358             $u = DB_DataObject::factory('Person');
359             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
360                 return clone($u);
361             }
362              
363         }
364         
365         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
366             $u = DB_DataObject::factory('Person');
367             $u->whereAdd(' LENGTH(passwd) > 0');
368              $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
369         }
370                 
371              
372         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
373             
374             // fake person - open system..
375             //$ce = DB_DataObject::factory('core_enum');
376             //$ce->initEnums();
377             
378             
379             $u = DB_DataObject::factory('Person');
380             $u->id = -1;
381             return $u;
382             
383         }
384         return false;
385     }     
386     function login()
387     {
388         $this->isAuth(); // force session start..
389         if (!$this->verifyAuth()) {
390             return false;
391         }
392         $db = $this->getDatabaseConnection();
393         
394         
395         // open up iptables at login..
396         $dbname = $this->database();
397         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
398          
399         // refresh admin group if we are logged in as one..
400         //DB_DataObject::debugLevel(1);
401         $g = DB_DataObject::factory('Groups');
402         $g->type = 0;
403         $g->get('name', 'Administrators');
404         $gm = DB_DataObject::Factory('group_members');
405         if (in_array($g->id,$gm->listGroupMembership($this))) {
406             // refresh admin groups.
407             $gr = DB_DataObject::Factory('group_rights');
408             $gr->applyDefs($g, 0);
409         }
410         $ff= HTML_FlexyFramework::get();
411         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
412
413
414         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
415         
416     }
417     function logout()
418     {
419         $this->isAuth(); // force session start..
420         $db = $this->getDatabaseConnection();
421         $ff= HTML_FlexyFramework::get();
422         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
423
424         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
425         
426     }    
427     function genPassKey ($t) 
428     {
429         return md5($this->email . $t. $this->passwd);
430     }
431     function simpleAuthKey($m = 0)
432     {
433         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
434         
435         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
436     } 
437     function checkPassword($val)
438     {
439         
440         if (substr($this->passwd,0,1) == '$') {
441             return crypt($val,$this->passwd) == $this->passwd ;
442         }
443         // old style md5 passwords...- cant be used with courier....
444         return md5($val) == $this->passwd;
445     }
446     function setPassword($value) 
447     {
448         $salt='';
449         while(strlen($salt)<9) {
450             $salt.=chr(rand(64,126));
451             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
452         }
453         $this->passwd = crypt($value, '$1$'. $salt. '$');
454        
455        
456     }      
457     
458     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
459     {
460         require_once 'Text/Password.php';
461         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
462         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
463         $this->setPassword($this->rawPasswd);
464         return $this->rawPasswd;
465     }
466     
467     function company()
468     {
469         $x = DB_DataObject::factory('Companies');
470         $x->autoJoin();
471         $x->get($this->company_id);
472         return $x;
473     }
474     function loadCompany()
475     {
476         $this->company = $this->company();
477     }
478     
479     function active()
480     { 
481         return $this->active;
482     }
483     function authUserName($n) // set username prior to acheck user exists query.
484     {
485         
486         $this->whereAdd('LENGTH(passwd) > 1'); 
487         $this->email = $n;
488     }
489     function lang()
490     {
491         if (!func_num_args()) {
492             return $this->lang;
493         }
494         $val = array_shift(func_get_args());
495         if ($val == $this->lang) {
496             return;
497         }
498         $uu = clone($this);
499         $this->lang = $val;
500         $this->update($uu);
501         return $this->lang;
502     }
503             
504     
505     function authUserArray()
506     {
507         
508         $aur = $this->toArray();
509         
510         if ($this->id < 1) {
511             return $aur;
512         }
513         
514         
515         //DB_DataObject::debugLevel(1);
516         $c = DB_Dataobject::factory('Companies');
517         $im = DB_Dataobject::factory('Images');
518         $c->joinAdd($im, 'LEFT');
519         $c->selectAdd();
520         $c->selectAs($c, 'company_id_%s');
521         $c->selectAs($im, 'company_id_logo_id_%s');
522         $c->id = $this->company_id;
523         $c->limit(1);
524         $c->find(true);
525         
526         $aur = array_merge( $c->toArray(),$aur);
527         
528         if (empty($c->company_id_logo_id_id))  {
529                  
530             $im = DB_Dataobject::factory('Images');
531             $im->ontable = 'Companies';
532             $im->onid = $c->id;
533             $im->imgtype = 'LOGO';
534             $im->limit(1);
535             $im->selectAdd();
536             $im->selectAs($im,  'company_id_logo_id_%s');
537             if ($im->find(true)) {
538                     
539                 foreach($im->toArray() as $k=>$v) {
540                     $aur[$k] = $v;
541                 }
542             }
543         }
544       
545         // perms + groups.
546         $aur['perms']  = $this->getPerms();
547         $g = DB_DataObject::Factory('group_members');
548         $aur['groups']  = $g->listGroupMembership($this, 'name');
549         
550         $aur['passwd'] = '';
551         $aur['dailykey'] = '';
552         
553         
554         
555         return $aur;
556     }
557     
558     //   ----------PERMS------  ----------------
559     function getPerms() 
560     {
561          //DB_DataObject::debugLevel(1);
562         // find out all the groups they are a member of.. + Default..
563         
564         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
565         
566         $g = DB_DataObject::Factory('group_rights');
567         if (!$g->count()) {
568             $g->genDefault();
569         }
570         
571         if ($this->id < 0) {
572             return $g->adminRights(); // system is not set up - so they get full rights.
573         }
574         //DB_DataObject::debugLevel(1);
575         $g = DB_DataObject::Factory('group_members');
576         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
577         if (!$g->count()) {
578             // add the current user to the admin group..
579             $g = DB_DataObject::Factory('Groups');
580             if ($g->get('name', 'Administrators')) {
581                 $gm = DB_DataObject::Factory('group_members');
582                 $gm->group_id = $g->id;
583                 $gm->user_id = $this->id;
584                 $gm->insert();
585             }
586             
587         }
588         
589         // ------ STANDARD PERMISSION HANDLING.
590         $isOwner = $this->company()->comptype == 'OWNER';
591         $g = DB_DataObject::Factory('group_members');
592         $grps = $g->listGroupMembership($this);
593        //var_dump($grps);
594         $isAdmin = $g->inAdmin;
595         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
596         // the load all the perms for those groups, and add them all together..
597         // then load all those 
598         $g = DB_DataObject::Factory('group_rights');
599         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
600         //echo '<PRE>';print_r($ret);
601         return $ret;
602          
603         
604     }
605     /**
606      *Basic group fetching - probably needs to filter by type eventually.
607      *
608      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
609      */
610     
611     function groups($what=false)
612     {
613         $g = DB_DataObject::Factory('group_members');
614         $grps = $g->listGroupMembership($this);
615         $g = DB_DataObject::Factory('Groups');
616         $g->whereAddIn('id', $grps, 'int');
617         return $g->fetchAll($what);
618         
619     }
620     
621     
622     
623     function hasPerm($name, $lvl) 
624     {
625         static $pcache = array();
626         
627         if (!isset($pcache[$this->id])) {
628             $pcache[$this->id] = $this->getPerms();
629         }
630        // echo "<PRE>";print_r($pcache[$au->id]);
631        // var_dump($pcache[$au->id]);
632         if (empty($pcache[$this->id][$name])) {
633             return false;
634         }
635         
636         return strpos($pcache[$this->id][$name], $lvl) > -1;
637         
638     }    
639     
640     //  ------------ROO HOOKS------------------------------------
641     function applyFilters($q, $au, $roo)
642     {
643         //DB_DataObject::DebugLevel(1);
644         if (!empty($q['query']['person_not_internal'])) {
645             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
646         }
647         
648         
649         if (!empty($q['query']['person_internal_only_all'])) {
650             
651             
652             // must be internal and not current user (need for distribution list)
653             // user has a projectdirectory entry and role is not blank.
654             //DB_DataObject::DebugLevel(1);
655             $pd = DB_DataObject::factory('ProjectDirectory');
656             $pd->whereAdd("role != ''");
657             $pd->selectAdd();
658             $pd->selectAdd('distinct(person_id) as person_id');
659             $roled = $pd->fetchAll('person_id');
660             $rs = $roled  ? "  OR
661                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
662                     " : '';
663             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
664             
665         }
666         // -- for distribution
667         if (!empty($q['query']['person_internal_only'])) {
668             // must be internal and not current user (need for distribution list)
669             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
670             
671             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
672             //    ".id  != ".$au->id);
673             $this->whereAdd("Person.id != {$au->id}");
674         } 
675         
676         if (!empty($q['query']['comptype_or_company_id'])) {
677            // DB_DataObject::debugLevel(1);
678             $bits = explode(',', $q['query']['comptype_or_company_id']);
679             $id = (int) array_pop($bits);
680             $ct = $this->escape($bits[0]);
681             
682             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
683             
684         }
685         
686         
687         // staff list..
688         if (!empty($q['query']['person_inactive'])) {
689            // DB_Dataobject::debugLevel(1);
690             $this->active = 1;
691         }
692         $tn_p = $this->tableName();
693         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
694         $tn_g = DB_DataObject::Factory('Groups')->tableName();
695
696         ///---------------- Group views --------
697         if (!empty($q['query']['in_group'])) {
698             // DB_DataObject::debugLevel(1);
699             $ing = (int) $q['query']['in_group'];
700             if ($q['query']['in_group'] == -1) {
701              
702                 // list all staff who are not in a group.
703                 $this->whereAdd("Person.id NOT IN (
704                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
705                         $tn_g ON $tn_g.id = $tn_gm.group_id
706                         WHERE $tn_g.type = ".$q['query']['type']."
707                     )");
708                 
709                 
710             } else {
711                 
712                 $this->whereAdd("$tn_p.id IN (
713                     SELECT distinct(user_id) FROM $tn_gm
714                         WHERE group_id = $ing
715                     )");
716                }
717             
718         }
719         
720         if (!empty($q['query']['not_in_directory'])) { 
721             // it's a Person list..
722             // DB_DATaobjecT::debugLevel(1);
723             
724             // specific to project directory which is single comp. login
725             //
726             $owncomp = DB_DataObject::Factory('Companies');
727             $owncomp->get('comptype', 'OWNER');
728             if ($q['company_id'] == $owncomp->id) {
729                 $this->active =1;
730             }
731             
732             
733
734             if ( $q['query']['not_in_directory'] > -1) {
735                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
736                 // can list current - so that it does not break!!!
737                 $this->whereAdd("$tn_p.id NOT IN 
738                     ( SELECT distinct person_id FROM $tn_pd WHERE
739                         project_id = " . $q['query']['not_in_directory'] . " AND 
740                         company_id = " . $this->company_id . ')');
741             }
742         }
743            
744         if (!empty($q['query']['role'])) { 
745             // it's a Person list..
746             // DB_DATaobjecT::debugLevel(1);
747             
748             // specific to project directory which is single comp. login
749             //
750             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
751                 // can list current - so that it does not break!!!
752             $this->whereAdd("$tn_p.id IN 
753                     ( SELECT distinct person_id FROM $tn_pd WHERE
754                         role = '". $this->escape($q['query']['role']) ."'
755             )");
756         
757         }
758         
759         
760         if (!empty($q['query']['project_member_of'])) {
761                // this is also a flag to return if they are a member..
762             //DB_DataObject::debugLevel(1);
763             $do = DB_DataObject::factory('ProjectDirectory');
764             $do->project_id = $q['query']['project_member_of'];
765             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
766             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
767             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
768                 
769                 
770             if (!empty($q['query']['project_member_filter'])) {
771                 $this->having('is_member !=0');
772             
773             }
774             
775         }
776         
777         if (!empty($q['query']['search'])) {
778             
779             // use our magic search builder...
780             
781              require_once 'Text/SearchParser.php';
782             $x = new Text_SearchParser($q['query']['search']);
783             
784             $props = array(
785                     "$tn_p.name",
786                     "$tn_p.email",
787                     "$tn_p.role",
788                     "$tn_p.phone",
789                     "$tn_p.remarks",
790                     "join_company_id_id.name"
791             );
792             
793             $str =  $x->toSQL(array(
794                 'default' => $props,
795                 'map' => array(
796                     'company' => 'join_company_id_id.name',
797                     //'country' => 'Clipping.country',
798                     //  'media' => 'Clipping.media_name',
799                 ),
800                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
801
802             ));
803             
804             
805             $this->whereAdd($str); /*
806                         $tn_p.name LIKE '%$s%'  OR
807                         $tn_p.email LIKE '%$s%'  OR
808                         $tn_p.role LIKE '%$s%'  OR
809                         $tn_p.phone LIKE '%$s%' OR
810                         $tn_p.remarks LIKE '%$s%' 
811                         
812                     ");*/
813         }
814         
815         //
816     }
817     function setFromRoo($ar, $roo)
818     {
819         $this->setFrom($ar);
820         if (!empty($ar['passwd1'])) {
821             $this->setPassword($ar['passwd1']);
822         }
823         
824         
825         if (    $this->id &&
826                 ($this->email == $roo->old->email)&&
827                 ($this->company_id == $roo->old->company_id)
828             ) {
829             return true;
830         }
831         if (empty($this->email)) {
832             return true;
833         }
834         $xx = DB_Dataobject::factory('Person');
835         $xx->setFrom(array(
836             'email' => $this->email,
837            // 'company_id' => $x->company_id
838         ));
839         
840         if ($xx->count()) {
841             return "Duplicate Email found";
842         }
843         return true;
844     }
845     /**
846      *
847      * before Delete - delete significant dependancies..
848      * this is called after checkPerm..
849      */
850     
851     function beforeDelete()
852     {
853         
854         $e = DB_DataObject::Factory('Events');
855         $e->whereAdd('person_id = ' . $this->id);
856         $e->delete(true);
857         
858         // anything else?  
859         
860     }
861     
862     
863     /***
864      * Check if the a user has access to modify this item.
865      * @param String $lvl Level (eg. Core.Projects)
866      * @param Pman_Core_DataObjects_Person $au The authenticated user.
867      * @param boolean $changes alllow changes???
868      *
869      * @return false if no access..
870      */
871     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
872     {
873          
874        // do we have an empty system..
875         if ($au && $au->id == -1) {
876             return true;
877         }
878         
879         // determine if it's staff!!!
880          
881         if ($au->company()->comptype != 'OWNER') {
882             
883             // - can not change company!!!
884             if ($changes && 
885                 isset($changes['company_id']) && 
886                 $changes['company_id'] != $au->company_id) {
887                 return false;
888             }
889             // can only set new emails..
890             if ($changes && 
891                     !empty($this->email) && 
892                     isset($changes['email']) && 
893                     $changes['email'] != $this->email) {
894                 return false;
895             }
896             
897             // edit self... - what about other staff members...
898             
899             return $this->company_id == $au->company_id;
900         }
901          
902          
903         // yes, only owner company can mess with this...
904         $owncomp = DB_DataObject::Factory('Companies');
905         $owncomp->get('comptype', 'OWNER');
906         
907         $isStaff = ($this->company_id ==  $owncomp->id);
908         
909     
910         switch ($lvl) {
911             // extra case change passwod?
912             case 'P': //??? password
913                 // standard perms -- for editing + if the user is dowing them selves..
914                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
915                 return $ret || $au->id == $this->id;
916             
917             default:                
918                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
919         
920         }
921         return false;
922     }
923     function onInsert($req, $roo)  
924     {
925          
926         $p = DB_DataObject::factory('person');
927         if ($roo->authUser->id < 0 && $p->count() == 1) {
928             // this seems a bit risky...
929             
930             $g = DB_DataObject::factory('Groups');
931             $g->initGroups();
932             
933             $g->type = 0;
934             $g->get('name', 'Administrators');
935             
936             $p = DB_DataObject::factory('group_members');
937             $p->group_id = $g->id;
938             $p->user_id = $this->id;     
939             if (!$p->count()) {
940                 $p->insert();
941                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
942             }
943             $this->login();
944         }
945         if (!empty($req['project_id_addto'])) {
946             $pd = DB_DataObject::factory('ProjectDirectory');
947             $pd->project_id = $req['project_id_addto'];
948             $pd->person_id = $this->id; 
949             $pd->ispm =0;
950             $pd->office_id = $this->office_id;
951             $pd->company_id = $this->company_id;
952             $pd->insert();
953         }
954         
955     }
956     
957     function importFromArray($roo, $persons, $opts)
958     {
959         if (empty($opts['prefix'])) {
960             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
961         }
962         
963         if (!is_array($persons) || empty($persons)) {
964             $roo->jerr("error in the person data. - empty on not valid");
965         }
966         DB_DataObject::factory('groups')->initGroups();
967         
968         foreach($persons as $person){
969             $p = DB_DataObject::factory('person');
970             if($p->get('name', $person['name'])){
971                 continue;
972             }
973             $p->setFrom($person);
974             
975             $companies = DB_DataObject::factory('companies');
976             if(!$companies->get('comptype', 'OWNER')){
977                 $roo->jerr("Missing OWNER companies!");
978             }
979             $p->company_id = $companies->pid();
980             // strip the 'spaces etc.. make lowercase..
981             $name = strtolower(str_replace(' ', '', $person['name']));
982             $p->setPassword("{$opts['prefix']}{$name}");
983             $p->insert();
984             // set up groups
985             // if $person->groups is set.. then
986             // add this person to that group eg. groups : [ 'Administrator' ] 
987             if(!empty($person['groups'])){
988                 $groups = DB_DataObject::factory('groups');
989                 if(!$groups->get('name', $person['groups'])){
990                     $roo->jerr("Missing groups : {$person['groups']}");
991                 }
992                 $gm = DB_DataObject::factory('group_members');
993                 $gm->change($p, $groups, true);
994             }
995             
996             $p->onInsert(array(), $roo);
997         }
998     }
999  }