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
28 var $appShortName= "";
29 var $appVersion = "1.8";
36 var $appDisabled = array(); // array of disabled modules..
37 // (based on config option disable)
39 var $authUser; // always contains the authenticated user..
44 * ------------- Standard getAuth/get/post methods of framework.
49 function getAuth() // everyone allowed in!!!!!
51 $this->loadOwnerCompany();
59 if (isset($this->_hasInit)) {
62 $this->_hasInit = true;
64 $boot = HTML_FlexyFramework::get();
65 // echo'<PRE>';print_R($boot);exit;
66 $this->appName= $boot->appName;
67 $this->appNameShort= $boot->appNameShort;
70 $this->appModules= $boot->enable;
71 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
72 $this->appDisable = $boot->disable;
73 $this->appDisabled = explode(',', $boot->disable);
74 $this->version = $boot->version;
76 if (!empty($ff->Pman['local_autoauth']) &&
77 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
78 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
91 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
92 $bits = explode('/', $base);
94 if ($bits[0] == 'Link') {
95 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
96 header('Content-type: text/html; charset=utf-8');
99 if ($bits[0] == 'PasswordReset') {
100 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
101 header('Content-type: text/html; charset=utf-8');
106 if ($this->getAuthUser()) {
107 $this->addEvent("RELOAD");
112 $this->addEvent("BADURL", false, $base);
113 $this->jerr("invalid url");
116 if (isset($_GET['onloadTrack'])) {
117 $this->onloadTrack = (int)$_GET['onloadTrack'];
119 // getting this to work with xhtml is a nightmare
120 // = nbsp / <img> issues screw everyting up.
121 //var_dump($this->isDev);
122 // force regeneration on load for development enviroments..
124 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
126 //header('Content-type: application/xhtml+xml; charset=utf-8');
130 if ($this->company->logo_id) {
131 $im = DB_DataObject::Factory('Images');
132 $im->get($this->company->logo_id);
133 $this->appLogo = $this->baseURL . '/Images/Thumb/400x100/'. $this->company->logo_id .'/' . $im->filename;
136 header('Content-type: text/html; charset=utf-8');
139 function post($base) {
140 return $this->get($base);
144 // --------------- AUTHENTICATION or system information
147 * finds the compay with comptype=='OWNER'
149 * @return {Pman_Core_DataObjects_Companies} the owner company
151 function loadOwnerCompany()
154 $this->company = DB_DataObject::Factory('Companies');
155 if (!is_a($this->company, 'DB_DataObject')) { // non-core pman projects
158 $this->company->get('comptype', 'OWNER');
159 return $this->company;
165 * getAuthUser: - get the authenticated user..
167 * @return {DB_DataObject} of type Pman[authTable] if authenticated.
170 function getAuthUser()
172 if (!empty($this->authUser)) {
173 return $this->authUser;
175 $ff = HTML_FlexyFramework::get();
176 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
178 $u = DB_DataObject::factory( $tbl );
182 $this->authUser =$u->getAuthUser();
183 return $this->authUser ;
187 * wrapper arround authuser->hasPerm
188 * @see Pman_Core_DataObjects_User::hasPerm
190 * @param {String} $name The permission name (eg. Projects.List)
191 * @param {String} $lvl eg. (C)reate (E)dit (D)elete ... etc.
194 function hasPerm($name, $lvl) // do we have a permission
196 static $pcache = array();
197 $au = $this->getAuthUser();
198 return $au && $au->hasPerm($name,$lvl);
203 * modulesList: List the modules in the application
205 * @return {Array} list of modules
207 function modulesList()
211 $mods = explode(',', $this->appModules);
212 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
213 array_unshift($mods, 'Core');
216 $mods = array_unique($mods);
218 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
220 foreach($mods as $mod) {
221 // add the css file..
222 if (in_array($mod, $disabled)) {
233 function hasModule($name)
236 if (!strpos( $name,'.') ) {
237 // use enable / disable..
238 return in_array($name, $this->modules());
241 $x = DB_DataObject::factory('Group_Rights');
242 $ar = $x->defaultPermData();
243 if (empty($ar[$name]) || empty($ar[$name][0])) {
254 * ---------------- Global Tools ---------------
260 * send a template to the user
261 * rcpts are read from the resulting template.
263 * @arg $templateFile - the file in mail/XXXXXX.txt
264 * @arg $args - variables available to the form as {t.*} over and above 'this'
269 function sendTemplate($templateFile, $args)
274 $content = clone($this);
276 foreach((array)$args as $k=>$v) {
279 $content->msgid = md5(time() . rand());
281 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
282 /* use the regex compiler, as it doesnt parse <tags */
283 require_once 'HTML/Template/Flexy.php';
284 $template = new HTML_Template_Flexy( array(
285 'compiler' => 'Regex',
286 'filters' => array('SimpleTags','Mail'),
290 // this should be done by having multiple template sources...!!!
292 $template->compile('mail/'. $templateFile.'.txt');
294 /* use variables from this object to ouput data. */
295 $mailtext = $template->bufferedOutputObject($content);
296 //echo "<PRE>";print_R($mailtext);
298 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
299 require_once 'Mail/mimeDecode.php';
300 require_once 'Mail.php';
302 $decoder = new Mail_mimeDecode($mailtext);
303 $parts = $decoder->getSendArray();
304 if (PEAR::isError($parts)) {
306 //echo "PROBLEM: {$parts->message}";
309 list($recipents,$headers,$body) = $parts;
310 ///$recipents = array($this->email);
311 $mailOptions = PEAR::getStaticProperty('Mail','options');
312 $mail = Mail::factory("SMTP",$mailOptions);
313 $headers['Date'] = date('r');
314 if (PEAR::isError($mail)) {
317 $oe = error_reporting(E_ALL ^ E_NOTICE);
318 $ret = $mail->send($recipents,$headers,$body);
319 error_reporting($oe);
325 function checkFileUploadError() // check for file upload errors.
328 empty($_FILES['File'])
329 || empty($_FILES['File']['name'])
330 || empty($_FILES['File']['tmp_name'])
331 || empty($_FILES['File']['type'])
332 || !empty($_FILES['File']['error'])
333 || empty($_FILES['File']['size'])
335 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
341 * generate a tempory file with an extension (dont forget to delete it)
344 function tempName($ext)
346 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
348 return $x .'.'. $ext;
351 * ------------- Authentication testing ------ ??? MOVEME?
355 function linkAuth($trid, $trkey)
357 $tr = DB_DataObject::factory('Documents_Tracking');
358 if (!$tr->get($trid)) {
359 return "Invalid URL";
361 if (strtolower($tr->authkey) != strtolower($trkey)) {
362 $this->AddEvent("ERROR-L", false, "Invalid Key");
363 return "Invalid KEY";
366 $this->onloadTrack = (int) $tr->doc_id;
367 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
368 $this->AddEvent("ERROR-L", false, "Key Expired");
369 return "Key Expired";
371 // user logged in and not
372 $au = $this->getAuthUser();
373 if ($au && $au->id && $au->id != $tr->person_id) {
376 return "Logged Out existing Session\n - reload to log in with correct key";
378 if ($au) { // logged in anyway..
379 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
380 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
385 // authenticate the user...
387 $u = DB_DataObject::factory('Person');
389 $u->get($tr->person_id);
391 $this->AddEvent("LOGIN", false, "With Key");
393 // we need to redirect out - otherwise refererer url will include key!
394 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
406 * ------------- Authentication password reset ------ ??? MOVEME?
412 function resetPassword($id,$t, $key)
415 $au = $this->getAuthUser();
417 return "Already Logged in - no need to use Password Reset";
420 $u = DB_DataObject::factory('Person');
421 //$u->company_id = $this->company->id;
423 if (!$u->get($id) || !strlen($u->passwd)) {
428 if ($key != $u->genPassKey($t)) {
429 return "invalid key";
432 $u->no_reset_sent = 0;
435 if ($t < strtotime("NOW - 1 DAY")) {
438 $this->showNewPass = implode("/", array($id,$t,$key));
443 * jerrAuth: standard auth failure - with data that let's the UI know..
447 $au = $this->authUser();
449 // is it an authfailure?
450 $this->jerr("Permission denied to view this resource", array('authFailure' => true));
452 $this->jerr("Not authenticated", array('authFailure' => true));
458 * ---------------- Standard JSON outputers. - used everywhere
461 function jerr($str, $errors=array()) // standard error reporting..
464 $cli = HTML_FlexyFramework::get()->cli;
466 echo "ERROR:\n" .$str . "\n";
470 require_once 'Services/JSON.php';
471 $json = new Services_JSON();
474 $this->addEvent("ERROR", false, $str);
476 if (!empty($_REQUEST['returnHTML']) ||
477 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
479 header('Content-type: text/html');
480 echo "<HTML><HEAD></HEAD><BODY>";
481 echo $json->encodeUnsafe(array(
484 'message' => $str, // compate with exeption / loadexception.
486 'errors' => $errors ? $errors : true, // used by forms to flag errors.
487 'authFailure' => !empty($errors['authFailure']),
489 echo "</BODY></HTML>";
493 echo $json->encode(array(
497 'message' => $str, // compate with exeption / loadexception.
498 'errors' => $errors ? $errors : true, // used by forms to flag errors.
499 'authFailure' => !empty($errors['authFailure']),
507 require_once 'Services/JSON.php';
508 $json = new Services_JSON();
510 if (!empty($_REQUEST['returnHTML']) ||
511 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
514 header('Content-type: text/html');
515 echo "<HTML><HEAD></HEAD><BODY>";
516 // encode html characters so they can be read..
517 echo str_replace(array('<','>'), array('\u003c','\u003e'),
518 $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
519 echo "</BODY></HTML>";
524 echo $json->encode(array('success'=> true, 'data' => $str));
529 * output data for grids or tree
530 * @ar {Array} ar Array of data
531 * @total {Number|false} total number of records (or false to return count(ar)
532 * @extra {Array} extra key value list of data to pass as extra data.
535 function jdata($ar,$total=false, $extra=array())
537 // should do mobile checking???
538 if ($total == false) {
541 $extra= $extra ? $extra : array();
542 require_once 'Services/JSON.php';
543 $json = new Services_JSON();
544 if (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE'])) {
546 header('Content-type: text/html');
547 echo "<HTML><HEAD></HEAD><BODY>";
548 // encode html characters so they can be read..
549 echo str_replace(array('<','>'), array('\u003c','\u003e'),
550 $json->encodeUnsafe(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra));
551 echo "</BODY></HTML>";
561 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
571 * ---------------- OUTPUT
573 function hasBg($fn) // used on front page to check if logos exist..
575 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
578 * outputJavascriptIncludes:
580 * output <script....> for all the modules in the applcaiton
583 function outputJavascriptIncludes() // includes on devel version..
586 $mods = $this->modulesList();
588 foreach($mods as $mod) {
589 // add the css file..
592 $files = $this->moduleJavascriptList($mod.'/widgets');
593 foreach($files as $f) {
594 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
597 $files = $this->moduleJavascriptList($mod);
598 foreach($files as $f) {
599 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
608 * output <link rel=stylesheet......> for all the modules in the applcaiton
611 function outputCSSIncludes() // includes on CSS links.
614 $mods = $this->modulesList();
617 foreach($mods as $mod) {
618 // add the css file..
619 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
620 if (file_exists( $css)){
621 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
622 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
631 * Gather infor for javascript files..
633 * @param {String} $mod the module to get info about.
634 * @return {StdClass} details about module.
636 function moduleJavascriptFilesInfo($mod)
639 static $cache = array();
641 if (isset($cache[$mod])) {
646 $ff = HTML_FlexyFramework::get();
648 $base = dirname($_SERVER['SCRIPT_FILENAME']);
649 $dir = $this->rootDir.'/Pman/'. $mod;
650 $path = $this->rootURL ."/Pman/$mod/";
652 $ar = glob($dir . '/*.js');
658 foreach($ar as $fn) {
660 // got the 'module file..'
661 $mtime = filemtime($dir . '/'. $f);
662 $maxtime = max($mtime, $maxtime);
663 $arfiles[$fn] = $mtime;
664 $files[] = $path . $f . '?ts='.$mtime;
667 ksort($arfiles); // just sort by name so it's consistant for serialize..
669 $compile = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
670 $basedir = $ff->Pman['public_cache_dir'];
671 $baseurl = $ff->Pman['public_cache_url'];
673 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
674 usort($files, $lsort);
676 $smod = str_replace('/','.',$mod);
678 $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
680 $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
681 ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
683 $cache[$mod] = (object) array(
684 'smod' => $smod, // module name without '/'
685 'files' => $files, // list of all files.
686 'filesmtime' => $arfiles, // map of mtime=>file
687 'maxtime' => $maxtime, // max mtime
688 'compile' => $this->isDev ? false : $compile,
689 'translation_file' => $base .'/_translations_/' . $smod . '.js',
690 'translation_mtime' => $tmtime,
692 'translation_data' => preg_replace('/\.js$/', '.__translation__.js', $output),
693 'translation_base' => $dir .'/', //prefix of filename (without moudle name))
694 'basedir' => $basedir,
695 'baseurl' => $baseurl,
696 'module_dir' => $dir,
703 * moduleJavascriptList: list the javascript files in a module
705 * The original version of this.. still needs more thought...
707 * Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
708 * Translations are in Pman/_translations_/{$mod}.js
710 * if that stuff does not exist just list files in Pman/{$mod}/*.js
712 * Compiled could be done on the fly..
716 * @param {String} $mod the module to look at - eg. Pman/{$mod}/*.js
717 * @return {Array} list of include paths (either compiled or raw)
723 function moduleJavascriptList($mod)
727 $dir = $this->rootDir.'/Pman/'. $mod;
730 if (!file_exists($dir)) {
731 echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
735 $info = $this->moduleJavascriptFilesInfo($mod);
739 if (empty($info->files)) {
742 // finally sort the files, so they are in the right order..
744 // only compile this stuff if public_cache is set..
748 // public_cache_dir = /var/www/myproject_cache
749 // public_cache_url = /myproject_cache (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
752 if (!$info->compile) {
753 echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
756 // where are we going to write all of this..
757 // This has to be done via a
758 if (!file_exists($info->basedir.'/'.$info->output)) {
759 require_once 'Pman/Core/JsCompile.php';
760 $x = new Pman_Core_JsCompile();
762 $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
765 if (file_exists($info->basedir.'/'.$info->output) &&
766 filesize($info->basedir.'/'.$info->output)) {
769 $info->baseurl.'/'. $info->output,
772 if ($info->translation_mtime) {
773 $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
780 // give up and output original files...
791 * ---------------- Logging ---------------
796 * Log an action (only if it has not been logged already.
798 * @param {String} action - group/name of event
799 * @param {DataObject|false} obj - dataobject action occured on.
800 * @param {String} any remarks
801 * @return {false|DB_DataObject} Event object.,
804 function addEventOnce($act, $obj = false, $remarks = '')
807 $e = DB_DataObject::factory('Events');
808 $e->init($act,$obj,$remarks);
809 if ($e->find(true)) {
812 return $this->addEvent($act, $obj, $remarks);
818 * @param {String} action - group/name of event
819 * @param {DataObject|false} obj - dataobject action occured on.
820 * @param {String} any remarks
821 * @return {DB_DataObject} Event object.,
824 function addEvent($act, $obj = false, $remarks = '')
826 $au = $this->getAuthUser();
828 $e = DB_DataObject::factory('Events');
829 $e->init($act,$obj,$remarks);
831 $e->event_when = date('Y-m-d H:i:s');
835 $wa = DB_DataObject::factory('core_watch');
836 $wa->notifyEvent($e); // trigger any actions..
839 $ff = HTML_FlexyFramework::get();
840 if (empty($ff->Pman['event_log_dir'])) {
843 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
844 if (!file_exists(dirname($file))) {
845 mkdir(dirname($file),0700,true);
847 file_put_contents($file, var_export(array(
848 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
849 'GET' => empty($_GET) ? array() : $_GET,
850 'POST' => empty($_POST) ? array() : $_POST,
856 // ------------------ DEPERCIATED ---
858 function modules() // DEPRECITAED
860 return $this->modulesList();
862 function staticGetAuthUser() // DEPRECIATED..
866 return $x->getAuthUser();