2b3f323643905f38f50ae3f686c527d0069880e2
[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             unset($_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          
297         $u = DB_DataObject::factory('Person');
298         $ff = HTML_FlexyFramework::get();
299         if (!empty($ff->Pman['local_autoauth']) && 
300             (!empty($_SERVER['SERVER_ADDR'])) &&
301             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
302             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
303             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
304         ) {
305             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($default_admin ? $default_admin : $u);
306             return true;
307         }
308            
309         // http basic auth..
310         $u = DB_DataObject::factory('Person');
311
312         if (!empty($_SERVER['PHP_AUTH_USER']) 
313             &&
314             !empty($_SERVER['PHP_AUTH_PW'])
315             &&
316             $u->get('email', $_SERVER['PHP_AUTH_USER'])
317             &&
318             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
319            ) {
320             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
321             return true; 
322         }
323         
324         if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
325             return false;
326         }
327         
328         // not in session or not matched...
329         $u = DB_DataObject::factory('Person');
330         $u->whereAdd(' LENGTH(passwd) > 0');
331         $n = $u->count();
332         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
333         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
334         if ($error) {
335             die($error->toString()); // not really a good thing to do...
336         }
337         if (!$n){ // authenticated as there are no users in the system...
338             return true;
339         }
340         
341         return false;
342         
343     }
344     function getAuthUser()
345     {
346         if (!$this->isAuth()) {
347             return false;
348         }
349         $db = $this->getDatabaseConnection();
350         
351         $ff= HTML_FlexyFramework::get();
352         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
353
354         
355         
356         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
357             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
358             
359             $u = DB_DataObject::factory('Person');
360             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
361                 return clone($u);
362             }
363             unset($_SESSION[__CLASS__][$sesPrefix .'-auth']);
364         }
365         
366         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
367             $u = DB_DataObject::factory('Person');
368             $u->whereAdd(' LENGTH(passwd) > 0');
369             $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
370         }
371                 
372              
373         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
374             
375             // fake person - open system..
376             //$ce = DB_DataObject::factory('core_enum');
377             //$ce->initEnums();
378             
379             
380             $u = DB_DataObject::factory('Person');
381             $u->id = -1;
382             
383             // if a company has been created fill that in in company_id_id
384             $c = DB_DAtaObject::factory('Companies')->lookupOwner();
385             if ($c) {
386                 $u->company_id_id = $c->pid();
387                 $u->company_id = $c->pid();
388             }
389             
390             return $u;
391             
392         }
393         return false;
394     }     
395     function login()
396     {
397         $this->isAuth(); // force session start..
398         if (!$this->verifyAuth()) {
399             return false;
400         }
401         $db = $this->getDatabaseConnection();
402         
403         
404         // open up iptables at login..
405         $dbname = $this->database();
406         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
407          
408         // refresh admin group if we are logged in as one..
409         //DB_DataObject::debugLevel(1);
410         $g = DB_DataObject::factory('Groups');
411         $g->type = 0;
412         $g->get('name', 'Administrators');
413         $gm = DB_DataObject::Factory('group_members');
414         if (in_array($g->id,$gm->listGroupMembership($this))) {
415             // refresh admin groups.
416             $gr = DB_DataObject::Factory('group_rights');
417             $gr->applyDefs($g, 0);
418         }
419         $ff= HTML_FlexyFramework::get();
420         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
421
422
423         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
424         
425     }
426     function logout()
427     {
428         $this->isAuth(); // force session start..
429         $db = $this->getDatabaseConnection();
430         $ff= HTML_FlexyFramework::get();
431         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
432
433         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
434         $_SESSION[__CLASS__][$sesPrefix .'-empty'] = "";
435         
436     }    
437     function genPassKey ($t) 
438     {
439         return md5($this->email . $t. $this->passwd);
440     }
441     function simpleAuthKey($m = 0)
442     {
443         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
444         
445         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
446     } 
447     function checkPassword($val)
448     {
449         
450         if (substr($this->passwd,0,1) == '$') {
451             return crypt($val,$this->passwd) == $this->passwd ;
452         }
453         // old style md5 passwords...- cant be used with courier....
454         return md5($val) == $this->passwd;
455     }
456     function setPassword($value) 
457     {
458         $salt='';
459         while(strlen($salt)<9) {
460             $salt.=chr(rand(64,126));
461             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
462         }
463         $this->passwd = crypt($value, '$1$'. $salt. '$');
464        
465        
466     }      
467     
468     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
469     {
470         require_once 'Text/Password.php';
471         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
472         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
473         $this->setPassword($this->rawPasswd);
474         return $this->rawPasswd;
475     }
476     
477     function company()
478     {
479         $x = DB_DataObject::factory('Companies');
480         $x->autoJoin();
481         $x->get($this->company_id);
482         return $x;
483     }
484     function loadCompany()
485     {
486         $this->company = $this->company();
487     }
488     
489     function active()
490     { 
491         return $this->active;
492     }
493     function authUserName($n) // set username prior to acheck user exists query.
494     {
495         
496         $this->whereAdd('LENGTH(passwd) > 1'); 
497         $this->email = $n;
498     }
499     function lang()
500     {
501         if (!func_num_args()) {
502             return $this->lang;
503         }
504         $val = array_shift(func_get_args());
505         if ($val == $this->lang) {
506             return;
507         }
508         $uu = clone($this);
509         $this->lang = $val;
510         $this->update($uu);
511         return $this->lang;
512     }
513             
514     
515     function authUserArray()
516     {
517         
518         $aur = $this->toArray();
519         
520         if ($this->id < 1) {
521             return $aur;
522         }
523         
524         
525         //DB_DataObject::debugLevel(1);
526         $c = DB_Dataobject::factory('Companies');
527         $im = DB_Dataobject::factory('Images');
528         $c->joinAdd($im, 'LEFT');
529         $c->selectAdd();
530         $c->selectAs($c, 'company_id_%s');
531         $c->selectAs($im, 'company_id_logo_id_%s');
532         $c->id = $this->company_id;
533         $c->limit(1);
534         $c->find(true);
535         
536         $aur = array_merge( $c->toArray(),$aur);
537         
538         if (empty($c->company_id_logo_id_id))  {
539                  
540             $im = DB_Dataobject::factory('Images');
541             $im->ontable = 'Companies';
542             $im->onid = $c->id;
543             $im->imgtype = 'LOGO';
544             $im->limit(1);
545             $im->selectAdd();
546             $im->selectAs($im,  'company_id_logo_id_%s');
547             if ($im->find(true)) {
548                     
549                 foreach($im->toArray() as $k=>$v) {
550                     $aur[$k] = $v;
551                 }
552             }
553         }
554       
555         // perms + groups.
556         $aur['perms']  = $this->getPerms();
557         $g = DB_DataObject::Factory('group_members');
558         $aur['groups']  = $g->listGroupMembership($this, 'name');
559         
560         $aur['passwd'] = '';
561         $aur['dailykey'] = '';
562         
563         
564         
565         return $aur;
566     }
567     
568     //   ----------PERMS------  ----------------
569     function getPerms() 
570     {
571          //DB_DataObject::debugLevel(1);
572         // find out all the groups they are a member of.. + Default..
573         
574         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
575         
576         $g = DB_DataObject::Factory('group_rights');
577         if (!$g->count()) {
578             $g->genDefault();
579         }
580         
581         if ($this->id < 0) {
582             return $g->adminRights(); // system is not set up - so they get full rights.
583         }
584         //DB_DataObject::debugLevel(1);
585         $g = DB_DataObject::Factory('group_members');
586         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
587         if (!$g->count()) {
588             // add the current user to the admin group..
589             $g = DB_DataObject::Factory('Groups');
590             if ($g->get('name', 'Administrators')) {
591                 $gm = DB_DataObject::Factory('group_members');
592                 $gm->group_id = $g->id;
593                 $gm->user_id = $this->id;
594                 $gm->insert();
595             }
596             
597         }
598         
599         // ------ STANDARD PERMISSION HANDLING.
600         $isOwner = $this->company()->comptype == 'OWNER';
601         $g = DB_DataObject::Factory('group_members');
602         $grps = $g->listGroupMembership($this);
603        //var_dump($grps);
604         $isAdmin = $g->inAdmin;
605         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
606         // the load all the perms for those groups, and add them all together..
607         // then load all those 
608         $g = DB_DataObject::Factory('group_rights');
609         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
610         //echo '<PRE>';print_r($ret);
611         return $ret;
612          
613         
614     }
615     /**
616      *Basic group fetching - probably needs to filter by type eventually.
617      *
618      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
619      */
620     
621     function groups($what=false)
622     {
623         $g = DB_DataObject::Factory('group_members');
624         $grps = $g->listGroupMembership($this);
625         $g = DB_DataObject::Factory('Groups');
626         $g->whereAddIn('id', $grps, 'int');
627         return $g->fetchAll($what);
628         
629     }
630     
631     
632     
633     function hasPerm($name, $lvl) 
634     {
635         static $pcache = array();
636         
637         if (!isset($pcache[$this->id])) {
638             $pcache[$this->id] = $this->getPerms();
639         }
640        // echo "<PRE>";print_r($pcache[$au->id]);
641        // var_dump($pcache[$au->id]);
642         if (empty($pcache[$this->id][$name])) {
643             return false;
644         }
645         
646         return strpos($pcache[$this->id][$name], $lvl) > -1;
647         
648     }    
649     
650     //  ------------ROO HOOKS------------------------------------
651     function applyFilters($q, $au, $roo)
652     {
653         //DB_DataObject::DebugLevel(1);
654         if (!empty($q['query']['person_not_internal'])) {
655             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
656         }
657         
658         
659         if (!empty($q['query']['person_internal_only_all'])) {
660             
661             
662             // must be internal and not current user (need for distribution list)
663             // user has a projectdirectory entry and role is not blank.
664             //DB_DataObject::DebugLevel(1);
665             $pd = DB_DataObject::factory('ProjectDirectory');
666             $pd->whereAdd("role != ''");
667             $pd->selectAdd();
668             $pd->selectAdd('distinct(person_id) as person_id');
669             $roled = $pd->fetchAll('person_id');
670             $rs = $roled  ? "  OR
671                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
672                     " : '';
673             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
674             
675         }
676         // -- for distribution
677         if (!empty($q['query']['person_internal_only'])) {
678             // must be internal and not current user (need for distribution list)
679             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
680             
681             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
682             //    ".id  != ".$au->id);
683             $this->whereAdd("Person.id != {$au->id}");
684         } 
685         
686         if (!empty($q['query']['comptype_or_company_id'])) {
687            // DB_DataObject::debugLevel(1);
688             $bits = explode(',', $q['query']['comptype_or_company_id']);
689             $id = (int) array_pop($bits);
690             $ct = $this->escape($bits[0]);
691             
692             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
693             
694         }
695         
696         
697         // staff list..
698         if (!empty($q['query']['person_inactive'])) {
699            // DB_Dataobject::debugLevel(1);
700             $this->active = 1;
701         }
702         $tn_p = $this->tableName();
703         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
704         $tn_g = DB_DataObject::Factory('Groups')->tableName();
705
706         ///---------------- Group views --------
707         if (!empty($q['query']['in_group'])) {
708             // DB_DataObject::debugLevel(1);
709             $ing = (int) $q['query']['in_group'];
710             if ($q['query']['in_group'] == -1) {
711              
712                 // list all staff who are not in a group.
713                 $this->whereAdd("Person.id NOT IN (
714                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
715                         $tn_g ON $tn_g.id = $tn_gm.group_id
716                         WHERE $tn_g.type = ".$q['query']['type']."
717                     )");
718                 
719                 
720             } else {
721                 
722                 $this->whereAdd("$tn_p.id IN (
723                     SELECT distinct(user_id) FROM $tn_gm
724                         WHERE group_id = $ing
725                     )");
726                }
727             
728         }
729         
730         if (!empty($q['query']['not_in_directory'])) { 
731             // it's a Person list..
732             // DB_DATaobjecT::debugLevel(1);
733             
734             // specific to project directory which is single comp. login
735             //
736             $owncomp = DB_DataObject::Factory('Companies');
737             $owncomp->get('comptype', 'OWNER');
738             if ($q['company_id'] == $owncomp->id) {
739                 $this->active =1;
740             }
741             
742             
743
744             if ( $q['query']['not_in_directory'] > -1) {
745                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
746                 // can list current - so that it does not break!!!
747                 $this->whereAdd("$tn_p.id NOT IN 
748                     ( SELECT distinct person_id FROM $tn_pd WHERE
749                         project_id = " . $q['query']['not_in_directory'] . " AND 
750                         company_id = " . $this->company_id . ')');
751             }
752         }
753            
754         if (!empty($q['query']['role'])) { 
755             // it's a Person list..
756             // DB_DATaobjecT::debugLevel(1);
757             
758             // specific to project directory which is single comp. login
759             //
760             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
761                 // can list current - so that it does not break!!!
762             $this->whereAdd("$tn_p.id IN 
763                     ( SELECT distinct person_id FROM $tn_pd WHERE
764                         role = '". $this->escape($q['query']['role']) ."'
765             )");
766         
767         }
768         
769         
770         if (!empty($q['query']['project_member_of'])) {
771                // this is also a flag to return if they are a member..
772             //DB_DataObject::debugLevel(1);
773             $do = DB_DataObject::factory('ProjectDirectory');
774             $do->project_id = $q['query']['project_member_of'];
775             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
776             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
777             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
778                 
779                 
780             if (!empty($q['query']['project_member_filter'])) {
781                 $this->having('is_member !=0');
782             
783             }
784             
785         }
786         
787         if (!empty($q['query']['search'])) {
788             
789             // use our magic search builder...
790             
791              require_once 'Text/SearchParser.php';
792             $x = new Text_SearchParser($q['query']['search']);
793             
794             $props = array(
795                     "$tn_p.name",
796                     "$tn_p.email",
797                     "$tn_p.role",
798                     "$tn_p.phone",
799                     "$tn_p.remarks",
800                     "join_company_id_id.name"
801             );
802             
803             $str =  $x->toSQL(array(
804                 'default' => $props,
805                 'map' => array(
806                     'company' => 'join_company_id_id.name',
807                     //'country' => 'Clipping.country',
808                     //  'media' => 'Clipping.media_name',
809                 ),
810                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
811
812             ));
813             
814             
815             $this->whereAdd($str); /*
816                         $tn_p.name LIKE '%$s%'  OR
817                         $tn_p.email LIKE '%$s%'  OR
818                         $tn_p.role LIKE '%$s%'  OR
819                         $tn_p.phone LIKE '%$s%' OR
820                         $tn_p.remarks LIKE '%$s%' 
821                         
822                     ");*/
823         }
824         
825         //
826     }
827     function setFromRoo($ar, $roo)
828     {
829         $this->setFrom($ar);
830         if (!empty($ar['passwd1'])) {
831             $this->setPassword($ar['passwd1']);
832         }
833         
834         
835         if (    $this->id &&
836                 ($this->email == $roo->old->email)&&
837                 ($this->company_id == $roo->old->company_id)
838             ) {
839             return true;
840         }
841         if (empty($this->email)) {
842             return true;
843         }
844         $xx = DB_Dataobject::factory('Person');
845         $xx->setFrom(array(
846             'email' => $this->email,
847            // 'company_id' => $x->company_id
848         ));
849         
850         if ($xx->count()) {
851             return "Duplicate Email found";
852         }
853         return true;
854     }
855     /**
856      *
857      * before Delete - delete significant dependancies..
858      * this is called after checkPerm..
859      */
860     
861     function beforeDelete()
862     {
863         
864         $e = DB_DataObject::Factory('Events');
865         $e->whereAdd('person_id = ' . $this->id);
866         $e->delete(true);
867         
868         // anything else?  
869         
870     }
871     
872     
873     /***
874      * Check if the a user has access to modify this item.
875      * @param String $lvl Level (eg. Core.Projects)
876      * @param Pman_Core_DataObjects_Person $au The authenticated user.
877      * @param boolean $changes alllow changes???
878      *
879      * @return false if no access..
880      */
881     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
882     {
883          
884        // do we have an empty system..
885         if ($au && $au->id == -1) {
886             return true;
887         }
888         
889         // determine if it's staff!!!
890          
891         if ($au->company()->comptype != 'OWNER') {
892             
893             // - can not change company!!!
894             if ($changes && 
895                 isset($changes['company_id']) && 
896                 $changes['company_id'] != $au->company_id) {
897                 return false;
898             }
899             // can only set new emails..
900             if ($changes && 
901                     !empty($this->email) && 
902                     isset($changes['email']) && 
903                     $changes['email'] != $this->email) {
904                 return false;
905             }
906             
907             // edit self... - what about other staff members...
908             
909             return $this->company_id == $au->company_id;
910         }
911          
912          
913         // yes, only owner company can mess with this...
914         $owncomp = DB_DataObject::Factory('Companies');
915         $owncomp->get('comptype', 'OWNER');
916         
917         $isStaff = ($this->company_id ==  $owncomp->id);
918         
919     
920         switch ($lvl) {
921             // extra case change passwod?
922             case 'P': //??? password
923                 // standard perms -- for editing + if the user is dowing them selves..
924                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
925                 return $ret || $au->id == $this->id;
926             
927             default:                
928                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
929         
930         }
931         return false;
932     }
933     function onInsert($req, $roo)  
934     {
935          
936         $p = DB_DataObject::factory('person');
937         if ($roo->authUser->id < 0 && $p->count() == 1) {
938             // this seems a bit risky...
939             
940             $g = DB_DataObject::factory('Groups');
941             $g->initGroups();
942             
943             $g->type = 0;
944             $g->get('name', 'Administrators');
945             
946             $p = DB_DataObject::factory('group_members');
947             $p->group_id = $g->id;
948             $p->user_id = $this->id;     
949             if (!$p->count()) {
950                 $p->insert();
951                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
952             }
953             $this->login();
954         }
955         if (!empty($req['project_id_addto'])) {
956             $pd = DB_DataObject::factory('ProjectDirectory');
957             $pd->project_id = $req['project_id_addto'];
958             $pd->person_id = $this->id; 
959             $pd->ispm =0;
960             $pd->office_id = $this->office_id;
961             $pd->company_id = $this->company_id;
962             $pd->insert();
963         }
964         
965     }
966     
967     function importFromArray($roo, $persons, $opts)
968     {
969         if (empty($opts['prefix'])) {
970             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
971         }
972         
973         if (!is_array($persons) || empty($persons)) {
974             $roo->jerr("error in the person data. - empty on not valid");
975         }
976         DB_DataObject::factory('groups')->initGroups();
977         
978         foreach($persons as $person){
979             $p = DB_DataObject::factory('person');
980             if($p->get('name', $person['name'])){
981                 continue;
982             }
983             $p->setFrom($person);
984             
985             $companies = DB_DataObject::factory('companies');
986             if(!$companies->get('comptype', 'OWNER')){
987                 $roo->jerr("Missing OWNER companies!");
988             }
989             $p->company_id = $companies->pid();
990             // strip the 'spaces etc.. make lowercase..
991             $name = strtolower(str_replace(' ', '', $person['name']));
992             $p->setPassword("{$opts['prefix']}{$name}");
993             $p->insert();
994             // set up groups
995             // if $person->groups is set.. then
996             // add this person to that group eg. groups : [ 'Administrator' ] 
997             if(!empty($person['groups'])){
998                 $groups = DB_DataObject::factory('groups');
999                 if(!$groups->get('name', $person['groups'])){
1000                     $roo->jerr("Missing groups : {$person['groups']}");
1001                 }
1002                 $gm = DB_DataObject::factory('group_members');
1003                 $gm->change($p, $groups, true);
1004             }
1005             
1006             $p->onInsert(array(), $roo);
1007         }
1008     }
1009  }