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