3 * Table Definition for Person
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
8 class Pman_Core_DataObjects_Core_person extends DB_DataObject
11 /* the code below is auto generated do not remove the above tag */
13 public $__table = 'core_person'; // table name
14 public $id; // int(11) not_null primary_key auto_increment
15 public $email; // string(128) not_null
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
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)
36 public $active; // int(11) not_null
37 public $deleted_by; // int(11) not_null
38 public $deleted_dt; // datetime(19) binary
41 public $name_facebook; // VARCHAR(128) NULL;
42 public $url_blog; // VARCHAR(256) NULL ;
43 public $url_twitter; // VARCHAR(256) NULL ;
44 public $url_linkedin; // VARCHAR(256) NULL ;
45 public $linkedin_id; // VARCHAR(256) NULL ;
47 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
48 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
49 public $countries; // VARCHAR(128) NULL;
51 /* the code above is auto generated do not remove the tag below */
54 static $authUser = false;
59 $p = DB_DataObject::Factory($this->tableName());
60 $p->get($this->owner_id);
69 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
75 function buildMail($templateFile, $args)
78 $args = (array) $args;
79 $content = clone($this);
81 foreach((array)$args as $k=>$v) {
85 $ff = HTML_FlexyFramework::get();
88 //?? is this really the place for this???
91 empty($args['no_auth']) &&
92 !in_array($templateFile, array(
93 // templates that can be sent without authentication.
99 $content->authUser = $this->getAuthUser();
100 if (!$content->authUser) {
101 return PEAR::raiseError("Not authenticated");
105 // should handle x-forwarded...
107 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
108 $_SERVER["HTTP_HOST"] :
109 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
111 /* use the regex compiler, as it doesnt parse <tags */
114 'compiler' => 'Flexy',
116 'filters' => array('SimpleTags','Mail'),
122 if (!empty($args['templateDir'])) {
123 $tops['templateDir'] = $args['templateDir'];
128 require_once 'HTML/Template/Flexy.php';
129 $template = new HTML_Template_Flexy( $tops );
130 $template->compile("mail/$templateFile.txt");
132 /* use variables from this object to ouput data. */
133 $mailtext = $template->bufferedOutputObject($content);
136 // if a html file with the same name exists, use that as the body
137 // I've no idea where this code went, it was here before..
138 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
139 $tops['nonHTML'] = false;
140 $template = new HTML_Template_Flexy( $tops );
141 $template->compile("mail/$templateFile.html");
142 $htmlbody = $template->bufferedOutputObject($content);
148 //echo "<PRE>";print_R($mailtext);
149 //print_R($mailtext);exit;
150 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
151 require_once 'Mail/mimeDecode.php';
152 require_once 'Mail.php';
154 $decoder = new Mail_mimeDecode($mailtext);
155 $parts = $decoder->getSendArray();
157 if (is_a($parts,'PEAR_Error')) {
159 //echo "PROBLEM: {$parts->message}";
162 list($recipents,$headers,$body) = $parts;
163 $recipents = array($this->email);
164 if (!empty($content->bcc) && is_array($content->bcc)) {
165 $recipents =array_merge($recipents, $content->bcc);
167 $headers['Date'] = date('r');
169 if ($htmlbody !== false) {
170 require_once 'Mail/mime.php';
171 $mime = new Mail_mime(array('eol' => "\n"));
172 $mime->setTXTBody($body);
173 $mime->setHTMLBody($htmlbody);
174 // I think there might be code in mediaoutreach toEmail somewhere
175 // h embeds images here..
176 $body = $mime->get();
177 $headers = $mime->headers($headers);
181 'recipients' => $recipents,
182 'headers' => $headers,
190 * - user must be authenticate or args[no_auth] = true
191 * or template = password_[reset|welcome]
194 function sendTemplate($templateFile, $args)
196 $ar = $this->buildMail($templateFile, $args);
198 //print_r($recipents);exit;
199 $mailOptions = PEAR::getStaticProperty('Mail','options');
200 $mail = Mail::factory("SMTP",$mailOptions);
202 if (PEAR::isError($mail)) {
205 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
206 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
207 error_reporting($oe);
215 function getEmailFrom()
217 if (empty($this->name)) {
221 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
224 function toEventString()
226 return empty($this->name) ? $this->email : $this->name;
229 function verifyAuth()
231 $ff= HTML_FlexyFramework::get();
232 if (!empty($ff->Pman['auth_comptype']) &&
233 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
236 $sesPrefix = $this->sesPrefix();
238 self::$authUser = false;
239 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
243 //$ff->page->jerr("Login not permited to outside companies");
250 // ---------------- authentication / passwords and keys stuff ----------------
255 $ff= HTML_FlexyFramework::get();
257 $sesPrefix = $this->sesPrefix();
259 if (self::$authUser) {
260 return self::$authUser;
264 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
266 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
267 $u = DB_DataObject::factory($this->tableName());
269 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
270 if ($u->verifyAuth()) {
271 self::$authUser = $u;
275 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
276 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
277 setcookie('Pman.timeout', -1, time() + (30*60), '/');
282 $u = DB_DataObject::factory($this->tableName());
284 if (!empty($_SERVER['PHP_AUTH_USER'])
286 !empty($_SERVER['PHP_AUTH_PW'])
288 $u->get('email', $_SERVER['PHP_AUTH_USER'])
290 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
292 // logged in via http auth
293 // http auth will not need session...
294 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
295 self::$authUser = $u;
299 if (!$this->canInitializeSystem()) {
300 // die("can not init");
305 $auto_auth_allow = false;
306 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
307 $auto_auth_allow = true;
309 if ( !empty($ff->Pman['local_autoauth'])
311 !empty($_SERVER['SERVER_ADDR']) &&
312 !empty($_SERVER['REMOTE_ADDR']) &&
315 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
316 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
320 $_SERVER['SERVER_ADDR'] == '::1' &&
321 $_SERVER['REMOTE_ADDR'] == '::1'
326 $auto_auth_allow = true;
330 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login' || $_SERVER['PATH_INFO'] == '/PasswordReset'
332 $auto_auth_allow = false;
334 //var_dump($auto_auth_allow);
336 $default_admin = false;
337 if ($auto_auth_allow) {
338 $group = DB_DataObject::factory('core_group');
339 $group->get('name', 'Administrators');
341 $member = DB_DataObject::factory('core_group_member');
343 $member->group_id = $group->id;
345 join_user_id_id.id IS NOT NULL
347 if($member->find(true)){
348 $default_admin = DB_DataObject::factory($this->tableName());
349 $default_admin->autoJoin();
350 if(!$default_admin->get($member->user_id)){
351 $default_admin = false;
356 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
357 $u = DB_DataObject::factory($this->tableName());
359 $ff = HTML_FlexyFramework::get();
361 if ($auto_auth_allow &&
362 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
365 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
367 // if we request other URLS.. then we get auto logged in..
368 self::$authUser = $default_admin ? $default_admin : $u;;
369 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
373 //var_dump(session_id());
374 //var_dump($_SESSION[__CLASS__]);
376 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
379 //die("got this far?");
380 // not in session or not matched...
381 $u = DB_DataObject::factory($this->tableName());
382 $u->whereAdd(' LENGTH(passwd) > 0');
384 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
385 if (class_exists('PEAR')) {
386 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
388 die($error->toString()); // not really a good thing to do...
391 if (!$n){ // authenticated as there are no users in the system...
398 function canInitializeSystem()
401 return !strcasecmp(get_class($this) , __CLASS__);
404 function getAuthUser()
406 if (!$this->isAuth()) {
410 $ff= HTML_FlexyFramework::get();
412 $sesPrefix = $this->sesPrefix();
414 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
416 if (self::$authUser) {
418 if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
419 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
420 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
422 // not really sure why it's cloned..
423 return clone (self::$authUser);
430 if (!$this->canInitializeSystem()) {
436 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
437 $u = DB_DataObject::factory($this->tableName());
438 $u->whereAdd(' LENGTH(passwd) > 0');
439 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
444 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
445 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
448 // fake person - open system..
449 //$ce = DB_DataObject::factory('core_enum');
453 $u = DB_DataObject::factory($this->tableName());
456 // if a company has been created fill that in in company_id_id
457 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
459 $u->company_id_id = $c->pid();
460 $u->company_id = $c->pid();
470 $this->isAuth(); // force session start..
471 if (!$this->verifyAuth()) { // check for company valid..
475 // open up iptables at login..
476 $dbname = $this->databaseNickname();
477 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
479 // refresh admin group if we are logged in as one..
480 //DB_DataObject::debugLevel(1);
481 $g = DB_DataObject::factory('core_group');
483 $g->get('name', 'Administrators');
484 $gm = DB_DataObject::Factory('core_group_member');
485 if (in_array($g->id,$gm->listGroupMembership($this))) {
486 // refresh admin groups.
487 $gr = DB_DataObject::Factory('core_group_right');
488 $gr->applyDefs($g, 0);
491 $sesPrefix = $this->sesPrefix();
493 // we should not store the whole data in the session - otherwise it get's huge.
494 $p = DB_DAtaObject::Factory($this->tableName());
495 $p->get($this->pid());
499 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
500 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
502 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
503 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
505 $pp = DB_DAtaObject::Factory($this->tableName());
506 $pp->get($this->pid());
509 self::$authUser = $pp;
510 // ensure it's written so that ajax calls can fetch it..
517 $this->isAuth(); // force session start..
519 $sesPrefix = $this->sesPrefix();
521 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
523 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
525 self::$authUser = false;
528 function genPassKey ($t)
530 return md5($this->email . $t. $this->passwd);
532 function simpleAuthKey($m = 0)
534 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
536 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
539 function checkTwoFactorAuthentication($val)
543 // also used in login
544 require_once 'System.php';
548 empty($this->oath_key)
553 $oathtool = System::which('oathtool');
559 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
561 $password = exec($cmd);
563 return ($password == $val) ? true : false;
566 function checkPassword($val)
568 if (substr($this->passwd,0,1) == '$') {
569 if (function_exists('pasword_verify')) {
570 return password_verify($val, $this->passwd);
572 return crypt($val,$this->passwd) == $this->passwd ;
574 // old style md5 passwords...- cant be used with courier....
575 return md5($val) == $this->passwd;
578 function setPassword($value)
580 if (function_exists('pasword_hash')) {
581 return password_hash($value);
585 while(strlen($salt)<9) {
586 $salt.=chr(rand(64,126));
587 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
589 $this->passwd = crypt($value, '$1$'. $salt. '$');
594 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
596 require_once 'Text/Password.php';
597 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
598 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
599 $this->setPassword($this->rawPasswd);
600 return $this->rawPasswd;
605 $x = DB_DataObject::factory('core_company');
607 $x->get($this->company_id);
610 function loadCompany()
612 $this->company = $this->company();
617 return $this->active;
619 function authUserName($n) // set username prior to acheck user exists query.
622 $this->whereAdd('LENGTH(passwd) > 1');
627 if (!func_num_args()) {
630 $ar = func_get_args();
631 $val = array_shift($ar);
632 if ($val == $this->lang) {
642 function authUserArray()
645 $aur = $this->toArray();
652 //DB_DataObject::debugLevel(1);
653 $c = DB_Dataobject::factory('core_company');
654 $im = DB_Dataobject::factory('Images');
655 $c->joinAdd($im, 'LEFT');
657 $c->selectAs($c, 'company_id_%s');
658 $c->selectAs($im, 'company_id_logo_id_%s');
659 $c->id = $this->company_id;
663 $aur = array_merge( $c->toArray(),$aur);
665 if (empty($c->company_id_logo_id_id)) {
667 $im = DB_Dataobject::factory('Images');
668 $im->ontable = DB_DataObject::factory('core_company')->tableName();
670 $im->imgtype = 'LOGO';
673 $im->selectAs($im, 'company_id_logo_id_%s');
674 if ($im->find(true)) {
676 foreach($im->toArray() as $k=>$v) {
677 if (!preg_match('/^company_id_logo_id_/', $k)) {
686 $aur['perms'] = $this->getPerms();
687 $g = DB_DataObject::Factory('core_group_member');
688 $aur['groups'] = $g->listGroupMembership($this, 'name');
691 $aur['dailykey'] = '';
692 $aur['oath_key'] = '';
694 $aur['oath_key_enable'] = !empty($this->oath_key);
695 $aur['require_oath'] = 1;
697 $s = DB_DataObject::Factory('core_setting');
698 $oath_require = $s->lookup('core', 'two_factor_auth_required');
699 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
704 // ----------PERMS------ ----------------
707 //DB_DataObject::debugLevel(1);
708 // find out all the groups they are a member of.. + Default..
710 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
712 $g = DB_DataObject::Factory('core_group_right');
718 return $g->adminRights(); // system is not set up - so they get full rights.
720 //DB_DataObject::debugLevel(1);
721 $g = DB_DataObject::Factory('core_group_member');
722 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
724 // add the current user to the admin group..
725 $g = DB_DataObject::Factory('core_group');
726 if ($g->get('name', 'Administrators')) {
727 $gm = DB_DataObject::Factory('core_group_member');
728 $gm->group_id = $g->id;
729 $gm->user_id = $this->id;
735 // ------ STANDARD PERMISSION HANDLING.
736 $isOwner = $this->company()->comptype == 'OWNER';
737 $g = DB_DataObject::Factory('core_group_member');
738 $grps = $g->listGroupMembership($this);
740 $isAdmin = $g->inAdmin; //??? what???
741 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
742 // the load all the perms for those groups, and add them all together..
743 // then load all those
744 $g = DB_DataObject::Factory('core_group_right');
745 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
746 //echo '<PRE>';print_r($ret);
752 *Basic group fetching - probably needs to filter by type eventually.
754 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
757 function groups($what=false)
759 $g = DB_DataObject::Factory('core_group_member');
760 $grps = $g->listGroupMembership($this);
761 $g = DB_DataObject::Factory('core_group');
762 $g->whereAddIn('id', $grps, 'int');
763 return $g->fetchAll($what);
769 function hasPerm($name, $lvl)
771 static $pcache = array();
773 if (!isset($pcache[$this->id])) {
774 $pcache[$this->id] = $this->getPerms();
777 // echo "<PRE>";print_r($pcache[$au->id]);
778 // var_dump($pcache[$au->id]);
779 if (empty($pcache[$this->id][$name])) {
783 return strpos($pcache[$this->id][$name], $lvl) > -1;
787 // ------------ROO HOOKS------------------------------------
788 function applyFilters($q, $au, $roo)
790 //DB_DataObject::DebugLevel(1);
791 if(!empty($q['_to_qr_code'])){
792 $person = DB_DataObject::factory('Core_person');
793 $person->id = $q['id'];
795 if(!$person->find(true)) {
796 $roo->jerr('_invalid_person');
799 $hash = $this->generateOathKey();
801 $_SESSION[__CLASS__] =
802 isset($_SESSION[__CLASS__]) ?
803 $_SESSION[__CLASS__] : array();
804 $_SESSION[__CLASS__]['oath'] =
805 isset($_SESSION[__CLASS__]['oath']) ?
806 $_SESSION[__CLASS__]['oath'] : array();
808 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
810 $qrcode = $person->generateQRCode($hash);
813 $roo->jerr('Fail to generate QR Code');
819 if(!empty($q['two_factor_auth_code'])) {
820 $person = DB_DataObject::factory('core_person');
821 $person->get($q['id']);
823 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
825 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
827 unset($_SESSION[__CLASS__]['oath'][$person->id]);
831 $roo->jerr('_invalid_auth_code');
834 if(!empty($q['oath_key_disable'])) {
835 $person = DB_DataObject::factory('core_person');
836 $person->get($q['id']);
840 $person->oath_key = '';
846 if (!empty($q['query']['is_owner'])) {
847 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
850 if (!empty($q['query']['person_not_internal'])) {
851 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
854 if (!empty($q['query']['person_internal_only_all'])) {
857 // must be internal and not current user (need for distribution list)
858 // user has a projectdirectory entry and role is not blank.
859 //DB_DataObject::DebugLevel(1);
860 $pd = DB_DataObject::factory('ProjectDirectory');
861 $pd->whereAdd("role != ''");
863 $pd->selectAdd('distinct(person_id) as person_id');
864 $roled = $pd->fetchAll('person_id');
866 {$this->tableName()}.id IN (".implode(',', $roled) . ")
868 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
871 // -- for distribution
872 if (!empty($q['query']['person_internal_only'])) {
873 // must be internal and not current user (need for distribution list)
874 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
876 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
877 // ".id != ".$au->id);
878 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
881 if (!empty($q['query']['comptype_or_company_id'])) {
882 // DB_DataObject::debugLevel(1);
883 $bits = explode(',', $q['query']['comptype_or_company_id']);
884 $id = (int) array_pop($bits);
885 $ct = $this->escape($bits[0]);
887 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
893 if (!empty($q['query']['person_inactive'])) {
894 // DB_Dataobject::debugLevel(1);
897 $tn_p = $this->tableName();
898 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
899 $tn_g = DB_DataObject::Factory('core_group')->tableName();
901 ///---------------- Group views --------
902 if (!empty($q['query']['in_group'])) {
903 // DB_DataObject::debugLevel(1);
904 $ing = (int) $q['query']['in_group'];
905 if ($q['query']['in_group'] == -1) {
907 // list all staff who are not in a group.
908 $this->whereAdd("{$this->tableName()}.id NOT IN (
909 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
910 $tn_g ON $tn_g.id = $tn_gm.group_id)");
914 $this->whereAdd("$tn_p.id IN (
915 SELECT distinct(user_id) FROM $tn_gm
916 WHERE group_id = $ing
922 if(!empty($q['in_group_name'])){
924 $v = $this->escape($q['in_group_name']);
929 DISTINCT(user_id) FROM $tn_gm
933 $tn_g.id = $tn_gm.group_id
940 // #2307 Search Country!!
941 if (!empty($q['query']['in_country'])) {
942 // DB_DataObject::debugLevel(1);
943 $inc = $q['query']['in_country'];
944 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
947 if (!empty($q['query']['not_in_directory'])) {
948 // it's a Person list..
949 // DB_DATaobjecT::debugLevel(1);
951 // specific to project directory which is single comp. login
953 $owncomp = DB_DataObject::Factory('core_company');
954 $owncomp->get('comptype', 'OWNER');
955 if ($q['company_id'] == $owncomp->id) {
961 if ( $q['query']['not_in_directory'] > -1) {
962 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
963 // can list current - so that it does not break!!!
964 $this->whereAdd("$tn_p.id NOT IN
965 ( SELECT distinct person_id FROM $tn_pd WHERE
966 project_id = " . $q['query']['not_in_directory'] . " AND
967 company_id = " . $this->company_id . ')');
971 if (!empty($q['query']['role'])) {
972 // it's a Person list..
973 // DB_DATaobjecT::debugLevel(1);
975 // specific to project directory which is single comp. login
977 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
978 // can list current - so that it does not break!!!
979 $this->whereAdd("$tn_p.id IN
980 ( SELECT distinct person_id FROM $tn_pd WHERE
981 role = '". $this->escape($q['query']['role']) ."'
987 if (!empty($q['query']['project_member_of'])) {
988 // this is also a flag to return if they are a member..
989 //DB_DataObject::debugLevel(1);
990 $do = DB_DataObject::factory('ProjectDirectory');
991 $do->project_id = $q['query']['project_member_of'];
992 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
993 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
994 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
997 if (!empty($q['query']['project_member_filter'])) {
998 $this->having('is_member !=0');
1004 if(!empty($q['query']['name'])){
1006 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1009 if(!empty($q['query']['name_starts'])){
1011 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1015 if (!empty($q['query']['search'])) {
1017 // use our magic search builder...
1019 require_once 'Text/SearchParser.php';
1020 $x = new Text_SearchParser($q['query']['search']);
1028 "join_company_id_id.name"
1030 $tbcols = $this->table();
1031 foreach(array('firstname','lastname') as $k) {
1032 if (isset($tbcols[$k])) {
1033 $props[] = "{$tn_p}.{$k}";
1040 $str = $x->toSQL(array(
1041 'default' => $props,
1043 'company' => 'join_company_id_id.name',
1044 //'country' => 'Clipping.country',
1045 // 'media' => 'Clipping.media_name',
1047 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1052 $this->whereAdd($str); /*
1053 $tn_p.name LIKE '%$s%' OR
1054 $tn_p.email LIKE '%$s%' OR
1055 $tn_p.role LIKE '%$s%' OR
1056 $tn_p.phone LIKE '%$s%' OR
1057 $tn_p.remarks LIKE '%$s%'
1062 // project directory rules -- this may distrupt things.
1063 $p = DB_DataObject::factory('ProjectDirectory');
1064 // if project directories are set up, then we can apply project query rules..
1067 $pids = $p->projects($au);
1068 if (isset($q['query']['project_id'])) {
1069 $pid = (int)$q['query']['project_id'];
1070 if (!in_array($pid, $pids)) {
1071 $roo->jerr("Project not in users valid projects");
1073 $pids = array($pid);
1076 //if (empty($q['_anyrole'])) { // should be project_directry_role
1077 // $p->whereAdd("{$p->tableName()}.role != ''");
1079 if (!empty($q['query']['role'])) { // should be project_directry_role
1080 $role = $this->escape($q['query']['role']);
1082 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1086 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1087 $peps = $p->people($pids);
1088 $this->whereAddIn("{$tn}.id", $peps, 'int');
1092 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1093 if (isset($q['query']['ticket_id'])) {
1094 // find out what state the ticket is in.
1095 $t = DB_DataObject::Factory('mtrack_ticket');
1097 $t->get($q['query']['ticket_id']);
1099 if (!$this->checkPerm('S', $au)) {
1100 $roo->jerr("permssion denied to query state of ticket");
1103 $p = DB_DataObject::factory('ProjectDirectory');
1104 $pids = array($t->project_id);
1106 $peps = $p->people($pids);
1108 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1110 //$this->whereAdd('join_prole != ''");
1115 * Seems we never expose oath_key / passwd, so...
1118 if($this->tableName() == 'core_person'){
1119 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1122 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1123 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1130 function setFromRoo($ar, $roo)
1132 $this->setFrom($ar);
1134 if(!empty($ar['_enable_oath_key'])){
1135 $oath_key = $this->generateOathKey();
1138 if (!empty($ar['passwd1'])) {
1139 $this->setPassword($ar['passwd1']);
1143 ($this->email == $roo->old->email)&&
1144 ($this->company_id == $roo->old->company_id)
1148 if (empty($this->email)) {
1151 // this only applies to our owner company..
1152 $c = $this->company();
1153 if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1158 $xx = DB_Dataobject::factory($this->tableName());
1160 'email' => $this->email,
1161 // 'company_id' => $x->company_id
1165 return "Duplicate Email found";
1172 * before Delete - delete significant dependancies..
1173 * this is called after checkPerm..
1176 function beforeDelete($dependants_array, $roo)
1178 //delete group membership except for admin group..
1179 // if they are a member of admin group do not delete anything.
1180 $default_admin = false;
1182 $e = DB_DataObject::Factory('Events');
1183 $e->whereAdd('person_id = ' . $this->id);
1185 $g = DB_DataObject::Factory('core_group');
1186 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1188 $p = DB_DataObject::Factory('core_group_member');
1190 'user_id' => $this->id,
1191 'group_id' => $g->id
1195 $roo->jerr("Please remove this user from the Administrator group before deleting");
1199 $p = DB_DataObject::Factory('core_group_member');
1200 $p->user_id = $this->id;
1201 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1202 $e->logDeletedRecord($mem);
1204 foreach($mem as $p) {
1208 $e = DB_DataObject::Factory('Events');
1209 $e->person_id = $this->id;
1210 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1212 $e->logDeletedRecord($eve);
1213 foreach($eve as $e) {
1224 * Check if the a user has access to modify this item.
1225 * @param String $lvl Level (eg. Core.Projects)
1226 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1227 * @param boolean $changes alllow changes???
1229 * @return false if no access..
1231 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1234 // do we have an empty system..
1235 if ($au && $au->id == -1) {
1238 // if not authenticated... do not allow in???
1243 // determine if it's staff!!!
1244 $owncomp = DB_DataObject::Factory('core_company');
1245 $owncomp->get('comptype', 'OWNER');
1246 $isStaff = ($au->company_id == $owncomp->id);
1251 // - can not change company!!!
1253 isset($changes['company_id']) &&
1254 $changes['company_id'] != $au->company_id) {
1257 // can only set new emails..
1259 !empty($this->email) &&
1260 isset($changes['email']) &&
1261 $changes['email'] != $this->email) {
1266 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1267 // ???? do we want this?
1269 // edit self... - what about other staff members...
1271 //return $this->company_id == $au->company_id;
1275 // yes, only owner company can mess with this...
1281 // extra case change passwod?
1282 case 'P': //??? password
1283 // standard perms -- for editing + if the user is dowing them selves..
1284 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1285 return $ret || $au->id == $this->id;
1288 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1294 function beforeInsert($req, $roo)
1296 $p = DB_DataObject::factory('core_person');
1297 if ($roo->authUser->id > -1 || $p->count() > 1) {
1300 $c = DB_DataObject::Factory('core_company');
1303 if (!$tc || $tc> 1) {
1304 $roo->jerr("can not create initial user as multiple companies already exist");
1307 $this->company_id = $c->id;
1308 $this->email = trim($this->email);
1312 function onInsert($req, $roo)
1315 $p = DB_DataObject::factory('core_person');
1316 if ($roo->authUser->id < 0 && $p->count() == 1) {
1317 // this seems a bit risky...
1319 $g = DB_DataObject::factory('core_group');
1323 $g->get('name', 'Administrators');
1325 $p = DB_DataObject::factory('core_group_member');
1326 $p->group_id = $g->id;
1327 $p->user_id = $this->id;
1330 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1334 if (!empty($req['project_id_addto'])) {
1335 $pd = DB_DataObject::factory('ProjectDirectory');
1336 $pd->project_id = $req['project_id_addto'];
1337 $pd->person_id = $this->id;
1339 $pd->office_id = $this->office_id;
1340 $pd->company_id = $this->company_id;
1346 function importFromArray($roo, $persons, $opts)
1348 if (empty($opts['prefix'])) {
1349 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1352 if (!is_array($persons) || empty($persons)) {
1353 $roo->jerr("error in the person data. - empty on not valid");
1355 DB_DataObject::factory('core_group')->initGroups();
1357 foreach($persons as $person){
1358 $p = DB_DataObject::factory('core_person');
1359 if($p->get('name', $person['name'])){
1362 $p->setFrom($person);
1364 $companies = DB_DataObject::factory('core_company');
1365 if(!$companies->get('comptype', 'OWNER')){
1366 $roo->jerr("Missing OWNER companies!");
1368 $p->company_id = $companies->pid();
1369 // strip the 'spaces etc.. make lowercase..
1370 $name = strtolower(str_replace(' ', '', $person['name']));
1371 $p->setPassword("{$opts['prefix']}{$name}");
1374 // if $person->groups is set.. then
1375 // add this person to that group eg. groups : [ 'Administrator' ]
1376 if(!empty($person['groups'])){
1377 $groups = DB_DataObject::factory('core_group');
1378 if(!$groups->get('name', $person['groups'])){
1379 $roo->jerr("Missing groups : {$person['groups']}");
1381 $gm = DB_DataObject::factory('core_group_member');
1382 $gm->change($p, $groups, true);
1385 $p->onInsert(array(), $roo);
1389 // this is for the To: "{getEmailName()}" <email@address>
1390 // not good for Dear XXXX, - use {person.firstname} for that.
1391 function getEmailName()
1395 if(!empty($this->honor)){
1396 array_push($name, $this->honor);
1399 if(!empty($this->name)){
1400 array_push($name, $this->name);
1402 return implode(' ', $name);
1405 if(!empty($this->firstname) || !empty($this->lastname)){
1406 array_push($name, $this->firstname);
1407 array_push($name, $this->lastname);
1409 $name = array_filter($name);
1411 return implode(' ', $name);
1414 return $this->email;
1417 function sesPrefix()
1419 $ff= HTML_FlexyFramework::get();
1421 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1423 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1425 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1430 function loginPublic() // used where???
1432 $this->isAuth(); // force session start..
1434 $db = $this->getDatabaseConnection();
1436 $ff = HTML_FlexyFramework::get();
1438 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1442 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1444 $p = DB_DAtaObject::Factory($this->tableName());
1445 $p->get($this->pid());
1447 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1452 function beforeUpdate($old, $q, $roo)
1454 $this->email = trim($this->email);
1457 function generateOathKey()
1459 require 'Base32.php';
1461 $base32 = new Base32();
1463 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1466 function generateQRCode($hash)
1469 empty($this->email) &&
1475 $issuer = (empty($this->name)) ?
1476 rawurlencode('ROOJS') : rawurlencode($this->name);
1478 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1480 require_once 'Image/QRCode.php';
1482 $qrcode = new Image_QRCode();
1484 $image = $qrcode->makeCode($uri, array(
1485 'output_type' => 'return'
1490 $base64 = base64_encode(ob_get_contents());
1493 return "data:image/png;base64,{$base64}";
1496 static function test_ADMIN_PASSWORD_RESET($pg, $to)
1498 $ff = HTML_FlexyFramework::get();
1499 $person = DB_DataObject::Factory('core_person');
1503 'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1504 'person' => $person,
1505 'authFrom' => 'FAKE_LINK',
1506 'authKey' => 'FAKE_KEY',
1508 'rcpts' => $to->email,