6 * - base application setup (variables etc to javascript)
8 * - authentication and permission info about user / application
9 * - json output methods.
10 * - file upload error checking - checkFileUploadError
11 * - logging to event table
12 * - sendTemplate code (normally use the Person version for sending to specific people..)
14 * - doc managment code?? - remarks and tracking??? - MOVEME
15 * - authentication link checking?? MOVEME?
16 * - authentication reset password ?? MOVEME?
17 * ?? arrayClean.. what's it doing here?!? ;)
22 class Pman extends HTML_FlexyFramework_Page
25 var $appShortName= "";
26 var $appVersion = "1.8";
38 * ------------- Standard getAuth/get/post methods of framework.
43 function getAuth() // everyone allowed in!!!!!
45 $this->loadOwnerCompany();
53 if (isset($this->_hasInit)) {
56 $this->_hasInit = true;
58 $boot = HTML_FlexyFramework::get();
59 // echo'<PRE>';print_R($boot);exit;
60 $this->appName= $boot->appName;
61 $this->appNameShort= $boot->appNameShort;
62 $this->appModules= $boot->enable;
63 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
64 $this->appDisable = $boot->disable;
65 $this->version = $boot->version;
67 if (!empty($ff->Pman['local_autoauth']) &&
68 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
69 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
80 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
81 $bits = explode('/', $base);
83 if ($bits[0] == 'Link') {
84 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
85 header('Content-type: text/html; charset=utf-8');
88 if ($bits[0] == 'PasswordReset') {
89 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
90 header('Content-type: text/html; charset=utf-8');
95 if ($this->getAuthUser()) {
96 $this->addEvent("RELOAD");
101 $this->addEvent("BADURL", false, $base);
102 $this->jerr("invalid url");
105 if (isset($_GET['onloadTrack'])) {
106 $this->onloadTrack = (int)$_GET['onloadTrack'];
108 // getting this to work with xhtml is a nightmare
109 // = nbsp / <img> issues screw everyting up.
110 //var_dump($this->isDev);
111 // force regeneration on load for development enviroments..
112 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
114 //header('Content-type: application/xhtml+xml; charset=utf-8');
115 header('Content-type: text/html; charset=utf-8');
118 function post($base) {
119 return $this->get($base);
123 * ------------- Authentication and permission info about logged in user!!!
128 function loadOwnerCompany()
130 $this->company = DB_DataObject::Factory('Companies');
131 if ($this->company) { // non-core pman projects
134 $this->company->get('comptype', 'OWNER');
137 function staticGetAuthUser()
139 $ff = HTML_FlexyFramework::get();
140 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
142 $u = DB_DataObject::factory($tbl);
146 return $u->getAuthUser();
148 function getAuthUser()
150 if (!empty($this->authUser)) {
151 return $this->authUser;
153 $ff = HTML_FlexyFramework::get();
154 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
156 $u = DB_DataObject::factory( $tbl );
160 $this->authUser =$u->getAuthUser();
161 return $this->authUser ;
163 function hasPerm($name, $lvl) // do we have a permission
165 static $pcache = array();
166 $au = $this->getAuthUser();
167 return $au->hasPerm($name,$lvl);
170 function hasModule($name)
173 if (!strpos( $name,'.') ) {
174 // use enable / disable..
177 $enabled = array('Core') ;
178 $enabled = !empty($this->appModules) ?
179 array_merge($enabled, explode(',', $this->appModules)) :
181 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
185 return in_array($name, $enabled) && !in_array($name, $disabled);
188 $x = DB_DataObject::factory('Group_Rights');
189 $ar = $x->defaultPermData();
190 if (empty($ar[$name]) || empty($ar[$name][0])) {
200 * ---------------- Global Tools ---------------
206 * send a template to the user
207 * rcpts are read from the resulting template.
209 * @arg $templateFile - the file in mail/XXXXXX.txt
210 * @arg $args - variables available to the form as {t.*} over and above 'this'
215 function sendTemplate($templateFile, $args)
220 $content = clone($this);
222 foreach((array)$args as $k=>$v) {
225 $content->msgid = md5(time() . rand());
227 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
228 /* use the regex compiler, as it doesnt parse <tags */
229 require_once 'HTML/Template/Flexy.php';
230 $template = new HTML_Template_Flexy( array(
231 'compiler' => 'Regex',
232 'filters' => array('SimpleTags','Mail'),
236 // this should be done by having multiple template sources...!!!
238 $template->compile('mail/'. $templateFile.'.txt');
240 /* use variables from this object to ouput data. */
241 $mailtext = $template->bufferedOutputObject($content);
242 //echo "<PRE>";print_R($mailtext);
244 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
245 require_once 'Mail/mimeDecode.php';
246 require_once 'Mail.php';
248 $decoder = new Mail_mimeDecode($mailtext);
249 $parts = $decoder->getSendArray();
250 if (PEAR::isError($parts)) {
252 //echo "PROBLEM: {$parts->message}";
255 list($recipents,$headers,$body) = $parts;
256 ///$recipents = array($this->email);
257 $mailOptions = PEAR::getStaticProperty('Mail','options');
258 $mail = Mail::factory("SMTP",$mailOptions);
259 $headers['Date'] = date('r');
260 if (PEAR::isError($mail)) {
263 $oe = error_reporting(E_ALL ^ E_NOTICE);
264 $ret = $mail->send($recipents,$headers,$body);
265 error_reporting($oe);
271 function checkFileUploadError() // check for file upload errors.
274 empty($_FILES['File'])
275 || empty($_FILES['File']['name'])
276 || empty($_FILES['File']['tmp_name'])
277 || empty($_FILES['File']['type'])
278 || !empty($_FILES['File']['error'])
279 || empty($_FILES['File']['size'])
281 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
287 * generate a tempory file with an extension (dont forget to delete it)
290 function tempName($ext)
292 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
294 return $x .'.'. $ext;
297 * ------------- Authentication testing ------ ??? MOVEME?
301 function linkAuth($trid, $trkey)
303 $tr = DB_DataObject::factory('Documents_Tracking');
304 if (!$tr->get($trid)) {
305 return "Invalid URL";
307 if (strtolower($tr->authkey) != strtolower($trkey)) {
308 $this->AddEvent("ERROR-L", false, "Invalid Key");
309 return "Invalid KEY";
312 $this->onloadTrack = (int) $tr->doc_id;
313 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
314 $this->AddEvent("ERROR-L", false, "Key Expired");
315 return "Key Expired";
317 // user logged in and not
318 $au = $this->getAuthUser();
319 if ($au && $au->id && $au->id != $tr->person_id) {
322 return "Logged Out existing Session\n - reload to log in with correct key";
324 if ($au) { // logged in anyway..
325 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
326 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
331 // authenticate the user...
333 $u = DB_DataObject::factory('Person');
335 $u->get($tr->person_id);
337 $this->AddEvent("LOGIN", false, "With Key");
339 // we need to redirect out - otherwise refererer url will include key!
340 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
352 * ------------- Authentication password reset ------ ??? MOVEME?
358 function resetPassword($id,$t, $key)
361 $au = $this->getAuthUser();
363 return "Already Logged in - no need to use Password Reset";
366 $u = DB_DataObject::factory('Person');
367 //$u->company_id = $this->company->id;
369 if (!$u->get($id) || !strlen($u->passwd)) {
374 if ($key != $u->genPassKey($t)) {
375 return "invalid key";
378 $u->no_reset_sent = 0;
381 if ($t < strtotime("NOW - 1 DAY")) {
384 $this->showNewPass = implode("/", array($id,$t,$key));
390 * ---------------- Standard JSON outputers. - used everywhere
393 function jerr($str, $errors=array()) // standard error reporting..
395 require_once 'Services/JSON.php';
396 $json = new Services_JSON();
398 if (!empty($_REQUEST['returnHTML']) ||
399 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
401 header('Content-type: text/html');
402 echo "<HTML><HEAD></HEAD><BODY>";
403 echo $json->encodeUnsafe(array(
406 'message' => $str, // compate with exeption / loadexception.
408 'errors' => $errors ? $errors : true, // used by forms to flag errors.
409 'authFailure' => !empty($errors['authFailure']),
411 echo "</BODY></HTML>";
415 echo $json->encode(array(
419 'message' => $str, // compate with exeption / loadexception.
420 'errors' => $errors ? $errors : true, // used by forms to flag errors.
421 'authFailure' => !empty($errors['authFailure']),
429 require_once 'Services/JSON.php';
430 $json = new Services_JSON();
432 if (!empty($_REQUEST['returnHTML']) ||
433 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
436 header('Content-type: text/html');
437 echo "<HTML><HEAD></HEAD><BODY>";
438 echo $json->encodeUnsafe(array('success'=> true, 'data' => $str));
439 echo "</BODY></HTML>";
444 echo $json->encode(array('success'=> true, 'data' => $str));
449 * output data for grids or tree
450 * @ar {Array} ar Array of data
451 * @total {Number|false} total number of records (or false to return count(ar)
452 * @extra {Array} extra key value list of data to pass as extra data.
455 function jdata($ar,$total=false, $extra=array())
457 // should do mobile checking???
458 if ($total == false) {
461 $extra= $extra ? $extra : array();
462 require_once 'Services/JSON.php';
463 $json = new Services_JSON();
464 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
475 * ---------------- Page output?!?!?
479 function hasBg($fn) // used on front page to check if logos exist..
481 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
484 function outputJavascriptIncludes() // includes on devel version..
487 $mods = explode(',', $this->appModules);
488 array_unshift($mods, 'Core');
489 $mods = array_unique($mods);
492 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
494 foreach($mods as $mod) {
495 // add the css file..
496 if (in_array($mod, $disabled)) {
501 $files = $this->moduleJavascriptList($mod.'/widgets');
502 foreach($files as $f) {
503 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
506 $files = $this->moduleJavascriptList($mod);
507 foreach($files as $f) {
508 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
515 function outputCSSIncludes() // includes on CSS links.
518 $mods = explode(',', $this->appModules);
519 array_unshift($mods, 'Core');
520 $mods = array_unique($mods);
522 foreach($mods as $mod) {
523 // add the css file..
524 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
525 if (file_exists( $css)){
526 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
527 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
538 function moduleJavascriptList($mod)
541 $ff = HTML_FlexyFramework::get();
543 $dir = $this->rootDir.'/Pman/'. $mod;
545 $path = $this->rootURL."/Pman/$mod/";
546 $base = dirname($_SERVER['SCRIPT_FILENAME']);
547 $cfile = realpath($base .'/_compiled_/' . $mod);
548 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
550 if (!file_exists($dir)) {
558 if (file_exists($cfile)) {
559 // $ctime = max(filemtime($cfile), filectime($cfile));
560 // otherwise use compile dfile..
562 $ar = glob($cfile . '/' . $mod . '*.js');
563 // default to first..
564 $cfile = basename($ar[count($ar) -1]);
565 foreach($ar as $fn) {
566 if (filemtime($fn) > $maxm) {
567 $cfile = basename($fn);
568 $maxm = filemtime($fn);
574 $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
575 if (file_exists($lfile)) {
576 array_push($files, $this->rootURL."/_translations_/$mod.js");
580 // works out if stuff has been updated..
581 // technically the non-dev version should output compiled only?!!?
583 while (false !== ($f = readdir($dh))) {
585 if (!preg_match('/\.js$/', $f)) {
588 // got the 'module file..'
590 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
591 $files[] = $path . $f;
596 // var_dump(array($maxtime , $ctime));
597 //if ($maxtime > $ctime) {
598 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
599 usort($files, $lsort);
600 // if (file_exists($lfile)) {
601 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
612 * ---------------- Logging ---------------
619 function addEvent($act, $obj = false, $remarks = '') {
620 $au = $this->getAuthUser();
621 $e = DB_DataObject::factory('Events');
623 if (is_a($e, 'PEAR_Error')) {
624 return; // no event table!
626 $e->person_name = $au ? $au->name : '';
627 $e->person_id = $au ? $au->id : '';
628 $e->event_when = date('Y-m-d H:i:s');
629 $e->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
631 $e->on_table = $obj ? $obj->tableName() : '';
633 $pk = $obj ? $obj->keys() : false;
635 $e->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
636 $e->remarks = $remarks;
638 $ff = HTML_FlexyFramework::get();
639 if (empty($ff->Pman['event_log_dir'])) {
642 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
643 if (!file_exists(dirname($file))) {
644 mkdir(dirname($file),0700,true);
646 file_put_contents($file, var_export(array(
647 'REQUEST_URI' => $_SERVER['REQUEST_URI'],
648 'GET' => empty($_GET) ? array() : $_GET,
649 'POST' => empty($_POST) ? array() : $_POST,