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?!? ;)
20 * DB_DataObject*:*toEventString (for logging - this is generically prefixed to all database operations.)
21 * - any data object where this method exists, the result will get prefixed to the log remarks
24 class Pman extends HTML_FlexyFramework_Page
27 var $appShortName= "";
28 var $appVersion = "1.8";
40 * ------------- Standard getAuth/get/post methods of framework.
45 function getAuth() // everyone allowed in!!!!!
47 $this->loadOwnerCompany();
55 if (isset($this->_hasInit)) {
58 $this->_hasInit = true;
60 $boot = HTML_FlexyFramework::get();
61 // echo'<PRE>';print_R($boot);exit;
62 $this->appName= $boot->appName;
63 $this->appNameShort= $boot->appNameShort;
64 $this->appModules= $boot->enable;
65 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
66 $this->appDisable = $boot->disable;
67 $this->version = $boot->version;
69 if (!empty($ff->Pman['local_autoauth']) &&
70 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
71 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
82 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
83 $bits = explode('/', $base);
85 if ($bits[0] == 'Link') {
86 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
87 header('Content-type: text/html; charset=utf-8');
90 if ($bits[0] == 'PasswordReset') {
91 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
92 header('Content-type: text/html; charset=utf-8');
97 if ($this->getAuthUser()) {
98 $this->addEvent("RELOAD");
103 $this->addEvent("BADURL", false, $base);
104 $this->jerr("invalid url");
107 if (isset($_GET['onloadTrack'])) {
108 $this->onloadTrack = (int)$_GET['onloadTrack'];
110 // getting this to work with xhtml is a nightmare
111 // = nbsp / <img> issues screw everyting up.
112 //var_dump($this->isDev);
113 // force regeneration on load for development enviroments..
114 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
116 //header('Content-type: application/xhtml+xml; charset=utf-8');
117 header('Content-type: text/html; charset=utf-8');
120 function post($base) {
121 return $this->get($base);
125 * ------------- Authentication and permission info about logged in user!!!
130 function loadOwnerCompany()
132 $this->company = DB_DataObject::Factory('Companies');
133 if ($this->company) { // non-core pman projects
136 $this->company->get('comptype', 'OWNER');
139 function staticGetAuthUser()
141 $ff = HTML_FlexyFramework::get();
142 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
144 $u = DB_DataObject::factory($tbl);
148 return $u->getAuthUser();
150 function getAuthUser()
152 if (!empty($this->authUser)) {
153 return $this->authUser;
155 $ff = HTML_FlexyFramework::get();
156 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
158 $u = DB_DataObject::factory( $tbl );
162 $this->authUser =$u->getAuthUser();
163 return $this->authUser ;
165 function hasPerm($name, $lvl) // do we have a permission
167 static $pcache = array();
168 $au = $this->getAuthUser();
169 return $au->hasPerm($name,$lvl);
173 function modules($with_component=false)
175 // appModules/appDisable contain a comma limited list of
176 // both modules and components that can be enabled/disabled..
178 // the modules call just lists the modules
179 $enabled = array('Core');
180 $am = !empty($this->appModules) ? explode(',', $this->appModules) : array();
182 if (!$with_component && strpos( $k ,'.') ) {
187 $enabled = !empty($this->appModules) ?
188 array_merge($enabled, explode(',', $this->appModules)) :
190 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
194 return in_array($name, $enabled) && !in_array($name, $disabled);
197 function hasModule($name)
200 if (!strpos( $name,'.') ) {
201 // use enable / disable..
204 $enabled = array('Core') ;
205 $enabled = !empty($this->appModules) ?
206 array_merge($enabled, explode(',', $this->appModules)) :
208 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
212 return in_array($name, $enabled) && !in_array($name, $disabled);
215 $x = DB_DataObject::factory('Group_Rights');
216 $ar = $x->defaultPermData();
217 if (empty($ar[$name]) || empty($ar[$name][0])) {
227 * ---------------- Global Tools ---------------
233 * send a template to the user
234 * rcpts are read from the resulting template.
236 * @arg $templateFile - the file in mail/XXXXXX.txt
237 * @arg $args - variables available to the form as {t.*} over and above 'this'
242 function sendTemplate($templateFile, $args)
247 $content = clone($this);
249 foreach((array)$args as $k=>$v) {
252 $content->msgid = md5(time() . rand());
254 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
255 /* use the regex compiler, as it doesnt parse <tags */
256 require_once 'HTML/Template/Flexy.php';
257 $template = new HTML_Template_Flexy( array(
258 'compiler' => 'Regex',
259 'filters' => array('SimpleTags','Mail'),
263 // this should be done by having multiple template sources...!!!
265 $template->compile('mail/'. $templateFile.'.txt');
267 /* use variables from this object to ouput data. */
268 $mailtext = $template->bufferedOutputObject($content);
269 //echo "<PRE>";print_R($mailtext);
271 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
272 require_once 'Mail/mimeDecode.php';
273 require_once 'Mail.php';
275 $decoder = new Mail_mimeDecode($mailtext);
276 $parts = $decoder->getSendArray();
277 if (PEAR::isError($parts)) {
279 //echo "PROBLEM: {$parts->message}";
282 list($recipents,$headers,$body) = $parts;
283 ///$recipents = array($this->email);
284 $mailOptions = PEAR::getStaticProperty('Mail','options');
285 $mail = Mail::factory("SMTP",$mailOptions);
286 $headers['Date'] = date('r');
287 if (PEAR::isError($mail)) {
290 $oe = error_reporting(E_ALL ^ E_NOTICE);
291 $ret = $mail->send($recipents,$headers,$body);
292 error_reporting($oe);
298 function checkFileUploadError() // check for file upload errors.
301 empty($_FILES['File'])
302 || empty($_FILES['File']['name'])
303 || empty($_FILES['File']['tmp_name'])
304 || empty($_FILES['File']['type'])
305 || !empty($_FILES['File']['error'])
306 || empty($_FILES['File']['size'])
308 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
314 * generate a tempory file with an extension (dont forget to delete it)
317 function tempName($ext)
319 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
321 return $x .'.'. $ext;
324 * ------------- Authentication testing ------ ??? MOVEME?
328 function linkAuth($trid, $trkey)
330 $tr = DB_DataObject::factory('Documents_Tracking');
331 if (!$tr->get($trid)) {
332 return "Invalid URL";
334 if (strtolower($tr->authkey) != strtolower($trkey)) {
335 $this->AddEvent("ERROR-L", false, "Invalid Key");
336 return "Invalid KEY";
339 $this->onloadTrack = (int) $tr->doc_id;
340 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
341 $this->AddEvent("ERROR-L", false, "Key Expired");
342 return "Key Expired";
344 // user logged in and not
345 $au = $this->getAuthUser();
346 if ($au && $au->id && $au->id != $tr->person_id) {
349 return "Logged Out existing Session\n - reload to log in with correct key";
351 if ($au) { // logged in anyway..
352 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
353 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
358 // authenticate the user...
360 $u = DB_DataObject::factory('Person');
362 $u->get($tr->person_id);
364 $this->AddEvent("LOGIN", false, "With Key");
366 // we need to redirect out - otherwise refererer url will include key!
367 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
379 * ------------- Authentication password reset ------ ??? MOVEME?
385 function resetPassword($id,$t, $key)
388 $au = $this->getAuthUser();
390 return "Already Logged in - no need to use Password Reset";
393 $u = DB_DataObject::factory('Person');
394 //$u->company_id = $this->company->id;
396 if (!$u->get($id) || !strlen($u->passwd)) {
401 if ($key != $u->genPassKey($t)) {
402 return "invalid key";
405 $u->no_reset_sent = 0;
408 if ($t < strtotime("NOW - 1 DAY")) {
411 $this->showNewPass = implode("/", array($id,$t,$key));
417 * ---------------- Standard JSON outputers. - used everywhere
420 function jerr($str, $errors=array()) // standard error reporting..
422 require_once 'Services/JSON.php';
423 $json = new Services_JSON();
426 $this->addEvent("ERROR", false, $str);
428 if (!empty($_REQUEST['returnHTML']) ||
429 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
431 header('Content-type: text/html');
432 echo "<HTML><HEAD></HEAD><BODY>";
433 echo $json->encodeUnsafe(array(
436 'message' => $str, // compate with exeption / loadexception.
438 'errors' => $errors ? $errors : true, // used by forms to flag errors.
439 'authFailure' => !empty($errors['authFailure']),
441 echo "</BODY></HTML>";
445 echo $json->encode(array(
449 'message' => $str, // compate with exeption / loadexception.
450 'errors' => $errors ? $errors : true, // used by forms to flag errors.
451 'authFailure' => !empty($errors['authFailure']),
459 require_once 'Services/JSON.php';
460 $json = new Services_JSON();
462 if (!empty($_REQUEST['returnHTML']) ||
463 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
466 header('Content-type: text/html');
467 echo "<HTML><HEAD></HEAD><BODY>";
468 echo $json->encodeUnsafe(array('success'=> true, 'data' => $str));
469 echo "</BODY></HTML>";
474 echo $json->encode(array('success'=> true, 'data' => $str));
479 * output data for grids or tree
480 * @ar {Array} ar Array of data
481 * @total {Number|false} total number of records (or false to return count(ar)
482 * @extra {Array} extra key value list of data to pass as extra data.
485 function jdata($ar,$total=false, $extra=array())
487 // should do mobile checking???
488 if ($total == false) {
491 $extra= $extra ? $extra : array();
492 require_once 'Services/JSON.php';
493 $json = new Services_JSON();
494 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
505 * ---------------- Page output?!?!?
509 function hasBg($fn) // used on front page to check if logos exist..
511 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
514 function outputJavascriptIncludes() // includes on devel version..
517 $mods = explode(',', $this->appModules);
518 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
519 array_unshift($mods, 'Core');
522 $mods = array_unique($mods);
524 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
526 foreach($mods as $mod) {
527 // add the css file..
528 if (in_array($mod, $disabled)) {
533 $files = $this->moduleJavascriptList($mod.'/widgets');
534 foreach($files as $f) {
535 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
538 $files = $this->moduleJavascriptList($mod);
539 foreach($files as $f) {
540 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
547 function outputCSSIncludes() // includes on CSS links.
550 $mods = explode(',', $this->appModules);
551 array_unshift($mods, 'Core');
552 $mods = array_unique($mods);
554 foreach($mods as $mod) {
555 // add the css file..
556 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
557 if (file_exists( $css)){
558 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
559 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
570 function moduleJavascriptList($mod)
573 $ff = HTML_FlexyFramework::get();
575 $dir = $this->rootDir.'/Pman/'. $mod;
577 $path = $this->rootURL."/Pman/$mod/";
578 $base = dirname($_SERVER['SCRIPT_FILENAME']);
579 $cfile = realpath($base .'/_compiled_/' . $mod);
580 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
582 if (!file_exists($dir)) {
590 if (file_exists($cfile)) {
591 // $ctime = max(filemtime($cfile), filectime($cfile));
592 // otherwise use compile dfile..
594 $ar = glob($cfile . '/' . $mod . '*.js');
595 // default to first..
596 $cfile = basename($ar[count($ar) -1]);
597 foreach($ar as $fn) {
598 if (filemtime($fn) > $maxm) {
599 $cfile = basename($fn);
600 $maxm = filemtime($fn);
606 $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
607 if (file_exists($lfile)) {
608 array_push($files, $this->rootURL."/_translations_/$mod.js");
612 // works out if stuff has been updated..
613 // technically the non-dev version should output compiled only?!!?
615 while (false !== ($f = readdir($dh))) {
617 if (!preg_match('/\.js$/', $f)) {
620 // got the 'module file..'
622 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
623 $files[] = $path . $f;
628 // var_dump(array($maxtime , $ctime));
629 //if ($maxtime > $ctime) {
630 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
631 usort($files, $lsort);
632 // if (file_exists($lfile)) {
633 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
644 * ---------------- Logging ---------------
649 * Log an action (only if it has not been logged already.
651 * @param {String} action - group/name of event
652 * @param {DataObject|false} obj - dataobject action occured on.
653 * @param {String} any remarks
656 function addEventOnce($act, $obj = false, $remarks = '')
658 $au = $this->getAuthUser();
659 $e = DB_DataObject::factory('Events');
660 $e->init($act,$obj,$remarks);
661 if ($e->find(true)) {
664 $this->addEvent($act, $obj, $remarks);
670 * @param {String} action - group/name of event
671 * @param {DataObject|false} obj - dataobject action occured on.
672 * @param {String} any remarks
675 function addEvent($act, $obj = false, $remarks = '')
677 $au = $this->getAuthUser();
678 $e = DB_DataObject::factory('Events');
679 $e->init($act,$obj,$remarks);
681 $e->event_when = date('Y-m-d H:i:s');
684 $ff = HTML_FlexyFramework::get();
685 if (empty($ff->Pman['event_log_dir'])) {
688 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
689 if (!file_exists(dirname($file))) {
690 mkdir(dirname($file),0700,true);
692 file_put_contents($file, var_export(array(
693 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
694 'GET' => empty($_GET) ? array() : $_GET,
695 'POST' => empty($_POST) ? array() : $_POST,