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;
53 /* the code above is auto generated do not remove the tag below */
56 static $authUser = false;
61 // this might be a Person in some old code?
62 $p = DB_DataObject::Factory('core_person');
63 $p->get($this->owner_id);
72 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
78 function buildMail($templateFile, $args)
81 $args = (array) $args;
82 $content = clone($this);
84 foreach((array)$args as $k=>$v) {
88 $ff = HTML_FlexyFramework::get();
91 //?? is this really the place for this???
94 empty($args['no_auth']) &&
95 !in_array($templateFile, array(
96 // templates that can be sent without authentication.
102 $content->authUser = $this->getAuthUser();
103 if (!$content->authUser) {
104 return PEAR::raiseError("Not authenticated");
108 // should handle x-forwarded...
110 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
111 $_SERVER["HTTP_HOST"] :
112 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
114 /* use the regex compiler, as it doesnt parse <tags */
117 'compiler' => 'Flexy',
119 'filters' => array('SimpleTags','Mail'),
125 if (!empty($args['templateDir'])) {
126 $tops['templateDir'] = $args['templateDir'];
131 require_once 'HTML/Template/Flexy.php';
132 $template = new HTML_Template_Flexy( $tops );
133 $template->compile("mail/$templateFile.txt");
135 /* use variables from this object to ouput data. */
136 $mailtext = $template->bufferedOutputObject($content);
139 // if a html file with the same name exists, use that as the body
140 // I've no idea where this code went, it was here before..
141 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
142 $tops['nonHTML'] = false;
143 $template = new HTML_Template_Flexy( $tops );
144 $template->compile("mail/$templateFile.html");
145 $htmlbody = $template->bufferedOutputObject($content);
151 //echo "<PRE>";print_R($mailtext);
152 //print_R($mailtext);exit;
153 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
154 require_once 'Mail/mimeDecode.php';
155 require_once 'Mail.php';
157 $decoder = new Mail_mimeDecode($mailtext);
158 $parts = $decoder->getSendArray();
160 if (is_a($parts,'PEAR_Error')) {
162 //echo "PROBLEM: {$parts->message}";
165 list($recipents,$headers,$body) = $parts;
166 $recipents = array($this->email);
167 if (!empty($content->bcc) && is_array($content->bcc)) {
168 $recipents =array_merge($recipents, $content->bcc);
170 $headers['Date'] = date('r');
172 if ($htmlbody !== false) {
173 require_once 'Mail/mime.php';
174 $mime = new Mail_mime(array('eol' => "\n"));
175 $mime->setTXTBody($body);
176 $mime->setHTMLBody($htmlbody);
177 // I think there might be code in mediaoutreach toEmail somewhere
178 // h embeds images here..
179 $body = $mime->get();
180 $headers = $mime->headers($headers);
184 'recipients' => $recipents,
185 'headers' => $headers,
193 * - user must be authenticate or args[no_auth] = true
194 * or template = password_[reset|welcome]
197 function sendTemplate($templateFile, $args)
199 $ar = $this->buildMail($templateFile, $args);
201 //print_r($recipents);exit;
202 $mailOptions = PEAR::getStaticProperty('Mail','options');
203 $mail = Mail::factory("SMTP",$mailOptions);
205 if (PEAR::isError($mail)) {
208 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
209 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
210 error_reporting($oe);
218 function getEmailFrom()
220 if (empty($this->name)) {
224 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
227 function toEventString()
229 return empty($this->name) ? $this->email : $this->name;
232 function verifyAuth()
234 $ff= HTML_FlexyFramework::get();
235 if (!empty($ff->Pman['auth_comptype']) &&
236 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
239 $sesPrefix = $this->sesPrefix();
241 self::$authUser = false;
242 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
246 //$ff->page->jerr("Login not permited to outside companies");
253 // ---------------- authentication / passwords and keys stuff ----------------
256 // do not start a session if we are using http auth...
257 // we have a situation where the app is behind a http access and is also login
258 // need to work out a way to handle that.
259 $ff= HTML_FlexyFramework::get();
260 if (php_sapi_name() != "cli" && (empty($_SERVER['PHP_AUTH_USER']) || !empty($ff->disable_http_auth))) {
266 $sesPrefix = $this->sesPrefix();
268 if (self::$authUser) {
269 return self::$authUser;
273 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
275 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
276 $u = DB_DataObject::factory($this->tableName());
278 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
279 if ($u->verifyAuth()) {
280 self::$authUser = $u;
284 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
285 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
286 setcookie('Pman.timeout', -1, time() + (30*60), '/');
291 $u = DB_DataObject::factory($this->tableName());
293 if (empty($ff->disable_http_auth) // http auth requests should not have this...
295 !empty($_SERVER['PHP_AUTH_USER'])
297 !empty($_SERVER['PHP_AUTH_PW'])
299 $u->get('email', $_SERVER['PHP_AUTH_USER'])
301 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
303 // logged in via http auth
304 // http auth will not need session...
305 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
306 self::$authUser = $u;
310 // at this point all http auth stuff is done, so we can init session
314 if (!$this->canInitializeSystem()) {
315 // die("can not init");
320 $auto_auth_allow = false;
321 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
322 $auto_auth_allow = true;
324 if ( !empty($ff->Pman['local_autoauth'])
326 !empty($_SERVER['SERVER_ADDR']) &&
327 !empty($_SERVER['REMOTE_ADDR']) &&
330 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
331 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
335 $_SERVER['SERVER_ADDR'] == '::1' &&
336 $_SERVER['REMOTE_ADDR'] == '::1'
341 $auto_auth_allow = true;
345 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
346 $auto_auth_allow = false;
348 //var_dump($auto_auth_allow);
350 $default_admin = false;
351 if ($auto_auth_allow) {
352 $group = DB_DataObject::factory('core_group');
353 $group->get('name', 'Administrators');
355 $member = DB_DataObject::factory('core_group_member');
357 $member->group_id = $group->id;
359 join_user_id_id.id IS NOT NULL
361 if($member->find(true)){
362 $default_admin = DB_DataObject::factory($this->tableName());
363 $default_admin->autoJoin();
364 if(!$default_admin->get($member->user_id)){
365 $default_admin = false;
370 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
371 $u = DB_DataObject::factory($this->tableName());
373 $ff = HTML_FlexyFramework::get();
375 if ($auto_auth_allow &&
376 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
379 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
381 // if we request other URLS.. then we get auto logged in..
382 self::$authUser = $default_admin ? $default_admin : $u;;
383 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
387 //var_dump(session_id());
388 //var_dump($_SESSION[__CLASS__]);
390 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
393 //die("got this far?");
394 // not in session or not matched...
395 $u = DB_DataObject::factory($this->tableName());
396 $u->whereAdd(' LENGTH(passwd) > 0');
398 if (empty($_SESSION[get_class($this)]) || !is_array($_SESSION[get_class($this)])) {
399 $_SESSION[get_class($this)] = array();
401 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
402 if (class_exists('PEAR')) {
403 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
405 die($error->toString()); // not really a good thing to do...
408 if (!$n){ // authenticated as there are no users in the system...
415 function canInitializeSystem()
418 return !strcasecmp(get_class($this) , __CLASS__);
421 function getAuthUser()
423 if (!$this->isAuth()) {
427 $ff= HTML_FlexyFramework::get();
429 $sesPrefix = $this->sesPrefix();
431 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
433 if (self::$authUser) {
435 if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
436 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
437 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
439 // not really sure why it's cloned..
440 return clone (self::$authUser);
447 if (!$this->canInitializeSystem()) {
453 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
454 $u = DB_DataObject::factory($this->tableName());
455 $u->whereAdd(' LENGTH(passwd) > 0');
456 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
461 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
462 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
465 // fake person - open system..
466 //$ce = DB_DataObject::factory('core_enum');
470 $u = DB_DataObject::factory($this->tableName());
473 // if a company has been created fill that in in company_id_id
474 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
476 $u->company_id_id = $c->pid();
477 $u->company_id = $c->pid();
487 $this->isAuth(); // force session start..
488 if (!$this->verifyAuth()) { // check for company valid..
492 // open up iptables at login..
493 $dbname = $this->databaseNickname();
494 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
496 // refresh admin group if we are logged in as one..
497 //DB_DataObject::debugLevel(1);
498 $g = DB_DataObject::factory('core_group');
500 $g->get('name', 'Administrators');
501 $gm = DB_DataObject::Factory('core_group_member');
502 if (in_array($g->id,$gm->listGroupMembership($this))) {
503 // refresh admin groups.
504 $gr = DB_DataObject::Factory('core_group_right');
505 $gr->applyDefs($g, 0);
508 $sesPrefix = $this->sesPrefix();
510 // we should not store the whole data in the session - otherwise it get's huge.
511 $p = DB_DAtaObject::Factory($this->tableName());
512 $p->get($this->pid());
516 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
517 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
519 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
520 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
522 $pp = DB_DAtaObject::Factory($this->tableName());
523 $pp->get($this->pid());
526 self::$authUser = $pp;
527 // ensure it's written so that ajax calls can fetch it..
534 $this->isAuth(); // force session start..
536 $sesPrefix = $this->sesPrefix();
537 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
538 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
539 self::$authUser = false;
542 function genPassKey ($t)
544 return md5($this->email . $t. $this->passwd);
546 function simpleAuthKey($m = 0)
548 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
550 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
553 * When we generate autologin urls:
554 * eg. /Somesite/Test/12
556 * /Somesite/Test/12/{datetime}/{sha256(url + expires_datetime + password)}
558 * eg. genAutoLoginURL($sub, $expires)
560 function genAutoLoginURL($url, $expires = false)
562 $expires = $expires === false ? strtotime("NOW + 1 WEEK") : $expires;
563 //echo serialize(array($url, $expires, $this->email, $this->passwd));
564 //echo hash('sha256', serialize(array($url, $expires, $this->email, $this->passwd)));
566 return $url.'/'.$this->id .'/'.$expires.'/'.
569 array($url, $expires, $this->email,$this->passwd)
575 function validateAutoLogin($called)
577 $bits = explode("/",$called);
578 if (count($bits) < 4) {
579 return false; // unrelated.
581 $hash = array_pop($bits);
582 $time = array_pop($bits);
584 $id = array_pop($bits);
585 if (!is_numeric($time) || !is_numeric($id)) {
586 return false; // wrong format.
588 $u = DB_DataObject::Factory($this->tableName());
590 $url = implode("/", $bits);
591 if ($time < time()) {
594 //echo serialize(array('/'.$url, $time, $u->email, $u->passwd));
595 //echo hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)));
596 if ($hash == hash('sha256', serialize(array('/'.$url, $time*1, $u->email, $u->passwd)))) {
604 function checkTwoFactorAuthentication($val)
608 // also used in login
609 require_once 'System.php';
613 empty($this->oath_key)
618 $oathtool = System::which('oathtool');
624 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
626 $password = exec($cmd);
628 return ($password == $val) ? true : false;
631 function checkPassword($val)
633 if (substr($this->passwd,0,1) == '$') {
634 if (function_exists('pasword_verify')) {
635 return password_verify($val, $this->passwd);
637 return crypt($val,$this->passwd) == $this->passwd ;
639 // old style md5 passwords...- cant be used with courier....
640 return md5($val) == $this->passwd;
643 function setPassword($value)
645 if (function_exists('pasword_hash')) {
646 return password_hash($value);
650 while(strlen($salt)<9) {
651 $salt.=chr(rand(64,126));
652 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
654 $this->passwd = crypt($value, '$1$'. $salt. '$');
659 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
661 require_once 'Text/Password.php';
662 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
663 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
664 $this->setPassword($this->rawPasswd);
665 return $this->rawPasswd;
670 if (empty($this->company_id)) {
673 $x = DB_DataObject::factory('core_company');
675 $x->get($this->company_id);
678 function loadCompany()
680 $this->company = $this->company();
685 return $this->active;
687 function authUserName($n) // set username prior to acheck user exists query.
690 $this->whereAdd('LENGTH(passwd) > 1');
695 if (!func_num_args()) {
698 $ar = func_get_args();
699 $val = array_shift($ar);
700 if ($val == $this->lang) {
706 if(!empty(self::$authUser) && self::$authUser->id == $this->id) {
707 self::$authUser->lang = $this->lang;
713 function authUserArray()
715 $aur = $this->toArray();
721 //DB_DataObject::debugLevel(1);
722 $c = DB_Dataobject::factory('core_company');
723 $im = DB_Dataobject::factory('Images');
724 $c->joinAdd($im, 'LEFT');
726 $c->selectAs($c, 'company_id_%s');
727 $c->selectAs($im, 'company_id_logo_id_%s');
728 $c->id = $this->company_id;
732 $aur = array_merge( $c->toArray(),$aur);
734 if (empty($c->company_id_logo_id_id)) {
736 $im = DB_Dataobject::factory('Images');
737 $im->ontable = DB_DataObject::factory('core_company')->tableName();
739 $im->imgtype = 'LOGO';
742 $im->selectAs($im, 'company_id_logo_id_%s');
743 if ($im->find(true)) {
745 foreach($im->toArray() as $k=>$v) {
746 if (!preg_match('/^company_id_logo_id_/', $k)) {
755 $aur['perms'] = $this->getPerms();
756 $g = DB_DataObject::Factory('core_group_member');
757 $aur['groups'] = $g->listGroupMembership($this, 'name');
760 $aur['dailykey'] = '';
761 $aur['oath_key'] = '';
763 $aur['oath_key_enable'] = !empty($this->oath_key);
764 $aur['require_oath'] = 1;
766 $s = DB_DataObject::Factory('core_setting');
767 $oath_require = $s->lookup('core', 'two_factor_auth_required');
768 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
770 $aur['core_person_settings'] = $this->settings();
775 function settings($return_obj = false)
777 $cs = DB_DataObject::factory('core_person_settings');
779 'person_id' => $this->id
781 return $return_obj ? $cs->fetchAll() : $cs->fetchAll('scope', 'data');;
783 function toRooSingleArray($authUser, $request)
785 $ret = $this->toArray();
786 foreach( $this->settings() as $k=>$v) {
787 $ret['core_person_settings['. $k .']'] = $v;
792 // ----------PERMS------ ----------------
795 //DB_DataObject::debugLevel(1);
796 // find out all the groups they are a member of.. + Default..
798 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
800 $g = DB_DataObject::Factory('core_group_right');
806 return $g->adminRights(); // system is not set up - so they get full rights.
808 //DB_DataObject::debugLevel(1);
809 $g = DB_DataObject::Factory('core_group_member');
810 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
812 // add the current user to the admin group..
813 $g = DB_DataObject::Factory('core_group');
814 if ($g->get('name', 'Administrators')) {
815 $gm = DB_DataObject::Factory('core_group_member');
816 $gm->group_id = $g->id;
817 $gm->user_id = $this->id;
823 // ------ STANDARD PERMISSION HANDLING.
824 $isOwner = $this->company()->comptype == 'OWNER';
825 $g = DB_DataObject::Factory('core_group_member');
826 $grps = $g->listGroupMembership($this);
828 $isAdmin = $g->inAdmin; //??? what???
829 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
830 // the load all the perms for those groups, and add them all together..
831 // then load all those
832 $g = DB_DataObject::Factory('core_group_right');
833 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
834 //echo '<PRE>';print_r($ret);
840 *Basic group fetching - probably needs to filter by type eventually.
842 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
845 function groups($what=false)
847 $g = DB_DataObject::Factory('core_group_member');
848 $grps = $g->listGroupMembership($this);
849 $g = DB_DataObject::Factory('core_group');
850 $g->whereAddIn('id', $grps, 'int');
851 return $g->fetchAll($what);
857 function hasPerm($name, $lvl)
859 static $pcache = array();
861 if (!isset($pcache[$this->id])) {
862 $pcache[$this->id] = $this->getPerms();
865 // echo "<PRE>";print_r($pcache[$au->id]);
866 // var_dump($pcache[$au->id]);
867 if (empty($pcache[$this->id][$name])) {
871 return strpos($pcache[$this->id][$name], $lvl) > -1;
875 // ------------ROO HOOKS------------------------------------
876 function applyFilters($q, $au, $roo)
878 //DB_DataObject::DebugLevel(1);
879 if(!empty($q['_to_qr_code'])){
880 $person = DB_DataObject::factory('Core_person');
881 $person->id = $q['id'];
883 if(!$person->find(true)) {
884 $roo->jerr('_invalid_person');
887 $hash = $this->generateOathKey();
889 $_SESSION[__CLASS__] =
890 isset($_SESSION[__CLASS__]) ?
891 $_SESSION[__CLASS__] : array();
892 $_SESSION[__CLASS__]['oath'] =
893 isset($_SESSION[__CLASS__]['oath']) ?
894 $_SESSION[__CLASS__]['oath'] : array();
896 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
898 $qrcode = $person->generateQRCode($hash);
901 $roo->jerr('Fail to generate QR Code');
907 'issuer' => $person->qrCodeIssuer()
911 if(!empty($q['two_factor_auth_code'])) {
912 $person = DB_DataObject::factory('core_person');
913 $person->get($q['id']);
915 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
917 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
919 unset($_SESSION[__CLASS__]['oath'][$person->id]);
923 $roo->jerr('_invalid_auth_code');
926 if(!empty($q['oath_key_disable'])) {
927 $person = DB_DataObject::factory('core_person');
928 $person->get($q['id']);
932 $person->oath_key = '';
938 if (!empty($q['query']['is_owner'])) {
939 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
942 if (!empty($q['query']['person_not_internal'])) {
943 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
946 if (!empty($q['query']['person_internal_only_all'])) {
949 // must be internal and not current user (need for distribution list)
950 // user has a projectdirectory entry and role is not blank.
951 //DB_DataObject::DebugLevel(1);
952 $pd = DB_DataObject::factory('ProjectDirectory');
953 $pd->whereAdd("role != ''");
955 $pd->selectAdd('distinct(person_id) as person_id');
956 $roled = $pd->fetchAll('person_id');
958 {$this->tableName()}.id IN (".implode(',', $roled) . ")
960 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
963 // -- for distribution
964 if (!empty($q['query']['person_internal_only'])) {
965 // must be internal and not current user (need for distribution list)
966 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
968 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
969 // ".id != ".$au->id);
970 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
973 if (!empty($q['query']['comptype_or_company_id'])) {
974 // DB_DataObject::debugLevel(1);
975 $bits = explode(',', $q['query']['comptype_or_company_id']);
976 $id = (int) array_pop($bits);
977 $ct = $this->escape($bits[0]);
979 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
985 if (!empty($q['query']['person_inactive'])) {
986 // DB_Dataobject::debugLevel(1);
989 $tn_p = $this->tableName();
990 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
991 $tn_g = DB_DataObject::Factory('core_group')->tableName();
993 ///---------------- Group views --------
994 if (!empty($q['query']['in_group'])) {
995 // DB_DataObject::debugLevel(1);
996 $ing = (int) $q['query']['in_group'];
997 if ($q['query']['in_group'] == -1) {
999 // list all staff who are not in a group.
1000 $this->whereAdd("{$this->tableName()}.id NOT IN (
1001 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
1002 $tn_g ON $tn_g.id = $tn_gm.group_id)");
1006 $this->whereAdd("$tn_p.id IN (
1007 SELECT distinct(user_id) FROM $tn_gm
1008 WHERE group_id = $ing
1014 if(!empty($q['in_group_name'])){
1016 $v = $this->escape($q['in_group_name']);
1021 DISTINCT(user_id) FROM $tn_gm
1025 $tn_g.id = $tn_gm.group_id
1031 if(!empty($q['in_group_starts'])){
1033 $v = $this->escape($q['in_group_starts']);
1038 DISTINCT(user_id) FROM $tn_gm
1042 $tn_g.id = $tn_gm.group_id
1044 $tn_g.name LIKE '{$v}%'
1051 // #2307 Search Country!!
1052 if (!empty($q['query']['in_country'])) {
1053 // DB_DataObject::debugLevel(1);
1054 $inc = $q['query']['in_country'];
1055 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1058 if (!empty($q['query']['not_in_directory'])) {
1059 // it's a Person list..
1060 // DB_DATaobjecT::debugLevel(1);
1062 // specific to project directory which is single comp. login
1064 $owncomp = DB_DataObject::Factory('core_company');
1065 $owncomp->get('comptype', 'OWNER');
1066 if ($q['company_id'] == $owncomp->id) {
1072 if ( $q['query']['not_in_directory'] > -1) {
1073 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1074 // can list current - so that it does not break!!!
1075 $this->whereAdd("$tn_p.id NOT IN
1076 ( SELECT distinct person_id FROM $tn_pd WHERE
1077 project_id = " . $q['query']['not_in_directory'] . " AND
1078 company_id = " . $this->company_id . ')');
1082 if (!empty($q['query']['role'])) {
1083 // it's a Person list..
1084 // DB_DATaobjecT::debugLevel(1);
1086 // specific to project directory which is single comp. login
1088 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1089 // can list current - so that it does not break!!!
1090 $this->whereAdd("$tn_p.id IN
1091 ( SELECT distinct person_id FROM $tn_pd WHERE
1092 role = '". $this->escape($q['query']['role']) ."'
1098 if (!empty($q['query']['project_member_of'])) {
1099 // this is also a flag to return if they are a member..
1100 //DB_DataObject::debugLevel(1);
1101 $do = DB_DataObject::factory('ProjectDirectory');
1102 $do->project_id = $q['query']['project_member_of'];
1103 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1104 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1105 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
1108 if (!empty($q['query']['project_member_filter'])) {
1109 $this->having('is_member !=0');
1115 if(!empty($q['query']['name'])){
1117 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1121 if(!empty($q['query']['name_or_email'])){
1122 $v = $this->escape($q['query']['name_or_email']);
1124 {$this->tableName()}.name LIKE '%{$v}%'
1126 {$this->tableName()}.email LIKE '%{$v}%'
1129 if(!empty($q['query']['name_starts'])){
1131 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1135 if (!empty($q['query']['search'])) {
1137 // use our magic search builder...
1139 require_once 'Text/SearchParser.php';
1140 $x = new Text_SearchParser($q['query']['search']);
1148 "join_company_id_id.name"
1150 $tbcols = $this->table();
1151 foreach(array('firstname','lastname') as $k) {
1152 if (isset($tbcols[$k])) {
1153 $props[] = "{$tn_p}.{$k}";
1160 $str = $x->toSQL(array(
1161 'default' => $props,
1163 'company' => 'join_company_id_id.name',
1164 //'country' => 'Clipping.country',
1165 // 'media' => 'Clipping.media_name',
1167 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1172 $this->whereAdd($str); /*
1173 $tn_p.name LIKE '%$s%' OR
1174 $tn_p.email LIKE '%$s%' OR
1175 $tn_p.role LIKE '%$s%' OR
1176 $tn_p.phone LIKE '%$s%' OR
1177 $tn_p.remarks LIKE '%$s%'
1182 // project directory rules -- this may distrupt things.
1183 $p = DB_DataObject::factory('ProjectDirectory');
1184 // if project directories are set up, then we can apply project query rules..
1187 $pids = $p->projects($au);
1188 if (isset($q['query']['project_id'])) {
1189 $pid = (int)$q['query']['project_id'];
1190 if (!in_array($pid, $pids)) {
1191 $roo->jerr("Project not in users valid projects");
1193 $pids = array($pid);
1196 //if (empty($q['_anyrole'])) { // should be project_directry_role
1197 // $p->whereAdd("{$p->tableName()}.role != ''");
1199 if (!empty($q['query']['role'])) { // should be project_directry_role
1200 $role = $this->escape($q['query']['role']);
1202 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1206 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1207 $peps = $p->people($pids);
1208 $this->whereAddIn("{$this->tableName()}.id", $peps, 'int');
1212 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1213 if (isset($q['query']['ticket_id'])) {
1214 // find out what state the ticket is in.
1215 $t = DB_DataObject::Factory('mtrack_ticket');
1217 $t->get($q['query']['ticket_id']);
1219 if (!$this->checkPerm('S', $au)) {
1220 $roo->jerr("permssion denied to query state of ticket");
1223 $p = DB_DataObject::factory('ProjectDirectory');
1224 $pids = array($t->project_id);
1226 $peps = $p->people($pids);
1228 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1230 //$this->whereAdd('join_prole != ''");
1235 * Seems we never expose oath_key / passwd, so...
1238 if($this->tableName() == 'core_person'){
1239 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1242 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1243 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1246 if (isset($q['_with_group_membership'])) {
1247 $this->selectAddGroupMemberships();
1252 function selectAddGroupMemberships()
1258 GROUP_CONCAT( CASE WHEN core_group.display_name = '' THEN core_group.name ELSE core_group.display_name END separator '\n')
1264 core_group.id = core_group_member.group_id
1266 core_group_member.user_id = core_person.id
1268 core_group.display_name ASC
1269 ), '') as member_of");
1272 function setFromRoo($ar, $roo)
1274 $this->setFrom($ar);
1276 if(!empty($ar['_enable_oath_key'])){
1277 $oath_key = $this->generateOathKey();
1280 if (!empty($ar['passwd1'])) {
1281 $this->setPassword($ar['passwd1']);
1285 ($this->email == $roo->old->email)&&
1286 ($this->company_id == $roo->old->company_id)
1290 if (empty($this->email)) {
1293 // this only applies to our owner company..
1294 $c = $this->company();
1295 if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1300 $xx = DB_Dataobject::factory($this->tableName());
1302 'email' => $this->email,
1303 // 'company_id' => $x->company_id
1307 return "Duplicate Email found";
1314 * before Delete - delete significant dependancies..
1315 * this is called after checkPerm..
1318 function beforeDelete($dependants_array, $roo)
1320 //delete group membership except for admin group..
1321 // if they are a member of admin group do not delete anything.
1322 $default_admin = false;
1324 $e = DB_DataObject::Factory('Events');
1325 $e->whereAdd('person_id = ' . $this->id);
1327 $g = DB_DataObject::Factory('core_group');
1328 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1330 $p = DB_DataObject::Factory('core_group_member');
1332 'user_id' => $this->id,
1333 'group_id' => $g->id
1337 $roo->jerr("Please remove this user from the Administrator group before deleting");
1341 $p = DB_DataObject::Factory('core_group_member');
1342 $p->user_id = $this->id;
1343 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1344 $e->logDeletedRecord($mem);
1346 foreach($mem as $p) {
1350 $e = DB_DataObject::Factory('Events');
1351 $e->person_id = $this->id;
1352 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1354 $e->logDeletedRecord($eve);
1355 foreach($eve as $e) {
1366 * Check if the a user has access to modify this item.
1367 * @param String $lvl Level (eg. Core.Projects)
1368 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1369 * @param boolean $changes alllow changes???
1371 * @return false if no access..
1373 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1376 // do we have an empty system..
1377 if ($au && $au->id == -1) {
1380 // if not authenticated... do not allow in???
1385 // determine if it's staff!!!
1386 $owncomp = DB_DataObject::Factory('core_company');
1387 $owncomp->get('comptype', 'OWNER');
1388 $editor_is_staff = ($au->company_id == $owncomp->id);
1390 if (!$editor_is_staff) {
1391 // non staff editing should not user roo/isPerm?
1392 return false; // no permission if user is not staff!?
1396 $this_is_staff = ($this->company_id == $owncomp->id);
1399 if (!$this_is_staff ) {
1401 // - can not change company!!!
1403 isset($changes['company_id']) &&
1404 $changes['company_id'] != $au->company_id) {
1407 // can only set new emails..
1409 !empty($this->email) &&
1410 isset($changes['email']) &&
1411 $changes['email'] != $this->email) {
1416 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1417 // ???? do we want this?
1419 // edit self... - what about other staff members...
1421 //return $this->company_id == $au->company_id;
1425 // yes, only owner company can mess with this...
1431 // extra case change passwod?
1432 case 'P': //??? password
1433 // standard perms -- for editing + if the user is dowing them selves..
1434 $ret = $this_is_staff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1435 return $ret || $au->id == $this->id; // can change own data?
1438 return $this_is_staff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1446 function beforeInsert($req, $roo)
1448 $p = DB_DataObject::factory('core_person');
1449 if ($roo->authUser->id > -1 || $p->count() > 1) {
1450 $pp = DB_DataObject::factory('core_person');
1451 $pp->email = trim($this->email);
1453 $roo->jerr("that email already exists in the database");
1459 $c = DB_DataObject::Factory('core_company');
1462 if (!$tc || $tc> 1) {
1463 $roo->jerr("can not create initial user as multiple companies already exist");
1466 $this->company_id = $c->id;
1467 $this->email = trim($this->email);
1476 function onInsert($req, $roo)
1479 $p = DB_DataObject::factory('core_person');
1480 if ($roo->authUser->id < 0 && $p->count() == 1) {
1481 // this seems a bit risky...
1483 $g = DB_DataObject::factory('core_group');
1487 $g->get('name', 'Administrators');
1489 $p = DB_DataObject::factory('core_group_member');
1490 $p->group_id = $g->id;
1491 $p->user_id = $this->id;
1494 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1498 if (!empty($req['project_id_addto'])) {
1499 $pd = DB_DataObject::factory('ProjectDirectory');
1500 $pd->project_id = $req['project_id_addto'];
1501 $pd->person_id = $this->id;
1503 $pd->office_id = $this->office_id;
1504 $pd->company_id = $this->company_id;
1507 if (!empty($req['core_person_settings'])) {
1508 $this->updateSettings($req['core_person_settings'], $roo);
1512 function onUpdate($old, $req,$roo, $event)
1514 if (!empty($req['core_person_settings'])) {
1515 $this->updateSettings($req['core_person_settings'], $roo);
1519 // there should really be a registry of valid scope values!?
1520 function updateSettings($ar, $roo)
1522 //DB_DataObject::debugLevel(1);
1524 foreach($this->settings(true) as $o) {
1525 $old[$o->scope] = $o;
1527 foreach($ar as $k=>$v) {
1528 if (isset($old[$k])) {
1529 $oo = clone($old[$k]);
1530 $old[$k]->data = $v;
1531 $old[$k]->update($oo);
1534 $cs = DB_DataObject::Factory('core_person_settings');
1536 'person_id' =>$this->id,
1542 // we dont delete old stuff....
1546 function importFromArray($roo, $persons, $opts)
1548 if (empty($opts['prefix'])) {
1549 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1552 if (!is_array($persons) || empty($persons)) {
1553 $roo->jerr("error in the person data. - empty on not valid");
1555 DB_DataObject::factory('core_group')->initGroups();
1557 foreach($persons as $person){
1558 $p = DB_DataObject::factory('core_person');
1559 if($p->get('name', $person['name'])){
1562 $p->setFrom($person);
1564 $companies = DB_DataObject::factory('core_company');
1565 if(!$companies->get('comptype', 'OWNER')){
1566 $roo->jerr("Missing OWNER companies!");
1568 $p->company_id = $companies->pid();
1569 // strip the 'spaces etc.. make lowercase..
1570 $name = strtolower(str_replace(' ', '', $person['name']));
1571 $p->setPassword("{$opts['prefix']}{$name}");
1574 // if $person->groups is set.. then
1575 // add this person to that group eg. groups : [ 'Administrator' ]
1576 if(!empty($person['groups'])){
1577 $groups = DB_DataObject::factory('core_group');
1578 if(!$groups->get('name', $person['groups'])){
1579 $roo->jerr("Missing groups : {$person['groups']}");
1581 $gm = DB_DataObject::factory('core_group_member');
1582 $gm->change($p, $groups, true);
1585 $p->onInsert(array(), $roo);
1589 // this is for the To: "{getEmailName()}" <email@address>
1590 // not good for Dear XXXX, - use {person.firstname} for that.
1591 function getEmailName()
1595 if(!empty($this->honor)){
1596 array_push($name, $this->honor);
1599 if(!empty($this->name)){
1600 array_push($name, $this->name);
1602 return implode(' ', $name);
1605 if(!empty($this->firstname) || !empty($this->lastname)){
1606 array_push($name, $this->firstname);
1607 array_push($name, $this->lastname);
1609 $name = array_filter($name);
1611 return implode(' ', $name);
1614 return $this->email;
1617 function sesPrefix()
1619 $ff= HTML_FlexyFramework::get();
1621 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1623 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1625 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1630 function loginPublic() // used where???
1632 $this->isAuth(); // force session start..
1634 $db = $this->getDatabaseConnection();
1636 $ff = HTML_FlexyFramework::get();
1638 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1642 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1644 $p = DB_DAtaObject::Factory($this->tableName());
1645 $p->get($this->pid());
1647 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1652 function beforeUpdate($old, $q, $roo)
1654 $this->email = trim($this->email);
1657 function generateOathKey()
1659 require 'Base32.php';
1661 $base32 = new Base32();
1663 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1666 function generateQRCode($hash)
1669 empty($this->email) &&
1675 $issuer = rawurlencode($this->qrCodeIssuer());
1677 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1679 require_once 'Image/QRCode.php';
1681 $qrcode = new Image_QRCode();
1683 $image = $qrcode->makeCode($uri, array(
1684 'output_type' => 'return'
1689 $base64 = base64_encode(ob_get_contents());
1692 return "data:image/png;base64,{$base64}";
1695 function qrCodeIssuer()
1697 $pg= HTML_FlexyFramework::get()->page;
1699 $issuer = (empty($pg->company->name)) ? 'ROOJS' : "{$pg->company->name}";
1704 static function test_ADMIN_PASSWORD_RESET($pg, $to)
1706 $ff = HTML_FlexyFramework::get();
1707 $person = DB_DataObject::Factory('core_person');
1711 'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1712 'person' => $person,
1713 'authFrom' => 'FAKE_LINK',
1714 'authKey' => 'FAKE_KEY',
1716 'rcpts' => $to->email,