3 * Table Definition for Person
5 require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Person extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Person'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $email; // string(128) not_null
16 public $company_id; // int(11)
17 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
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)
35 public $active; // int(11) not_null
36 public $deleted_by; // int(11) not_null
37 public $deleted_dt; // datetime(19) binary
40 /* the code above is auto generated do not remove the tag below */
44 * @param {String} $templateFile (mail/XXXXXXX.txt) exclude the mail and .txt bit.
45 * @param {Array|Object} $args data to send out..
46 * @return {Array|PEAR_Error} array of $recipents, $header, $body
48 function buildMail($templateFile, $args)
51 $args = (array) $args;
52 $content = clone($this);
54 foreach((array)$args as $k=>$v) {
58 $ff = HTML_FlexyFramework::get();
61 //?? is this really the place for this???
64 empty($args['no_auth']) &&
65 !in_array($templateFile, array(
66 // templates that can be sent without authentication.
72 $content->authUser = $this->getAuthUser();
73 if (!$content->authUser) {
74 return PEAR::raiseError("Not authenticated");
78 // should handle x-forwarded...
80 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
81 $_SERVER["HTTP_HOST"] :
82 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
84 /* use the regex compiler, as it doesnt parse <tags */
87 'compiler' => 'Flexy',
89 'filters' => array('SimpleTags','Mail'),
95 if (!empty($args['templateDir'])) {
96 $tops['templateDir'] = $args['templateDir'];
101 require_once 'HTML/Template/Flexy.php';
102 $template = new HTML_Template_Flexy( $tops );
103 $template->compile("mail/$templateFile.txt");
105 /* use variables from this object to ouput data. */
106 $mailtext = $template->bufferedOutputObject($content);
109 // if a html file with the same name exists, use that as the body
110 // I've no idea where this code went, it was here before..
111 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
112 $tops['nonHTML'] = false;
113 $template = new HTML_Template_Flexy( $tops );
114 $template->compile("mail/$templateFile.html");
115 $htmlbody = $template->bufferedOutputObject($content);
121 //echo "<PRE>";print_R($mailtext);
122 //print_R($mailtext);exit;
123 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
124 require_once 'Mail/mimeDecode.php';
125 require_once 'Mail.php';
127 $decoder = new Mail_mimeDecode($mailtext);
128 $parts = $decoder->getSendArray();
130 if (PEAR::isError($parts)) {
132 //echo "PROBLEM: {$parts->message}";
135 list($recipents,$headers,$body) = $parts;
136 $recipents = array($this->email);
137 if (!empty($content->bcc) && is_array($content->bcc)) {
138 $recipents =array_merge($recipents, $content->bcc);
140 $headers['Date'] = date('r');
143 if ($htmlbody !== false) {
144 $mime = new Mail_mime(array('eol' => "\n"));
145 $mime->setHeaders($headers);
146 $mime->setTXTBody($body);
147 $mime->setHTMLBody($htmlbody);
148 // I think there might be code in mediaoutreach toEmail somewhere
149 // h embeds images here..
150 $body = $mime->get();
151 $headers = $mime->headers($hdrs);
158 'recipients' => $recipents,
159 'headers' => $headers,
169 * - user must be authenticate or args[no_auth] = true
170 * or template = password_[reset|welcome]
173 function sendTemplate($templateFile, $args)
176 $ar = $this->buildMail($templateFile, $args);
179 //print_r($recipents);exit;
180 $mailOptions = PEAR::getStaticProperty('Mail','options');
181 $mail = Mail::factory("SMTP",$mailOptions);
183 if (PEAR::isError($mail)) {
186 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
187 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
188 error_reporting($oe);
197 function getEmailFrom()
199 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
201 function toEventString()
203 return empty($this->name) ? $this->email : $this->name;
205 function verifyAuth()
207 $ff= HTML_FlexyFramework::get();
208 if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
209 $ff->page->jerr("Login not permited to outside companies");
216 // ---------------- authentication / passwords and keys stuff ----------------
219 $db = $this->getDatabaseConnection();
220 // we combine db + project names,
221 // otherwise if projects use different 'auth' objects
222 // then we get unserialize issues.
223 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
227 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
229 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
231 $u = DB_DataObject::factory('Person');
232 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
238 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
242 $u = DB_DataObject::factory('Person');
243 $ff = HTML_FlexyFramework::get();
244 if (!empty($ff->Pman['local_autoauth']) &&
245 (!empty($_SERVER['SERVER_ADDR'])) &&
246 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
247 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
248 $u->get('email', $ff->Pman['local_autoauth'])
250 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
255 $u = DB_DataObject::factory('Person');
257 if (!empty($_SERVER['PHP_AUTH_USER'])
259 !empty($_SERVER['PHP_AUTH_PW'])
261 $u->get('email', $_SERVER['PHP_AUTH_USER'])
263 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
265 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
272 // not in session or not matched...
273 $u = DB_DataObject::factory('Person');
274 $u->whereAdd(' LENGTH(passwd) > 0');
276 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
278 die($error->toString()); // not really a good thing to do...
280 if (!$n){ // authenticated as there are no users in the system...
287 function getAuthUser()
289 if (!$this->isAuth()) {
292 $db = $this->getDatabaseConnection();
293 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
295 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
296 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
298 $u = DB_DataObject::factory('Person');
299 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
305 $u = DB_DataObject::factory('Person');
306 $u->whereAdd(' LENGTH(passwd) > 0');
308 $u = DB_DataObject::factory('Person');
317 $this->isAuth(); // force session start..
319 $db = $this->getDatabaseConnection();
320 // refresh admin group if we are logged in as one..
321 //DB_DataObject::debugLevel(1);
322 $g = DB_DataObject::factory('Groups');
324 $g->get('name', 'Administrators');
325 $gm = DB_DataObject::Factory('group_members');
326 if (in_array($g->id,$gm->listGroupMembership($this))) {
327 // refresh admin groups.
328 $gr = DB_DataObject::Factory('group_rights');
329 $gr->applyDefs($g, 0);
332 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
333 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
338 $this->isAuth(); // force session start..
339 $db = $this->getDatabaseConnection();
340 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
341 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
344 function genPassKey ($t)
346 return md5($this->email . $t. $this->passwd);
348 function simpleAuthKey($m = 0)
350 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
352 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
354 function checkPassword($val)
357 if (substr($this->passwd,0,1) == '$') {
358 return crypt($val,$this->passwd) == $this->passwd ;
360 // old style md5 passwords...- cant be used with courier....
361 return md5($val) == $this->passwd;
363 function setPassword($value)
366 while(strlen($salt)<9) {
367 $salt.=chr(rand(64,126));
368 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
370 $this->passwd = crypt($value, '$1$'. $salt. '$');
377 $x = DB_DataObject::factory('Companies');
378 $x->get($this->company_id);
381 function loadCompany()
383 $this->company = $this->company();
388 return $this->active;
390 function authUserName($n) // set username prior to acheck user exists query.
393 $this->whereAdd('LENGTH(passwd) > 1');
398 if ($val == $this->lang) {
408 function authUserArray()
411 $aur = $this->toArray();
418 //DB_DataObject::debugLevel(1);
419 $c = DB_Dataobject::factory('Companies');
420 $im = DB_Dataobject::factory('Images');
421 $c->joinAdd($im, 'LEFT');
423 $c->selectAs($c, 'company_id_%s');
424 $c->selectAs($im, 'company_id_logo_id_%s');
425 $c->id = $this->company_id;
429 $aur = array_merge( $c->toArray(),$aur);
431 if (empty($c->company_id_logo_id_id)) {
433 $im = DB_Dataobject::factory('Images');
434 $im->ontable = 'Companies';
436 $im->imgtype = 'LOGO';
439 $im->selectAs($im, 'company_id_logo_id_%s');
440 if ($im->find(true)) {
442 foreach($im->toArray() as $k=>$v) {
449 $aur['perms'] = $this->getPerms();
450 $g = DB_DataObject::Factory('group_members');
451 $aur['groups'] = $g->listGroupMembership($this, 'name');
454 $aur['dailykey'] = '';
461 // ----------PERMS------ ----------------
464 //DB_DataObject::debugLevel(1);
465 // find out all the groups they are a member of.. + Default..
467 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
469 $g = DB_DataObject::Factory('group_rights');
475 return $g->adminRights(); // system is not set up - so they get full rights.
477 //DB_DataObject::debugLevel(1);
478 $g = DB_DataObject::Factory('group_members');
479 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
481 // add the current user to the admin group..
482 $g = DB_DataObject::Factory('Groups');
483 if ($g->get('name', 'Administrators')) {
484 $gm = DB_DataObject::Factory('group_members');
485 $gm->group_id = $g->id;
486 $gm->user_id = $this->id;
492 // ------ STANDARD PERMISSION HANDLING.
493 $isOwner = $this->company()->comptype == 'OWNER';
494 $g = DB_DataObject::Factory('group_members');
495 $grps = $g->listGroupMembership($this);
497 $isAdmin = $g->inAdmin;
498 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
499 // the load all the perms for those groups, and add them all together..
500 // then load all those
501 $g = DB_DataObject::Factory('group_rights');
502 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
503 //echo '<PRE>';print_r($ret);
509 *Basic group fetching - probably needs to filter by type eventually.
511 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
514 function groups($what=false)
516 $g = DB_DataObject::Factory('group_members');
517 $grps = $g->listGroupMembership($this);
518 $g = DB_DataObject::Factory('Groups');
519 $g->whereAddIn('id', $grps, 'int');
520 return $g->fetchAll($what);
524 function hasPerm($name, $lvl)
526 static $pcache = array();
528 if (!isset($pcache[$this->id])) {
529 $pcache[$this->id] = $this->getPerms();
531 // echo "<PRE>";print_r($pcache[$au->id]);
532 // var_dump($pcache[$au->id]);
533 if (empty($pcache[$this->id][$name])) {
537 return strpos($pcache[$this->id][$name], $lvl) > -1;
541 // ------------ROO HOOKS------------------------------------
542 function applyFilters($q, $au, $roo)
544 //DB_DataObject::DebugLevel(1);
545 if (!empty($q['query']['person_not_internal'])) {
546 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
550 if (!empty($q['query']['person_internal_only_all'])) {
553 // must be internal and not current user (need for distribution list)
554 // user has a projectdirectory entry and role is not blank.
555 //DB_DataObject::DebugLevel(1);
556 $pd = DB_DataObject::factory('ProjectDirectory');
557 $pd->whereAdd("role != ''");
559 $pd->selectAdd('distinct(person_id) as person_id');
560 $roled = $pd->fetchAll('person_id');
562 {$this->tableName()}.id IN (".implode(',', $roled) . ")
564 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
567 // -- for distribution
568 if (!empty($q['query']['person_internal_only'])) {
569 // must be internal and not current user (need for distribution list)
570 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
572 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
573 // ".id != ".$au->id);
574 $this->whereAdd("Person.id != {$au->id}");
577 if (!empty($q['query']['comptype_or_company_id'])) {
578 // DB_DataObject::debugLevel(1);
579 $bits = explode(',', $q['query']['comptype_or_company_id']);
580 $id = (int) array_pop($bits);
581 $ct = $this->escape($bits[0]);
583 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
589 if (!empty($q['query']['person_inactive'])) {
590 // DB_Dataobject::debugLevel(1);
593 $tn_p = $this->tableName();
594 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
595 $tn_g = DB_DataObject::Factory('Groups')->tableName();
597 ///---------------- Group views --------
598 if (!empty($q['query']['in_group'])) {
599 // DB_DataObject::debugLevel(1);
600 $ing = (int) $q['query']['in_group'];
601 if ($q['query']['in_group'] == -1) {
603 // list all staff who are not in a group.
604 $this->whereAdd("Person.id NOT IN (
605 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
606 $tn_g ON $tn_g.id = $tn_gm.group_id
607 WHERE $tn_g.type = ".$q['query']['type']."
613 $this->whereAdd("$tn_p.id IN (
614 SELECT distinct(user_id) FROM $tn_gm
615 WHERE group_id = $ing
621 if (!empty($q['query']['not_in_directory'])) {
622 // it's a Person list..
623 // DB_DATaobjecT::debugLevel(1);
625 // specific to project directory which is single comp. login
627 $owncomp = DB_DataObject::Factory('Companies');
628 $owncomp->get('comptype', 'OWNER');
629 if ($q['company_id'] == $owncomp->id) {
635 if ( $q['query']['not_in_directory'] > -1) {
636 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
637 // can list current - so that it does not break!!!
638 $this->whereAdd("$tn_p.id NOT IN
639 ( SELECT distinct person_id FROM $tn_pd WHERE
640 project_id = " . $q['query']['not_in_directory'] . " AND
641 company_id = " . $this->company_id . ')');
645 if (!empty($q['query']['role'])) {
646 // it's a Person list..
647 // DB_DATaobjecT::debugLevel(1);
649 // specific to project directory which is single comp. login
651 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
652 // can list current - so that it does not break!!!
653 $this->whereAdd("$tn_p.id IN
654 ( SELECT distinct person_id FROM $tn_pd WHERE
655 role = '". $this->escape($q['query']['role']) ."'
661 if (!empty($q['query']['project_member_of'])) {
662 // this is also a flag to return if they are a member..
663 //DB_DataObject::debugLevel(1);
664 $do = DB_DataObject::factory('ProjectDirectory');
665 $do->project_id = $q['query']['project_member_of'];
666 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
667 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
668 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
671 if (!empty($q['query']['project_member_filter'])) {
672 $this->having('is_member !=0');
679 if (!empty($q['query']['search'])) {
680 $s = $this->escape($q['query']['search']);
682 $tn_p.name LIKE '%$s%' OR
683 $tn_p.email LIKE '%$s%' OR
684 $tn_p.role LIKE '%$s%' OR
685 $tn_p.remarks LIKE '%$s%'
692 function setFromRoo($ar, $roo)
695 if (!empty($ar['passwd1'])) {
696 $this->setPassword($ar['passwd1']);
701 ($this->email == $roo->old->email)&&
702 ($this->company_id == $roo->old->company_id)
706 if (empty($this->email)) {
709 $xx = DB_Dataobject::factory('Person');
711 'email' => $this->email,
712 // 'company_id' => $x->company_id
716 return "Duplicate Email found";
722 * before Delete - delete significant dependancies..
723 * this is called after checkPerm..
726 function beforeDelete()
729 $e = DB_DataObject::Factory('Events');
730 $e->whereAdd('person_id = ' . $this->id);
739 * Check if the a user has access to modify this item.
740 * @param String $lvl Level (eg. Core.Projects)
741 * @param Pman_Core_DataObjects_Person $au The authenticated user.
742 * @param boolean $changes alllow changes???
744 * @return false if no access..
746 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
749 // do we have an empty system..
750 if ($au && $au->id == -1) {
754 // determine if it's staff!!!
756 if ($au->company()->comptype != 'OWNER') {
758 // - can not change company!!!
760 isset($changes['company_id']) &&
761 $changes['company_id'] != $au->company_id) {
764 // can only set new emails..
766 !empty($this->email) &&
767 isset($changes['email']) &&
768 $changes['email'] != $this->email) {
772 // edit self... - what about other staff members...
774 return $this->company_id == $au->company_id;
778 // yes, only owner company can mess with this...
779 $owncomp = DB_DataObject::Factory('Companies');
780 $owncomp->get('comptype', 'OWNER');
782 $isStaff = ($this->company_id == $owncomp->id);
786 // extra case change passwod?
787 case 'P': //??? password
788 // standard perms -- for editing + if the user is dowing them selves..
789 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
790 return $ret || $au->id == $this->id;
793 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
798 function onInsert($req, $roo)
801 if ($roo->authUser->id < 0) {
802 $g = DB_DataObject::factory('Groups');
804 $g->get('name', 'Administrators');
806 $p = DB_DataObject::factory('group_members');
807 $p->group_id = $g->id;
808 $p->user_id = $this->id;
811 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
815 if (!empty($req['project_id_addto'])) {
816 $pd = DB_DataObject::factory('ProjectDirectory');
817 $pd->project_id = $req['project_id_addto'];
818 $pd->person_id = $this->id;
820 $pd->office_id = $this->office_id;
821 $pd->company_id = $this->company_id;