diff --git "a/000000.jsonl" "b/000000.jsonl" --- "a/000000.jsonl" +++ "b/000000.jsonl" @@ -1,18 +1,13 @@ -{"repo": "schamane/node-syslog", "pr_number": 34, "title": "Build an empty addon on win32", "state": "closed", "merged_at": null, "additions": 29, "deletions": 5, "files_changed": ["node-syslog.js", "test.js"], "files_before": {"node-syslog.js": "var SyslogWrapper = require('./build/Release/syslog');\n\n/*\n * export Syslog as module\n */\nmodule.exports = {\n\ninit: SyslogWrapper.init,\nlog: SyslogWrapper.log,\nsetMask: SyslogWrapper.setMask,\nclose: SyslogWrapper.close,\nversion: '1.1.7',\n\n/*\n * facilities\n */\nLOG_KERN\t\t: (0<<3),\nLOG_USER\t\t: (1<<3),\nLOG_MAIL\t\t: (2<<3),\nLOG_DAEMON\t\t: (3<<3),\nLOG_AUTH\t\t: (4<<3),\nLOG_SYSLOG\t\t: (5<<3),\nLOG_LPR\t\t\t: (6<<3),\nLOG_NEWS\t\t: (7<<3),\nLOG_UUCP\t\t: (8<<3),\nLOG_LOCAL0\t\t: (16<<3),\nLOG_LOCAL1\t\t: (17<<3),\nLOG_LOCAL2\t\t: (18<<3),\nLOG_LOCAL3\t\t: (19<<3),\nLOG_LOCAL4\t\t: (20<<3),\nLOG_LOCAL5\t\t: (21<<3),\nLOG_LOCAL6\t\t: (22<<3),\nLOG_LOCAL7\t\t: (23<<3),\n\n/*\n * option flag for openlog\n */\nLOG_PID\t\t\t: 0x01,\nLOG_CONS\t\t: 0x02,\nLOG_ODELAY\t\t: 0x04,\nLOG_NDELAY\t\t: 0x08,\nLOG_NOWAIT\t\t: 0x10,\nLOG_PERROR\t\t: 0x20,\n/*\n * priorities\n */\nLOG_EMERG\t\t: 0,\nLOG_ALERT\t\t: 1,\nLOG_CRIT\t\t: 2,\nLOG_ERR\t\t\t: 3,\nLOG_WARNING\t\t: 4,\nLOG_NOTICE\t\t: 5,\nLOG_INFO\t\t: 6,\nLOG_DEBUG\t\t: 7\n};\n\n/*\n * Attach destroy handling\n *\n * XXX(sam) consider using AtExit: joyent/node#e4a8d261\n */\nprocess.on('exit', function() {\n\tSyslogWrapper.close();\n});\n", "test.js": "var assert = require('assert');\nvar Syslog = require('./node-syslog');\n\nassert.throws(function() {\n Syslog.init();\n}, Error);\n\nSyslog.init(\"node-syslog-test\", Syslog.LOG_PID | Syslog.LOG_ODELAY, Syslog.LOG_LOCAL0);\nSyslog.log(Syslog.LOG_INFO, \"news info log test\");\nSyslog.log(Syslog.LOG_ERR, \"news log error test\");\nSyslog.log(Syslog.LOG_DEBUG, \"Last log message as debug: \" + new Date());\nSyslog.close();\n\nconsole.log('PASS');\n"}, "files_after": {"node-syslog.js": "var SyslogWrapper = require('./build/Release/syslog');\n\n/*\n * export Syslog as module\n */\nmodule.exports = {\n\ninit: SyslogWrapper.init,\nlog: SyslogWrapper.log,\nsetMask: SyslogWrapper.setMask,\nclose: SyslogWrapper.close,\nversion: '1.1.7',\n\n/*\n * facilities\n */\nLOG_KERN\t\t: (0<<3),\nLOG_USER\t\t: (1<<3),\nLOG_MAIL\t\t: (2<<3),\nLOG_DAEMON\t\t: (3<<3),\nLOG_AUTH\t\t: (4<<3),\nLOG_SYSLOG\t\t: (5<<3),\nLOG_LPR\t\t\t: (6<<3),\nLOG_NEWS\t\t: (7<<3),\nLOG_UUCP\t\t: (8<<3),\nLOG_LOCAL0\t\t: (16<<3),\nLOG_LOCAL1\t\t: (17<<3),\nLOG_LOCAL2\t\t: (18<<3),\nLOG_LOCAL3\t\t: (19<<3),\nLOG_LOCAL4\t\t: (20<<3),\nLOG_LOCAL5\t\t: (21<<3),\nLOG_LOCAL6\t\t: (22<<3),\nLOG_LOCAL7\t\t: (23<<3),\n\n/*\n * option flag for openlog\n */\nLOG_PID\t\t\t: 0x01,\nLOG_CONS\t\t: 0x02,\nLOG_ODELAY\t\t: 0x04,\nLOG_NDELAY\t\t: 0x08,\nLOG_NOWAIT\t\t: 0x10,\nLOG_PERROR\t\t: 0x20,\n/*\n * priorities\n */\nLOG_EMERG\t\t: 0,\nLOG_ALERT\t\t: 1,\nLOG_CRIT\t\t: 2,\nLOG_ERR\t\t\t: 3,\nLOG_WARNING\t\t: 4,\nLOG_NOTICE\t\t: 5,\nLOG_INFO\t\t: 6,\nLOG_DEBUG\t\t: 7\n};\n\n/*\n * Attach destroy handling\n *\n * XXX(sam) consider using AtExit: joyent/node#e4a8d261\n */\nif (SyslogWrapper.close) {\n\tprocess.on('exit', function() {\n\t\tSyslogWrapper.close();\n\t});\n}\n", "test.js": "var assert = require('assert');\nvar Syslog = require('./node-syslog');\n\nif (process.platform == \"win32\") {\n assert(Syslog.init === undefined);\n console.log('PASS');\n return;\n}\n\nassert.throws(function() {\n Syslog.init();\n}, Error);\n\nSyslog.init(\"node-syslog-test\", Syslog.LOG_PID | Syslog.LOG_ODELAY, Syslog.LOG_LOCAL0);\nSyslog.log(Syslog.LOG_INFO, \"news info log test\");\nSyslog.log(Syslog.LOG_ERR, \"news log error test\");\nSyslog.log(Syslog.LOG_DEBUG, \"Last log message as debug: \" + new Date());\nSyslog.close();\n\nconsole.log('PASS');\n"}} -{"repo": "trel/MPACT", "pr_number": 1, "title": "Php7", "state": "closed", "merged_at": "2021-05-07T04:46:11Z", "additions": 483, "deletions": 431, "files_changed": ["mpact.php", "mpact_include.php"], "files_before": {"mpact.php": " \"N/A\",\n \"-1\" => \"N/A\",\n \"0\" => \"Incomplete - Not_Inspected\",\n \"1\" => \"Incomplete - Inspected\",\n \"2\" => \"Incomplete - Ambiguous\",\n \"3\" => \"Complete - Except Indecipherables\",\n \"4\" => \"Fully Complete\"\n);\n\n$inspectioncodes = array(\n NULL => \"N/A\",\n \"0\" => \"No\",\n \"1\" => \"Yes\"\n);\n\n$degree_types = array(\n \"Unknown\",\n \"Unknown - Investigated\",\n \"A.L.A.\",\n \"B.A.\",\n \"B.S.\",\n \"B.L.S.\",\n \"L.L.B.\",\n \"H.A.\",\n \"M.A.\",\n \"M.S.\",\n \"M.F.A.\",\n \"M.P.A.\",\n \"D.E.A.\",\n \"Ed.M.\",\n \"F.L.A. (by thesis)\",\n \"LL.M.\",\n \"LL.D.\",\n \"M.L.S.\",\n \"D.S.N.\",\n \"D.S.W.\",\n \"D.Engr.\",\n \"D.Lib.\",\n \"Ed.D.\",\n \"Th.D.\",\n \"Pharm.D.\",\n \"D.Sc.\",\n \"D.L.S.\",\n \"J.D.\",\n \"M.D.\",\n \"Ph.D.\"\n);\n\n// Begin Session\nsession_start();\n\n// Delete server session if client cookie doesn't exist\nif (!isset($_COOKIE['MPACT_userid'])){\n unset($_SESSION['MPACT']);\n}\n\n// Check for good cookie (and expired session) - (re)set session values accordingly\nif (isset($_COOKIE['MPACT_userid']) && !isset($_SESSION['MPACT'])){\n $query = \"SELECT id, username, fullname FROM users WHERE id='\".$_COOKIE['MPACT_userid'].\"'\";\n $result = mysql_query($query) or die(mysql_error());\n $line = mysql_fetch_array($result);\n $_SESSION['MPACT']['userid'] = $line['id'];\n $_SESSION['MPACT']['username'] = $line['username'];\n $_SESSION['MPACT']['fullname'] = $line['fullname'];\n}\n\n###############################################\n// DISPLAY SOMETHING - something from the URL\nif ($_SERVER['REQUEST_METHOD'] == 'GET')\n{\n // Display header\n xhtml_web_header();\n\n// echo \"-----\\n\";\n// print_r($_COOKIE);\n// echo \"-----\\n\";\n// print_r($_SESSION);\n// echo \"-----\\n\";\n if (isset($_GET['op']))\n {\n switch ($_GET['op'])\n {\n ###############################################\n case \"login\";\n\n $host_info = get_environment_info();\n if ($host_info['hostname'] == \"sils\"){\n # no logins here - go to dev server\n action_box(\"No Logins Here...\",2,$_SERVER['SCRIPT_NAME']);\n }\n else{\n if (!isset($_SESSION['MPACT']['userid'])){\n # login form\n echo \"

Welcome

\\n\";\n echo \"

Please login if you have an account.

\\n\";\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"

Username:

Password:

     
\\n\";\n echo \"
\";\n }\n else{\n # um, already logged in...\n action_box(\"Already Logged In...\",2,$_SERVER['SCRIPT_NAME']);\n }\n }\n\n break;\n ###############################################\n case \"logout\";\n\n setcookie('MPACT_userid',$_SESSION['MPACT']['userid'],time()-1000);\n unset($_SESSION['MPACT']);\n action_box(\"Logged Out\",2,$_SERVER['SCRIPT_NAME']);\n\n break;\n ###############################################\n case \"glossary\";\n\n if ( isset($_GET['id']) ){\n show_glossaryterm($_GET['id']);\n }\n else\n {\n show_glossary();\n }\n\n break;\n ###############################################\n case \"admin\";\n\n if (is_admin())\n {\n echo \"

Administrator Pages

\\n\";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"
\\n\";\n\n echo \"

\\n\";\n echo \"Show Logs\\n\";\n echo \"

\\n\";\n\n echo \"

\\n\";\n echo \"Show Orphans\\n\";\n echo \"
\\n\";\n echo \"Citation Correlation\\n\";\n echo \"

\\n\";\n\n echo \"

\\n\";\n echo \"People with Multiple Dissertations (Errors in DB)\\n\";\n echo \"
\\n\";\n echo \"Year 0000\\n\";\n echo \"

\\n\";\n\n echo \"

\\n\";\n echo \"Add a New Person to the Database\\n\";\n echo \"

\\n\";\n\n echo \"
\\n\";\n\n echo \"

\\n\";\n echo \"No Title/Abstract\\n\";\n echo \"
\\n\";\n echo \"LIS, No Title/Abstract\\n\";\n echo \"
\\n\";\n echo \"LIS, No Title\\n\";\n echo \"
\\n\";\n echo \"LIS, No Abstract\\n\";\n echo \"
\\n\";\n echo \"
\\n\";\n echo \"LIS, No Committee\\n\";\n echo \"

\\n\";\n\n echo \"
\\n\";\n\n echo \"

\\n\";\n echo \"LIS, Graduates By Year\\n\";\n echo \"
\\n\";\n echo \"LIS History\\n\";\n echo \"

\\n\";\n\n echo \"

\\n\";\n echo \"LIS Professors Summary\\n\";\n echo \"
\\n\";\n echo \"LIS Professors with MPACT\\n\";\n echo \"
\\n\";\n echo \"LIS Professors and their Degrees (large CSV)\\n\";\n echo \"
\\n\";\n echo \"LIS Professors with Unknown Degree\\n\";\n echo \"
\\n\";\n echo \"LIS Professors with Unknown-Investigated Degree\\n\";\n echo \"
\\n\";\n echo \"LIS Professors without Dissertations\\n\";\n echo \"
\\n\";\n echo \"LIS Professors without LIS Dissertations\\n\";\n echo \"

\\n\";\n\n echo \"
\\n\";\n\n echo \"
\";\n\n show_alphabet();\n\n }\n else\n {\n not_admin();\n }\n\n break;\n ###############################################\n case \"glossary_edit\";\n\n if ( isset($_GET['id']) && is_admin() ){\n\n echo \"

Edit a Glossary Definition

\\n\";\n\n $query = \"SELECT id, term, definition FROM glossary WHERE id='\".$_GET['id'].\"'\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $results['term'] = $line['term'];\n $results['definition'] = $line['definition'];\n }\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\".$results['term'].\":
\\n\";\n echo \"\\n\";\n echo \"
\\n\";\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n\n\n }\n else\n {\n not_admin();\n }\n\n break;\n ###############################################\n case \"show_tree\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n draw_tree((int)$_GET['id']);\n }\n\n break;\n\n ###############################################\n case \"show_graph\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n echo \"

\\n\";\n echo \"Advisors and Advisees of \".get_person_link($_GET['id']);\n echo \"

\\n\";\n draw_graph((int)$_GET['id']);\n }\n\n break;\n\n ###############################################\n case \"statistics\":\n\n echo \"

\\n\";\n echo \"LIS Incomplete - \\n\";\n echo \"Top A -\\n\";\n echo \"Top C -\\n\";\n echo \"Top A+C -\\n\";\n echo \"Top T -\\n\";\n echo \"Top G -\\n\";\n echo \"Top W -\\n\";\n echo \"Top TD -\\n\";\n echo \"Top TA\\n\";\n echo \"

\\n\";\n\n echo \"

Overall MPACT Statistics

\\n\";\n\n echo \"\\n\";\n\n # disciplines\n $query = \"SELECT count(*) as disciplinecount FROM disciplines\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # schools\n $query = \"SELECT count(*) as schoolcount FROM schools\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # diss\n $query = \"SELECT count(*) as disscount FROM dissertations\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # a\n $query = \"SELECT count(*) as advisorcount FROM advisorships\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # c\n $query = \"SELECT count(*) as committeeshipscount FROM committeeships\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # full\n $query = \"SELECT count(*) as peoplecount FROM people\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n echo \"
Disciplines\".$disciplinecount.\"
Schools\".$schoolcount.\"
Dissertations\".$disscount.\"
Advisorships\".$advisorcount.\"
Committeeships\".$committeeshipscount.\"
People\".$peoplecount.\"
\\n\";\n\n\n # dissertations by country\n echo \"

\\n\";\n echo \"

Dissertations by Country:


\\n\";\n $query = \"SELECT count(*) as dissnone FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"\\\")\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as dissusa FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"USA\\\")\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as disscanada FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"Canada\\\")\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as dissother FROM dissertations WHERE school_id IN\n (SELECT id FROM schools WHERE (country != \\\"\\\" AND country != \\\"USA\\\" AND country != \\\"Canada\\\"))\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"
USA\".$dissusa.\"\".sprintf(\"%.2f\",100*$dissusa/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa)/$disscount).\"%
Canada\".$disscanada.\"\".sprintf(\"%.2f\",100*$disscanada/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada)/$disscount).\"%
Other\".$dissother.\"\".sprintf(\"%.2f\",100*$dissother/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada+$dissother)/$disscount).\"%
None Listed\".$dissnone.\"\".sprintf(\"%.2f\",100*$dissnone/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada+$dissother+$dissnone)/$disscount).\"%
Total\".$disscount.\"\".sprintf(\"%.2f\",100*$disscount/$disscount).\"%
\\n\";\n\n # dissertations by year\n echo \"

\\n\";\n echo \"

Dissertations by Year:


\\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations GROUP BY completedyear\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
\";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n\n break;\n\n\n ###############################################\n case \"show_logs\":\n\n if (is_admin())\n {\n echo \"

Recent Activity

\\n\";\n\n if (isset($_GET['offset']))\n {\n $entries = get_logs($_GET['offset']);\n }\n else\n {\n $entries = get_logs();\n }\n echo \"\\n\";\n foreach ($entries as $entry)\n {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
\".$entry['logged_at'].\"
\".$entry['ip'].\"
\".$entry['user'].\"\".$entry['message'].\"
\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_multi_dissertations\":\n\n if (is_admin())\n {\n echo \"

People With Multiple Dissertations (db needs to be edited by hand)

\\n\";\n \n $query = \"SELECT\n count(d.id) as howmany,\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n GROUP BY\n d.person_id\n ORDER BY\n howmany DESC\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $multicount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n if ($d['howmany'] > 1)\n {\n print \"person id = \".$d['person_id'];\n print \"
\";\n print \"
\";\n $multicount++;\n }\n }\n if ($multicount == 0)\n {\n print \" - None - database is clear.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_zero_year\":\n\n if (is_admin())\n {\n echo \"

Dissertations from the year 0000

\\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.discipline_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.completedyear = '0000'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n # get school\n $query = \"SELECT fullname\n FROM\n schools\n WHERE id = '\".$d['school_id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $schoolname = $line['fullname'];\n }\n # get degree\n $query = \"SELECT degree\n FROM\n people\n WHERE id = '\".$d['person_id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $degree = $line['degree'];\n }\n $discipline = find_discipline($d['discipline_id']);\n echo \"\";\n echo \"\";\n echo \"\";\n print \"\";\n print \"\";\n print \"\";\n print \"\";\n }\n if ($zerocount == 0)\n {\n print \"\";\n }\n echo \"
$zerocount.\".get_person_link($d['person_id']).\"$degree\".$discipline['title'].\"$schoolname
None - database is clear.
\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_lis\":\n\n if (is_admin())\n {\n echo \"

LIS Dissertations Without Title

\\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.title = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
\";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have titles.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_abstract_lis\":\n\n if (is_admin())\n {\n echo \"

LIS Dissertations Without Abstract

\\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.abstract = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
\";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have abstracts.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_abstract\":\n\n if (is_admin())\n {\n echo \"

Dissertations Without Title/Abstract

\\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.title = '' OR d.abstract = ''\n ORDER BY\n d.school_id\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
\";\n }\n if ($zerocount == 0)\n {\n print \" - None - All dissertations have titles and abstracts.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_abstract_lis\":\n\n if (is_admin())\n {\n echo \"

LIS Dissertations Without Title/Abstract

\\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.title = '' OR d.abstract = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
\";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have titles and abstracts.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_unknown_degree\":\n \n if (is_admin())\n {\n echo \"

LIS Professors with Unknown Degree

\\n\";\n \n # advisors or committee members with unknown degree,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n $lis_with_unknown = array();\n\n # get advisors for each diss, check for advisor's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $advisors = array();\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n foreach($advisors as $aid){\n $adv = find_person($aid);\n if ($adv['degree'] == \"Unknown\"){\n $lis_with_unknown[] = $aid;\n }\n }\n }\n\n # get committeeships for each diss, check for comm's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $committeemembers = array();\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n foreach($committeemembers as $cid){\n $com = find_person($cid);\n if ($com['degree'] == \"Unknown\"){\n $lis_with_unknown[] = $cid;\n }\n }\n }\n\n # uniquify\n $lis_with_unknown = array_unique($lis_with_unknown);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($lis_with_unknown as $pid){\n $count++;\n $person = find_person($pid);\n print \"$count. \";\n print get_person_link($pid);\n print \"
\\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_unknowninvestigated\":\n case \"lis_profs_unknowninvestigated_degree\":\n \n# if (is_admin())\n# {\n echo \"

LIS Professors with Unknown-Investigated Degree

\\n\";\n \n # advisors or committee members with unknown-investigated degree,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n $lis_with_unknown = array();\n\n # get advisors for each diss, check for advisor's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $advisors = array();\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n foreach($advisors as $aid){\n $adv = find_person($aid);\n if ($adv['degree'] == \"Unknown - Investigated\"){\n $lis_with_unknown[] = $aid;\n }\n }\n }\n\n # get committeeships for each diss, check for comm's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $committeemembers = array();\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n foreach($committeemembers as $cid){\n $com = find_person($cid);\n if ($com['degree'] == \"Unknown - Investigated\"){\n $lis_with_unknown[] = $cid;\n }\n }\n }\n\n # uniquify\n $lis_with_unknown = array_unique($lis_with_unknown);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($lis_with_unknown as $pid){\n $count++;\n $person = find_person($pid);\n print \"$count. \";\n print get_person_link($pid);\n $advisorcount = count(find_advisorships_under_person($pid));\n $commcount = count(find_committeeships_under_person($pid));\n $totalcommitteeships = $advisorcount + $commcount;\n if ($totalcommitteeships > 1){print \"\";}\n print \" : $advisorcount + $commcount = $totalcommitteeships\";\n if ($totalcommitteeships > 1){print \"\";}\n print \"
\\n\";\n $allcommitteeships += $totalcommitteeships;\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n\n print \"
TOTAL COMMITTEESHIPS = $allcommitteeships
\";\n\n echo \"

\\n\";\n\n# }\n# else\n# {\n# not_admin();\n# }\n\n break;\n\n\n ###############################################\n case \"lis_profswithoutdiss\":\n\n if (is_admin())\n {\n echo \"

LIS Professors without Dissertations

\\n\";\n \n # advisors or committee members with no dissertation,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n $total = array_merge($advisors,$committeemembers);\n $unique = array_unique($total);\n\n $unique_list = implode(\",\",$unique);\n $listed = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $listed[] = $line['person_id'];\n }\n $notlisted = array_diff($unique,$listed);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($notlisted as $pid){\n $count++;\n print \"$count. \";\n print get_person_link($pid);\n print \"
\\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_degrees\":\n\n if (is_admin())\n {\n echo \"

LIS Professors and their Degrees

\\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n print \"

Copy and Paste the text below into a .csv file.

\";\n\n # big loop\n print \"
\\n\";\n          print \"
\";\n print \"Count,DissID,DissYear,DissLastName,DissFirstName,DissSchool,DissCountry,AdvisorID,AdvisorType,AdvisorLastName,AdvisorFirstName,\";\n print \"AdvisorDegree,AdvisorYear,AdvisorDiscipline,AdvisorSchool,AdvisorCountry\\n\";\n $count = 0;\n foreach($lis_dissertations as $did){\n # loop through advisors\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $did\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n\n # advisor line\n\n # Count\n $count++;\n print \"\\\"$count\\\",\";\n # DissID\n print \"\\\"$did\\\",\";\n # DissYear\n $diss = find_dissertation($did);\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # DissLastName\n $author = find_person($diss['person_id']);\n print \"\\\"\".$author['lastname'].\"\\\",\";\n # DissFirstName\n print \"\\\"\".$author['firstname'].\"\\\",\";\n # DissSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # DissCountry\n print \"\\\"\".$school['country'].\"\\\",\";\n # AdvisorID\n $pid = $line['person_id'];\n print \"\\\"$pid\\\",\";\n # AdvisorType\n print \"\\\"Advisor\\\",\";\n # AdvisorLastName\n $person = find_person($pid);\n print \"\\\"\".$person['lastname'].\"\\\",\";\n # AdvisorFirstName\n print \"\\\"\".$person['firstname'].\"\\\",\";\n # AdvisorDegree\n print \"\\\"\".$person['degree'].\"\\\",\";\n $diss = find_dissertation_by_person($pid);\n if ($diss){\n # AdvisorYear\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # AdvisorDiscipline\n $disc = find_discipline($diss['discipline_id']);\n print \"\\\"\".$disc['title'].\"\\\",\";\n # AdvisorSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # AdvisorCountry\n print \"\\\"\".$school['country'].\"\\\"\";\n }\n else{\n # no dissertation for this person\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\"\";\n }\n print \"\\n\";\n\n }\n # loop through committeeships\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $did\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n\n # committeeship line\n\n # Count\n $count++;\n print \"\\\"$count\\\",\";\n # DissID\n print \"\\\"$did\\\",\";\n # DissYear\n $diss = find_dissertation($did);\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # DissLastName\n $author = find_person($diss['person_id']);\n print \"\\\"\".$author['lastname'].\"\\\",\";\n # DissFirstName\n print \"\\\"\".$author['firstname'].\"\\\",\";\n # DissSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # DissCountry\n print \"\\\"\".$school['country'].\"\\\",\";\n # AdvisorID\n $pid = $line['person_id'];\n print \"\\\"$pid\\\",\";\n # AdvisorType\n print \"\\\"Committee\\\",\";\n # AdvisorLastName\n $person = find_person($pid);\n print \"\\\"\".$person['lastname'].\"\\\",\";\n # AdvisorFirstName\n print \"\\\"\".$person['firstname'].\"\\\",\";\n # AdvisorDegree\n print \"\\\"\".$person['degree'].\"\\\",\";\n $diss = find_dissertation_by_person($pid);\n if ($diss){\n # AdvisorYear\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # AdvisorDiscipline\n $disc = find_discipline($diss['discipline_id']);\n print \"\\\"\".$disc['title'].\"\\\",\";\n # AdvisorSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # AdvisorCountry\n print \"\\\"\".$school['country'].\"\\\"\";\n }\n else{\n # no dissertation for this person\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\"\";\n }\n print \"\\n\";\n\n }\n }\n echo \"
\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profsnotfromlis\":\n\n if (is_admin())\n {\n\n echo \"

LIS Professors without LIS Dissertations

\\n\";\n\n # and then once the data collection is done\n # cassidy wants a list of all the people who were advisors and committee\n # members for lis, but were not themselves lis\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n $total = array_merge($advisors,$committeemembers);\n $unique = array_unique($total);\n\n $unique_list = implode(\",\",$unique);\n $listed = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $listed[] = $line['person_id'];\n }\n $notlisted = array_diff($unique,$listed);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($notlisted as $pid){\n $count++;\n print \"$count. \";\n print get_person_link($pid);\n print \"
\\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_nocommittee\":\n\n if (is_admin())\n {\n\n echo \"

LIS Dissertations with no committee

\\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT count(*) as howmany\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n if ($line['howmany'] > 0){$hascomm[] = $id;};\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT count(*) as howmany\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n if ($line['howmany'] > 0){$hascomm[] = $id;};\n }\n }\n $unique = array_unique($hascomm);\n $nocomm = array_diff($lis_dissertations,$unique);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($nocomm as $did){\n $count++;\n print \"$count. \";\n $d = find_dissertation($did);\n print get_person_link($d['person_id']);\n print \"
\\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_with_mpact\":\n\n if (is_admin())\n {\n echo \"

LIS Professors With MPACT

\\n\";\n \n # advisors or committee members\n # that served on an lis dissertation\n\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n \n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n\n $total = array_merge($advisors,$committeemembers);\n\n $unique = array_unique($total);\n\n echo \"
\\n\";\n          echo \"Count|Name|Year|A|C|A+C|T\\n\";\n          foreach ($unique as $prof){\n            $mpact = mpact_scores($prof);\n            $person = find_person($prof);\n            $dissertation = find_dissertation_by_person($prof);\n            # count\n            $count += 1;\n            echo \"$count\";\n            echo \"|\";\n            # name\n            echo $person['fullname'];\n            echo \"|\";\n            # year\n            echo $dissertation['completedyear'];\n            echo \"|\";\n            # a\n            echo $mpact['A'];\n            echo \"|\";\n            # c\n            echo $mpact['C'];\n            echo \"|\";\n            # a+c\n            echo $mpact['AC'];\n            echo \"|\";\n            # t\n            echo $mpact['T'];\n            echo \"\\n\";\n          }\n          echo \"
\\n\";\n }\n\n break;\n\n ###############################################\n case \"lis_profs_summary\":\n \n if (is_admin())\n {\n echo \"

LIS Professors Summary

\\n\";\n \n # advisors or committee members\n # that served on an lis dissertation\n\n echo \"\\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n echo \"\\n\";\n \n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n echo \"\\n\";\n\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n echo \"\\n\";\n\n $total = array_merge($advisors,$committeemembers);\n echo \"\\n\";\n\n $unique = array_unique($total);\n echo \"\\n\";\n\n $unique_list = implode(\",\",$unique);\n $known = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $known[] = $line['person_id'];\n }\n echo \"\\n\";\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n discipline_id != 16\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n completedyear != 0000\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n completedyear != 107\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n echo \"
Total LIS Dissertations\".count($lis_dissertations).\"
Total LIS Dissertation Advisorships\";\n echo count($advisors);\n echo \"
Total LIS Dissertation Committeeships\";\n echo count($committeemembers);\n echo \"
Total LIS Dissertation Advisorships and Committeeships:\";\n echo count($total);\n echo \"
Total number of unique advisor/committee members on LIS dissertations:\";\n\n echo count($unique);\n echo \"
\";\n echo \"Subset of \".count($unique).\" without a listed dissertation:\";\n echo count(array_diff($unique,$known));\n echo \"
Subset of \".count($unique).\" with a listed dissertation:\";\n echo count($known);\n echo \"
- Subset of \".count($known).\" with known discipline:\";\n echo $howmany;\n echo \"
- Subset of \".count($known).\" with known year:\";\n echo $howmany;\n echo \"
- Subset of \".count($known).\" with known school:\";\n echo $howmany;\n echo \"
\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_allyears\":\n\n if (is_admin())\n {\n echo \"

LIS, Graduates By Year

\\n\";\n print \"
\\n\";\n\n            # get list of dissertations\n            $query = \"SELECT\n                      d.id, d.person_id, d.completedyear\n                    FROM\n                      dissertations d\n                    WHERE\n                      d.discipline_id = '1'\n                    ORDER BY\n                      d.completedyear ASC,\n                      d.school_id ASC\n                    \";\n            $result = mysql_query($query) or die(mysql_error());\n            $schools = array();\n            $count = 0;\n            while ( $line = mysql_fetch_array($result)) {\n              $dissertation = find_dissertation($line['id']);\n              $person = find_person($line['person_id']);\n              $schoolinfo = find_persons_school($line['person_id']);\n              $count++;\n              print $count;\n              print \"|\";\n              print $line['completedyear'];\n              print \"|\";\n              print $schoolinfo['school'];\n              print \"|\";\n              print $person['fullname'];\n#              print \"|\";\n#              print $dissertation['title'];\n#              print \"|\";\n#              print $dissertation['abstract'];\n              print \"\\n\";\n            }\n\n            print \"
\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_history\":\n\n if (is_admin())\n {\n echo \"

LIS Dissertations by School by Year

\\n\";\n\n $firstyear = 1920;\n $lastyear = 2008;\n\n print \"
\\n\";\n            print \"school|\";\n            for ($i = $firstyear; $i <= $lastyear; $i++)\n            {\n                print \"$i|\";\n            }\n            print \"\\n\";\n\n            # get list of schools (all of them)\n            $query = \"SELECT\n                    s.id, s.fullname\n                    FROM\n                      schools s\n                    ORDER BY\n                      s.fullname\n                    \";\n            $result = mysql_query($query) or die(mysql_error());\n            $schools = array();\n            while ( $line = mysql_fetch_array($result)) {\n              $schools[] = $line;\n            }\n            foreach ($schools as $s)\n            {\n              # loop through each school and find count by year\n              $query = \"SELECT\n                    d.id, d.person_id, d.completedyear, COUNT(d.completedyear) AS yeartotal\n                    FROM\n                      dissertations d\n                    WHERE\n                      d.discipline_id = '1' AND\n                      d.school_id = '\".$s['id'].\"'\n                    GROUP BY\n                      d.completedyear\n                  \";\n              $result = mysql_query($query) or die(mysql_error());\n\n              print $s['fullname'].\"|\";\n              $d = array();\n              while ( $line = mysql_fetch_array($result)) {\n                $d[$s['id']][$line['completedyear']] = $line['yeartotal'];\n              }\n\n              # walk through all years, and print out counts for this school\n              for ($i = $firstyear; $i <= $lastyear; $i++)\n              {\n                if ($d[$s['id']][$i] > 0)\n                  print $d[$s['id']][$i].\"|\";\n                else\n                  print \"0|\";\n              }\n              print \"\\n\";\n            }\n\n            print \"
\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_incomplete\":\n\n echo \"

Incomplete LIS Dissertation Listings

\\n\";\n\n $discipline_id = 1; # hard coded for LIS\n $schools = find_schools($discipline_id);\n\n foreach ($schools as $one => $two)\n {\n\n $year_conferred = array();\n $degree_status = array();\n\n $query = \"SELECT d.person_id, d.completedyear, d.status\n FROM\n dissertations d,\n schools s,\n people p,\n names n\n WHERE\n s.id = '$one' AND\n d.discipline_id = '$discipline_id' AND\n d.school_id = s.id AND\n d.person_id = p.id AND\n p.preferred_name_id = n.id AND\n d.status < 4\n ORDER BY\n s.id ASC, d.completedyear ASC, n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n $resultcount = 0;\n\n while ( $line = mysql_fetch_array($result)) {\n $resultcount++;\n extract($line);\n $year_conferred[$person_id] = $completedyear;\n $degree_status[$person_id] = $status;\n }\n\n if ($resultcount > 0)\n {\n echo \"

$two

\\n\";\n }\n\n $incompletecount = 0;\n echo \"\";\n foreach ($year_conferred as $person => $year)\n {\n $incompletecount++;\n $printme = \"\\n\";\n $printme .= \"\\n\";\n\n $printme .= \"\\n\";\n $printme .= \"\\n\";\n\n echo $printme;\n }\n echo \"
$incompletecount. \";\n $printme .= \"\".get_person_link($person).\" ($year)\".$statuscodes[$degree_status[$person]].\"
\";\n\n }\n echo \"

\";\n\n break;\n\n ###############################################\n case \"all_edges\":\n\n if (is_admin())\n {\n echo \"

All Dissertations and Mentor Relationships

\\n\";\n\n print \"
\\n\";\n            print \"mentor|role|protege|year|school\\n\";\n\n            # each dissertation\n            $query = \"SELECT id, person_id, completedyear, school_id FROM dissertations\";\n            $result = mysql_query($query) or die(mysql_error());\n            while ( $line = mysql_fetch_array($result)) {\n              extract($line);\n              $student = find_person($person_id);\n              $query2 = \"SELECT fullname as schoolname FROM schools WHERE id = '$school_id'\";\n              $result2 = mysql_query($query2) or die(mysql_error());\n              $line2 = mysql_fetch_array($result2);\n              extract($line2);\n              print $student['fullname'].\"|dissertation|null|$completedyear|$schoolname\\n\";\n              # get advisorships\n              $advisors = find_advisors_for_person($person_id);\n              foreach ($advisors as $mentor_id){\n                $mentor = find_person($mentor_id);\n                print $mentor['fullname'].\"|advisorship|\".$student['fullname'].\"|$completedyear|$schoolname\\n\";\n              }\n              # get committeeships\n              $committee = find_committee_for_person($person_id);\n              foreach ($committee as $mentor_id){\n                $mentor = find_person($mentor_id);\n                print $mentor['fullname'].\"|committeeship|\".$student['fullname'].\"|$completedyear|$schoolname\\n\";\n              }\n            }\n            print \"
\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"citation_correlation\":\n\n if (is_admin())\n {\n echo \"

Citation Correlation Data

\\n\";\n\n $correlated_ids = array(\n 953,\n 2098,\n# 5086, bc\n 3659,\n# 1329, dalhousie\n 5087,\n 478,\n 3094,\n 3497,\n 4784,\n 1250,\n 5088,\n 5089,\n 5090,\n 4657,\n# 5091, mcdowell, not phd yet\n 5092,\n 5093,\n 5094,\n 2668,\n 4076,\n 2683,\n 3978,\n 2425,\n 3645,\n 2660,\n 2233,\n 2665,\n 1310,\n 2548,\n 2708,\n 2592,\n 4648,\n 5095,\n 5096,\n 4654,\n 5097,\n 5098,\n 1234,\n 1299,\n 1294,\n 3062,\n 3110,\n 1283,\n 1220,\n 874,\n 584,\n 3127,\n 1142,\n 3116,\n 5099,\n 5100,\n 1025,\n 486,\n 3130,\n 1321,\n 5101,\n 4502,\n 5102,\n 535,\n 5160, # koohang\n 2673,\n 5103,\n 5104,\n 1950,\n 3972,\n 3278,\n 5105,\n 3571,\n 5106,\n 3994,\n 1504,\n 4181,\n 3140,\n 2323, # benoit added\n 5107,\n 800,\n 4438,\n 5108,\n 5109,\n 4760,\n 2570,\n 1866,\n 3238,\n 1846,\n 1806,\n 2527,\n 3703,\n 4758,\n 3683,\n 3846,\n 2603,\n 4011,\n 2343,\n 2329,\n 5110,\n 5111,\n 4706,\n 2761,\n 1413,\n 3028,\n 3590,\n 3668,\n 2883,\n 3063,\n 3091,\n 1705,\n 3031,\n# gary again 486,\n 3979,\n 3018,\n 1855,\n 3409,\n 2747,\n 3093,\n 3065,\n 3060,\n 1685,\n 2114,\n 5112,\n# moore rm 5113,\n 2309,\n# liu rm 2215,\n 4086,\n 4013,\n 1573\n );\n\n echo \"\\n\";\n echo \"\n \n \n \n \n \n \n \n \n \n \\n\";\n $counter = 0;\n foreach ($correlated_ids as $one)\n {\n $counter++;\n echo \"\";\n echo \"\";\n echo \"\";\n $scores = mpact_scores($one);\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
-NameACA+CFMIFMEFMI/(A+C)FME/(A+C)
$counter.\";\n echo get_person_link($one);\n echo \"\".$scores['A'].\"\".$scores['C'].\"\".$scores['AC'].\"\".$scores['FMI'].\"\".$scores['FME'].\"\".$scores['FMIdivFULL'].\"\".$scores['FMEdivFULL'].\"
\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"top_a\":\n case \"top_c\":\n case \"top_ac\":\n case \"top_g\":\n case \"top_td\":\n case \"top_w\":\n case \"top_t\":\n case \"top_ta\":\n\n $list_type = strtoupper(substr($_GET['op'],4));\n echo \"

Top \";\n if ($list_type == \"TD\"){echo \"TD\";}\n else if ($list_type == \"TA\"){echo \"TA\";}\n else if ($list_type == \"AC\"){echo \"A+C\";}\n else {echo $list_type;}\n echo \" List

\\n\";\n $score_type = strtolower($list_type).\"_score\";\n $people = find_all_people();\n foreach ($people as $p)\n {\n $scores[$p] = find_mpact_score($p,$score_type);\n }\n # zero out indecipherables\n $scores[28] = 0;\n $scores[391] = 0;\n asort($scores);\n $scores = array_reverse($scores, true);\n $top = narray_slice($scores, 0, 100); #calls custom function, end of mpact_include (passes true)\n $count = 0;\n $lasttotal = 0;\n echo \"\\n\";\n foreach ($top as $one => $two)\n {\n $count++;\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n $lasttotal = $two;\n }\n echo \"
\";\n if ($two != $lasttotal){echo $count.\".\";}\n echo \"\";\n echo get_person_link($one);\n echo \"\";\n echo $two;\n echo \"
\\n\";\n break;\n\n ###############################################\n case \"create_discipline\":\n\n if (is_admin())\n {\n echo \"

Creating a New Discipline

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
Title
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_discipline\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n elseif (!is_empty_discipline($_GET['id']))\n {\n action_box(\"Discipline must be empty to edit...\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else{\n \n $query = \"SELECT title FROM disciplines WHERE id=\".$_GET['id'];\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

Editing a Discipline

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
Title
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_school\":\n\n if (is_admin())\n {\n echo \"

Creating a New School

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FullnameCountry
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n elseif (!is_empty_school($_GET['id']))\n {\n action_box(\"School must be empty to edit...\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else{\n \n $query = \"SELECT fullname, country FROM schools WHERE id=\".$_GET['id'];\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

Editing a School

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FullnameCountry
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_person\":\n\n if (is_admin())\n {\n echo \"

Creating a New Person

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FirstMiddleLastSuffixDegree
\";\n echo \"\\n\";\n echo \"
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin())\n {\n echo \"

Add a New Person to the Database

\\n\";\n\n echo \"

Adding a Mentor

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"Mentor Type:
\\n\";\n echo \" Advisor
\\n\";\n echo \" Committee Member\\n\";\n echo \"

\\n\";\n\n echo \"Mentor:
\\n\";\n echo \"\\n\";\n\n echo \"

\\n\";\n\n echo \"Student:
\\n\". get_person_link($_GET['id']);\n echo \"

\\n\";\n\n echo \"\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree($_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_student\":\n\n if (is_admin())\n {\n echo \"

Add a New Person to the Database

\\n\";\n\n echo \"

Adding a Student

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"Mentor Type:
\\n\";\n echo \" Advisor
\\n\";\n echo \" Committee Member\\n\";\n echo \"

\\n\";\n \n echo \"Mentor:
\\n\". get_person_link($_GET['id']);\n echo \"

\\n\";\n \n\n echo \"Student:
\\n\";\n echo \"\\n\";\n\n echo \"

\\n\";\n echo \"\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree($_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n\n ###############################################\n case \"remove_mentor\":\n\n if (is_admin())\n {\n echo \"

Removing a Mentor

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"Are you sure you want to remove this mentor relationship?

\\n\";\n if ($_GET['type'] == \"A\"){echo \"Advisor: \";}\n if ($_GET['type'] == \"C\"){echo \"Commitee Member: \";}\n echo get_person_link(intval($_GET['mentor_id'])).\"
\\n\";\n echo \"Student: \".get_person_link(intval($_GET['student_id'])).\"
\\n\";\n echo \"
\\n\";\n\n echo \"\";\n echo \" If NOT, please go BACK\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree(intval($_GET['student_id']));\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_url\";\n\n if (is_admin())\n {\n echo \"

Adding a Reference URL

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
URL:
Description:
\\n\";\n\n echo \"\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree(intval($_GET['id']));\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_url\";\n\n if (is_admin())\n {\n $url = find_url(intval($_GET['id']));\n echo \"

Editing a Reference URL

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
URL:
Description:
Last Updated:\".$url['updated_at'].\"
\\n\";\n\n echo \"\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree($url['person_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_url\";\n\n if (is_admin())\n {\n $url = find_url(intval($_GET['id']));\n echo \"

Deleting a Reference URL

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"Are you sure you want to delete this Reference URL?

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
URL:\".$url['url'].\"
Description:\".$url['description'].\"
Last Updated:\".$url['updated_at'].\"
\\n\";\n echo \"
\\n\";\n\n echo \"\";\n echo \" If NOT, please go BACK\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree($url['person_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_degree\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

Editing a Degree

\";\n echo \"

\";\n\n echo \"

\";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
NameDegree
\".$person['fullname'].\"\";\n echo \"\\n\";\n echo \"
\";\n\n echo \"\";\n\n echo \"
\";\n\n echo \"

\";\n\n\n echo \"
\";\n draw_tree($_GET['id']);\n echo \"
\";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

Adding an Alias

\";\n echo \"

\";\n\n echo \"

\";\n echo \"\";\n echo \"\";\n \n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FirstMiddleLastSuffix
\";\n\n echo \"\";\n\n echo \"
\";\n\n echo \"

\";\n\n\n echo \"
\";\n draw_tree($_GET['id']);\n echo \"
\";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n \n break;\n \n ###############################################\n case \"edit_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

Editing a Name

\";\n echo \"

\";\n\n echo \"

\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FirstMiddleLastSuffix
\";\n\n echo \"\";\n\n echo \"
\";\n\n echo \"

\";\n\n\n echo \"
\";\n draw_tree($_GET['id']);\n echo \"
\";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_dissertation\":\n\n if (is_admin())\n {\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n\n if (!$_GET['person_id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['person_id']);\n if (!$person)\n {\n action_box(\"Person not found.\");\n }\n else{\n\n echo \"

CREATE DISSERTATION

\\n\";\n\n echo \"
\";\n echo \"\";\n echo \"\";\n\n echo \"

\";\n echo get_person_link($person['id']);\n echo \"
\";\n\n echo \"Degree: \\n\";\n echo \"
\";\n\n echo \"Status: \\n\";\n echo \"
\";\n\n echo \"Discipline: \\n\";\n echo \"
\";\n\n\n echo \"School: \";\n echo \"\\n\";\n echo \"
Year:\\n\";\n echo \"
\";\n echo \"Title:

\";\n echo \"Abstract:

\";\n echo \"\";\n echo \"

\";\n\n echo \"
\";\n\n echo \"

\";\n echo \"Currently:\";\n echo \"

\";\n echo \"
\";\n draw_tree($person['id']);\n echo \"
\";\n }\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"edit_dissertation\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n $dissertation = find_dissertation(intval($_GET['id']));\n if (!$dissertation)\n {\n action_box(\"Dissertation not found.\");\n }\n else{\n \n $person = find_person($dissertation['person_id']);\n\n echo \"

EDIT DISSERTATION DETAILS

\\n\";\n\n echo \"
\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"

\";\n echo get_person_link($person['id']);\n echo \"
\";\n \n echo \"Degree: \\n\";\n echo \"
\";\n\n echo \"Status: \\n\";\n echo \"
\";\n\n echo \"Discipline: \\n\";\n echo \"
\";\n\n echo \"School: \\n\";\n\n echo \"
Year:\\n\";\n echo \"
\";\n echo \"Title:

\";\n echo \"Abstract:

\";\n echo \"Admin Notes:

\";\n echo \"\";\n echo \"

\";\n\n echo \"
\";\n\n echo \"

\";\n echo \"Currently:\";\n echo \"

\";\n echo \"
\";\n draw_tree($person['id']);\n echo \"
\";\n }\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_name($_GET['name']);\n\n echo \"

\";\n\n echo \"Are you sure you want to delete this name?\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\";\n \n echo \"

\";\n echo \"[ \".$person['firstname'].\" \".$person['middlename'].\" \".$person['lastname'].\" \".$person['suffix'].\" ]
\"; \n echo \"

\";\n\n\n echo \"

\";\n echo \"\";\n echo \"   Cancel

\";\n\n echo \"
\";\n\n echo \"

\";\n\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n \n ###############################################\n case \"set_preferred_name\":\n\n if (is_admin())\n {\n\n set_preferred_name($_GET['id'],$_GET['name']);\n\n action_box(\"Preferred Name Selected\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"recalculate_mpact\":\n\n if (is_admin()){\n\n # recalculate MPACT scores for passed person id\n calculate_scores($_GET['id']);\n\n action_box(\"MPACT Scores Recalculated\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_GET['id']);\n\n }\n else\n {\n not_admin();\n } \n\n break;\n\n ###############################################\n case \"show_orphans\":\n\n if (is_admin())\n {\n\n $orphans = find_orphans();\n\n echo \"

Orphans

\\n\";\n\n echo \"

\\n\";\n $counter = 0;\n foreach ($orphans as $orphan)\n {\n $counter++;\n echo $counter.\" \";\n echo get_person_link($orphan['person_id']);\n echo \" (Delete from Database)\";\n echo \"
\\n\";\n }\n if ($counter < 1){echo \" - No orphans at this time.\";}\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_person\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n if (is_orphan($_GET['id']))\n {\n echo \"

\";\n\n echo \"Are you sure you want to delete this person?\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n echo get_person_link($_GET['id']);\n echo \"

\";\n\n\n echo \"

\";\n echo \"

\\n\";\n echo \"\";\n echo \"   Cancel

\";\n\n echo \"
\";\n\n echo \"

\";\n }\n else\n {\n action_box(\"This person cannot be deleted.\");\n }\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"show_disciplines\":\n\n $statustotals = array(0,0,0,0,0);\n $disciplines = find_disciplines();\n $disciplinecounts = find_discipline_counts();\n\n if (is_admin()){\n echo \"

Add a New Discipline to the Database

\\n\";\n }\n\n echo \"

Disciplines Represented Across All Schools

\\n\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($disciplines as $one => $two)\n {\n echo \"\";\n echo \"\";\n $statuscounts = find_discipline_statuses($one);\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n if (!isset($disciplinecounts[$one]) || $disciplinecounts[$one]==0)\n {\n $fraction = 0;\n }\n else\n {\n $fraction = 100*$statuscounts[$three]/intval($disciplinecounts[$one]);\n }\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($disciplinecounts);\n echo \"\";\n }\n echo \"\";\n echo \"
Discipline$statuscodes[$one]
$two (\".intval($disciplinecounts[$one]).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
------------------
\";\n echo count($disciplines).\" Disciplines (\".array_sum($disciplinecounts).\" dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n break;\n\n ###############################################\n case \"show_discipline\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $discipline_id = intval($_GET['id']);\n\n # Show Discipline Name\n $query = \"SELECT d.title as disciplinename\n FROM disciplines d\n WHERE\n d.id = '$discipline_id'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

$disciplinename

\";\n\n # Show Histograph\n $counts = array();\n echo \"

\\n\";\n echo \"Dissertations by Year:
\\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations WHERE discipline_id='$discipline_id' GROUP BY completedyear\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n if (count($counts)>0)\n {\n $bigyear = max($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*intval(200/$bigyear);\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
\";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n }\n echo \"

\\n\";\n }\n\n $schools = find_schools($discipline_id);\n $dissertation_count = 0;\n $statustotals = array(0,0,0,0,0);\n echo \"

Schools Represented

\\n\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($schools as $one => $two)\n {\n $statuscounts = find_dept_statuses($one,$discipline_id);\n $dissertation_count += array_sum($statuscounts);\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n\n if (array_sum($statustotals)==0)\n {\n $fraction = 0;\n }\n else\n {\n $fraction = 100*$statustotals[$three]/array_sum($statustotals);\n }\n echo \"\";\n }\n echo \"\";\n echo \"
School$statuscodes[$one]
$two (\".array_sum($statuscounts).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
------------------
\";\n echo count($schools).\" Schools ($dissertation_count dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n # link to edit the discipline name\n if (is_empty_discipline($_GET['id']))\n {\n echo \"

\";\n echo \"

Edit Discipline Name

\\n\";\n }\n\n break;\n\n ###############################################\n case \"show_school\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $school_id = intval($_GET['id']);\n\n # Show School Name\n $query = \"SELECT s.fullname as schoolname, s.country\n FROM schools s\n WHERE\n s.id = '$school_id'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

$schoolname ($country)

\";\n\n # Show Histograph\n echo \"

\\n\";\n echo \"Dissertations by Year:
\\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations WHERE school_id='$school_id' GROUP BY completedyear\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n $bigyear = max($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*intval(200/$bigyear);\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
\";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n\n $disciplines = find_disciplines($school_id);\n $dissertation_count = 0;\n $statustotals = array(0,0,0,0,0);\n echo \"

Disciplines Represented

\\n\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($disciplines as $one => $two)\n {\n $statuscounts = find_dept_statuses($school_id,$one);\n $dissertation_count += array_sum($statuscounts);\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($statustotals);\n echo \"\";\n }\n echo \"\";\n echo \"
Discipline$statuscodes[$one]
$two (\".array_sum($statuscounts).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
------------------
\";\n echo count($disciplines).\" Disciplines ($dissertation_count dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
\\n\";\n echo \"

\\n\";\n }\n\n # link to edit the school info\n if (is_empty_school($_GET['id']))\n {\n echo \"

\";\n echo \"

Edit School Information

\\n\";\n }\n\n break;\n\n ###############################################\n case \"show_schools\":\n\n $statustotals = array(0,0,0,0,0);\n $schools = find_schools();\n $schoolcounts = find_school_counts();\n\n if (is_admin()){\n echo \"

Add a New School to the Database

\\n\";\n }\n echo \"

Schools Represented Across All Disciplines

\\n\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($schools as $one => $two)\n {\n echo \"\";\n echo \"\";\n $statuscounts = find_school_statuses($one);\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n if (intval($schoolcounts[$one]) == 0){\n $fraction = 0;\n }\n else{\n $fraction = 100*$statuscounts[$three]/intval($schoolcounts[$one]);\n }\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($schoolcounts);\n echo \"\";\n }\n echo \"\";\n echo \"
School$statuscodes[$one]
$two (\".intval($schoolcounts[$one]).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
------------------
\";\n echo count($schools).\" Schools (\".array_sum($schoolcounts).\" dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n break;\n\n ###############################################\n case \"show_department\":\n\n if (!$_GET['d'] || !$_GET['s']){action_box(\"No ID given.\");}\n else\n {\n\n $school_id = $_GET['s'];\n $discipline_id = $_GET['d'];\n \n\n # Show Discipline Name\n $query = \"SELECT d.title as disciplinename\n FROM disciplines d\n WHERE\n d.id = '$discipline_id'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n # Show School Name\n $query = \"SELECT s.fullname as schoolname, s.country\n FROM schools s\n WHERE\n s.id = '$school_id'\n \";\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"\n

\n $disciplinename\n @\n $schoolname ($country)\n

\n \";\n\n # Advisor and Committee Activity\n echo \"

Dissertation Activity and MPACT Scores (click table headings to sort)

\";\n \n echo \"

\";\n $theprofs = find_profs_at_dept($school_id,$discipline_id);\n if (count($theprofs)>0)\n {\n $sortedprofs = array();\n $proflist = \"\";\n $query = \"SELECT id FROM people WHERE id IN (\";\n foreach ($theprofs as $prof){$proflist .= \"$prof,\";}\n $proflist = rtrim($proflist, \",\");\n $query .= \"$proflist) ORDER BY ac_score DESC\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $sortedprofs[] = $line['id'];\n }\n $profcount = 0;\n echo \"\\n\";\n echo \"\n \n \n \n \n \n \n \n \n \n \n \\n\";\n foreach ($sortedprofs as $one)\n {\n echo \"\";\n $profcount++;\n echo \"\";\n echo \"\";\n $scores = mpact_scores($one);\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
-NameACA+CGTTATDW
$profcount.\";\n echo get_person_link($one);\n echo \"\".$scores['A'].\"\".$scores['C'].\"\".$scores['AC'].\"\".$scores['G'].\"\".$scores['T'].\"\".$scores['TA'].\"\".$scores['TD'].\"\".$scores['W'].\"
\\n\";\n echo \"

\";\n }\n else\n {\n echo \"

- None Listed

\\n\";\n }\n echo \"
\";\n\n\n\n\n # Dissertations Conferred\n echo \"

Dissertations Conferred

\";\n\n\n\n\n # Show Histograph\n echo \"

\\n\";\n echo \"Dissertations by Year:
\\n\";\n $query = \"SELECT completedyear, count(*) as disscount\n FROM dissertations\n WHERE\n school_id='$school_id' AND\n discipline_id=$discipline_id\n GROUP BY\n completedyear\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*10;\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
\";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n\n\n\n\n $query = \"SELECT d.person_id, d.completedyear, d.status\n FROM\n dissertations d,\n schools s,\n people p,\n names n\n WHERE\n s.id = '$school_id' AND\n d.discipline_id = '$discipline_id' AND\n d.school_id = s.id AND\n d.person_id = p.id AND\n p.preferred_name_id = n.id\n ORDER BY\n d.completedyear ASC, n.lastname ASC, n.firstname ASC \n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n $year_conferred[$person_id] = $completedyear;\n $degree_status[$person_id] = $status;\n }\n\n $schoolcount = 0;\n echo \"

\";\n foreach ($year_conferred as $person => $year)\n {\n $schoolcount++;\n echo \"
$schoolcount. \";\n echo get_person_link($person);\n echo \" ($year)\";\n if ($degree_status[$person] < 4)\n {\n echo \" ---------------------------------- \".$statuscodes[$degree_status[$person]];\n }\n }\n echo \"

\";\n\n }\n\n break;\n \n ###############################################\n default:\n // oops - not supposed to be here\n action_box(\"invalid action\",1);\n }\n }\n else\n {\n\n if (isset($_GET['show']))\n {\n if ($_GET['show'] == \"all\")\n {\n $alphabet_limiter = \"\"; // set it to show everything\n }\n else\n {\n $alphabet_limiter = $_GET['show'];\n }\n\n show_alphabet();\n\n if (is_admin())\n {\n echo \"

Add a New Person to the Database

\\n\";\n }\n\n if (is_admin()){\n echo \"
\";\n echo \"\";\n echo \"\";\n echo \"\";\n }\n\n // GET ALL DISSERTATIONS IN A HASH\n $disciplines = find_disciplines();\n $query = \"SELECT id, person_id, discipline_id FROM dissertations\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $graduates[$line['person_id']] = $line['discipline_id'];\n }\n\n // LOOP THROUGH ALL PEOPLE FOR THIS LETTER\n echo \"\\n\";\n echo \"\\n\";\n if (is_admin()){echo \"\\n\";}\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n $query = \"SELECT n.id, n.firstname,\n n.middlename, n.lastname, n.suffix,\n p.id as person_id\n FROM names n, people p\n WHERE\n n.id = p.preferred_name_id AND\n n.lastname LIKE '\".$alphabet_limiter.\"%'\n ORDER BY n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $rowcount = 0;\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n\n $rowcount++;\n\n echo \"\";\n if (is_admin()){\n echo \"\";\n }\n echo \"\";\n echo \"\";\n $discipline = isset($graduates[$person_id]) ? $disciplines[$graduates[$person_id]] : \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n if (is_admin()){\n if ($rowcount % 25 == 0){\n echo \"\";\n }\n }\n\n }\n\n echo \"
MergeCountLast NameFull NameDissertation Discipline
$rowcount.$lastname$firstname $middlename $lastname $suffix$discipline
\\n\";\n\n if (is_admin()){\n echo \"\";\n echo \"
\";\n }\n\n echo \"

\\n\";\n\n show_alphabet();\n\n }\n else\n {\n // DISPLAY THE FRONT PAGE\n\n action_box(\"Front Page...\",0.1,\"./\");\n\n }\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n###############################################\n// SOMETHING WAS SUBMITTED - through a form\nelse\n{\n\n if ($_POST['op'] != \"login\"){\n // Display header\n xhtml_web_header();\n }\n\n switch ($_POST['op'])\n {\n ###############################################\n case \"login\";\n\n $host_info = get_environment_info();\n if ($host_info['hostname'] == \"sils\"){\n # no logins here - go to dev server\n action_box(\"No Logins Here...\",2,$_SERVER['SCRIPT_NAME']);\n }\n else{\n # check credentials / start session\n $query = \"SELECT id, username, fullname FROM users\n WHERE username = '\".addslashes($_POST['username']).\"'\n AND password = '\".addslashes($_POST['password']).\"'\";\n $result = mysql_query($query) or die(mysql_error());\n $line = mysql_fetch_array($result);\n if (isset($line['id'])){\n # save cookie info for one week\n setcookie('MPACT_userid',$line['id'],time()+60*60*24*7);\n # redirect\n header(\"Location: \".$_SERVER['SCRIPT_NAME']);\n }\n else{\n // Display header\n xhtml_web_header();\n # incorrect credentials\n action_box(\"Please try again...\",2,$_SERVER['SCRIPT_NAME'].\"?op=login\");\n }\n }\n\n break;\n\n ###############################################\n case \"glossary_edit\";\n if (is_admin())\n {\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $query = \"UPDATE glossary\n SET\n definition = '\".$_POST['definition'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # log it\n mpact_logger(\"updated glossary [\".$_POST['term'].\" (\".$_POST['id'].\")] to (\".$_POST['definition'].\")\");\n\n action_box(\"Definition Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=glossary\");\n }\n else\n {\n not_admin();\n }\n break;\n\n ###############################################\n case \"merge_confirm\":\n \n if (is_admin()){\n\n echo \"
\";\n echo \"\";\n echo \"\";\n \n foreach ($_POST['mergers'] as $one)\n {\n echo \"
\";\n echo \"

[$one]

\";\n echo draw_tree( $one );\n echo \"\";\n echo \"
\";\n } \n\n echo \"\";\n echo \"
\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"search\":\n\n $results = people_search($_POST['q']);\n\n if (count($results) > 0)\n {\n echo \"

People Search Results for [\".$_POST['q'].\"]:

\";\n }\n\n echo \"

\\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
\\n\";\n }\n if ($count < 1)\n {\n echo \"

\\n\";\n echo \"There were no results for [\".$_POST['q'].\"].\";\n if (strlen($_POST['q']) < 2)\n {\n echo \"

\\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

\\n\";\n echo \"

Add a New Person to the Database

\\n\";\n }\n }\n echo \"

\\n\";\n }\n\n echo \"

\\n\";\n\n break;\n\n ###############################################\n case \"search_title_abstract\":\n\n $results = title_abstract_search($_POST['qta']);\n\n if (count($results) > 0)\n {\n echo \"

Title/Abstract Search Results for [\".$_POST['qta'].\"]:

\";\n }\n\n echo \"

\\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
\\n\";\n }\n if ($count < 1)\n {\n echo \"

\\n\";\n echo \"There were no results for [\".$_POST['qta'].\"].\";\n if (strlen($_POST['qta']) < 2)\n {\n echo \"

\\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

\\n\";\n }\n }\n echo \"

\\n\";\n }\n\n echo \"

\\n\";\n\n break;\n\n ###############################################\n case \"search_notes\":\n\n if (is_admin()){\n\n $results = notes_search($_POST['qn']);\n\n if (count($results) > 0)\n {\n echo \"

Admin Notes Search Results for [\".$_POST['qn'].\"]:

\";\n }\n\n echo \"

\\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
\\n\";\n }\n if ($count < 1)\n {\n echo \"

\\n\";\n echo \"There were no results for [\".$_POST['qm'].\"].\";\n if (strlen($_POST['qn']) < 2)\n {\n echo \"

\\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

\\n\";\n }\n }\n echo \"

\\n\";\n }\n\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n } \n\n break;\n\n ###############################################\n case \"merge_doit\":\n \n if (is_admin()){\n\n # delete the family tree's dotgraphs of each person\n foreach ($_POST['mergers'] as $one)\n {\n delete_associated_dotgraphs($one);\n }\n\n # pop off one of the people_ids\n $into = array_pop($_POST['mergers']);\n\n # merge each remaining person into the one above\n foreach ($_POST['mergers'] as $one)\n {\n merge_two_people($one,$into);\n }\n\n # recalculate MPACT scores for merged person id\n calculate_scores($into);\n\n action_box(\"Merge was Successful\",2,$_SERVER['SCRIPT_NAME'].\"?show=\".$_POST['show']);\n\n }\n else\n {\n not_admin();\n } \n\n break;\n\n \n ###############################################\n case \"create_discipline\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['title'] == \"\")\n {\n action_box(\"Need to have at least a Discipline Title.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_discipline\");\n }\n elseif (is_duplicate_discipline($_POST['title']))\n {\n action_box(\"Discipline (\".$_POST['title'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else\n {\n \n # Create Discipline\n $query = \"INSERT disciplines\n SET\n title = '\".$_POST['title'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # Get the just created discipline_id\n $query = \"SELECT id as new_discipline_id, title FROM disciplines\n WHERE\n title = '\".$_POST['title'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n # log it\n mpact_logger(\"created discipline[\".$new_discipline_id.\"] (\".$title.\")\");\n\n action_box(\"Discipline Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_discipline\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['title'] == \"\")\n {\n action_box(\"Need to have at least a Discipline Title.\",3,$_SERVER['SCRIPT_NAME'].\"?op=edit_discipline&id=\".$_POST['discipline_id'].\"\");\n }\n elseif (is_duplicate_discipline($_POST['title']))\n {\n action_box(\"Discipline (\".$_POST['title'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else\n {\n\n # Edit Discipline\n $query = \"UPDATE disciplines\n SET\n title = '\".$_POST['title'].\"'\n WHERE\n id = '\".$_POST['discipline_id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # log it\n mpact_logger(\"edited discipline[\".$_POST['discipline_id'].\"] (\".$_POST['title'].\")\");\n\n action_box(\"Discipline Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_school\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $_POST = array_map('trim',$_POST);\n\n if ($_POST['fullname'] == \"\" || $_POST['country'] == \"\")\n {\n action_box(\"Need to have at least a School name and Country.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_school\");\n }\n elseif (is_duplicate_school($_POST['fullname']))\n {\n action_box(\"School (\".$_POST['fullname'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else\n {\n\n # Create School\n $query = \"INSERT schools\n SET\n fullname = '\".$_POST['fullname'].\"',\n country = '\".$_POST['country'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # Get the just created school_id\n $query = \"SELECT id as new_school_id, fullname FROM schools\n WHERE\n fullname = '\".$_POST['fullname'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n # log it\n mpact_logger(\"created school[\".$new_school_id.\"] (\".$fullname.\")\");\n\n action_box(\"School Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['fullname'] == \"\" || $_POST['country'] == \"\")\n {\n action_box(\"Need to have at least a School name and Country.\",3,$_SERVER['SCRIPT_NAME'].\"?op=edit_school&id=\".$_POST['school_id'].\"\");\n }\n elseif (is_duplicate_school($_POST['fullname']))\n {\n action_box(\"School (\".$_POST['fullname'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else\n {\n\n # Edit School\n $query = \"UPDATE schools\n SET\n fullname = '\".$_POST['fullname'].\"',\n country = '\".$_POST['country'].\"'\n WHERE\n id = '\".$_POST['school_id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # log it\n mpact_logger(\"edited school[\".$_POST['school_id'].\"] (\".$_POST['fullname'].\")\");\n\n action_box(\"School Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_person\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['lastname'] == \"\")\n {\n action_box(\"Need to have at least a Last Name.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_person\");\n }\n else\n {\n # Create Name\n $query = \"INSERT names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # Get the just created name_id\n $query = \"SELECT id as new_name_id FROM names\n WHERE\n firstname = '\".$_POST['firstname'].\"' AND\n middlename = '\".$_POST['middlename'].\"' AND\n lastname = '\".$_POST['lastname'].\"' AND\n suffix = '\".$_POST['suffix'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n # Create Person with new_name_id\n $query = \"INSERT people\n SET\n preferred_name_id = '\".$new_name_id.\"',\n degree = '\".$_POST['degree'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # Get the just created person_id\n $query = \"SELECT id as new_person_id FROM people\n WHERE\n preferred_name_id = '\".$new_name_id.\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n # Sync them together with new_person_id\n $query = \"UPDATE names\n SET\n person_id = '\".$new_person_id.\"'\n WHERE\n id = '\".$new_name_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $after = find_person($new_person_id);\n\n action_box(\"Person Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$new_person_id);\n\n # log it\n mpact_logger(\"created person[\".$new_person_id.\"] (\".$after['fullname'].\")\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"remove_mentor\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if (remove_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']))\n {\n action_box(\"Mentor Removed\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['student_id']);\n }\n else\n {\n action_box(\"Nope.\");\n }\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);\n\n action_box(\"Mentor Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['student_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_student\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);\n\n action_box(\"Student Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['mentor_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_name\":\n \n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person($_POST['id']);\n\n $query = \"INSERT names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"',\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n # get the just created name_id\n $query = \"SELECT id as new_name_id FROM names\n WHERE\n firstname = '\".$_POST['firstname'].\"' AND\n middlename = '\".$_POST['middlename'].\"' AND\n lastname = '\".$_POST['lastname'].\"' AND\n suffix = '\".$_POST['suffix'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n \n # find that full name from the DB\n $added = find_name($new_name_id);\n\n action_box(\"Name Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n # log it\n mpact_logger(\"added name (\".$added['fullname'].\") for person[\".$_POST['id'].\"] (\".$person['fullname'].\")\");\n }\n else\n {\n not_admin();\n }\n \n break;\n\n ###############################################\n case \"edit_name\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $before = find_name($_POST['name_id']);\n \n $query = \"UPDATE names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"'\n WHERE\n id = '\".$_POST['name_id'].\"' AND\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $after = find_name($_POST['name_id']);\n\n # delete dotgraph for this person\n delete_associated_dotgraphs($_POST['id']);\n\n action_box(\"Name Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n # log it\n mpact_logger(\"edited name[\".$_POST['name_id'].\"] for person[\".$_POST['id'].\"] from (\".$before['fullname'].\") to (\".$after['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person(intval($_POST['person_id']));\n\n $query = \"INSERT urls\n SET\n url = '\".$_POST['url'].\"',\n description = '\".$_POST['description'].\"',\n updated_at = now(),\n person_id = '\".$_POST['person_id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Reference URL Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id'].\"#urls\");\n # log it\n mpact_logger(\"added URL[\".substr($_POST['url'], 0, 30).\"] for person[\".$_POST['person_id'].\"] (\".$person['fullname'].\")\");\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $url = find_url(intval($_POST['id']));\n $person = find_person($url['person_id']);\n\n $query = \"UPDATE urls\n SET\n url = '\".$_POST['url'].\"',\n description = '\".$_POST['description'].\"',\n updated_at = now()\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Reference URL Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$url['person_id'].\"#urls\");\n # log it\n mpact_logger(\"edited URL[\".substr($_POST['url'], 0, 30).\"] for person[\".$url['person_id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $url = find_url(intval($_POST['id']));\n $person = find_person($url['person_id']);\n\n $query = \"DELETE FROM urls\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Reference URL Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$url['person_id'].\"#urls\");\n # log it\n mpact_logger(\"deleted URL[\".substr($url['url'], 0, 30).\"] for person[\".$url['person_id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_degree\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person(intval($_POST['id']));\n\n $query = \"UPDATE people\n SET\n degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Degree Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$person['id']);\n # log it\n mpact_logger(\"edited degree[\".$_POST['degree'].\"] for person[\".$person['id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_dissertation\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $schools = find_schools();\n\n $person = find_person($_POST['person_id']);\n\n $query = \"INSERT INTO dissertations\n SET\n person_id = '\".$_POST['person_id'].\"',\n discipline_id = '\".$_POST['discipline_id'].\"',\n school_id = '\".$_POST['school_id'].\"',\n completedyear = '\".$_POST['completedyear'].\"',\n status = '\".$_POST['status'].\"',\n title = '\".$_POST['title'].\"',\n abstract = '\".$_POST['abstract'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE people\n SET degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['person_id'].\"'\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Dissertation Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id']);\n # log it\n $dissertation = find_dissertation_by_person($_POST['person_id']);\n mpact_logger(\"create dissertation[\".$dissertation['id'].\"] (\".$person['fullname'].\") with school[\".$dissertation['school_id'].\"] (\".$schools[$dissertation['school_id']].\") in year(\".$dissertation['completedyear'].\") with status (\".$statuscodes[$_POST['status']].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"edit_dissertation\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n\n $dissertation = find_dissertation($_POST['id']);\n $person = find_person($dissertation['person_id']);\n\n $query = \"UPDATE dissertations\n SET\n school_id = '\".$_POST['school_id'].\"',\n discipline_id = '\".$_POST['discipline_id'].\"',\n completedyear = '\".$_POST['completedyear'].\"',\n status = '\".$_POST['status'].\"',\n notes = '\".$_POST['notes'].\"',\n title = '\".$_POST['title'].\"',\n abstract = '\".$_POST['abstract'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE people\n SET degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['person_id'].\"'\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Dissertation Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id']);\n # log it\n mpact_logger(\"edit dissertation[\".$_POST['id'].\"] (\".$person['fullname'].\") from school[\".$dissertation['school_id'].\"] (\".$schools[$dissertation['school_id']].\") in year(\".$dissertation['completedyear'].\") to school[\".$_POST['school_id'].\"] (\".$schools[$_POST['school_id']].\") in year(\".$_POST['completedyear'].\")\");\n # look for changes\n # degree\n if ($person['degree'] != $_POST['degree'])\n {\n mpact_logger($dissertation['id'].\" updated degree [\".$_POST['degree'].\"]\",\"dissertation\");\n }\n # discipline\n if ($dissertation['discipline_id'] != $_POST['discipline_id'])\n {\n mpact_logger($dissertation['id'].\" updated discipline [\".$_POST['discipline_id'].\" (\".$disciplines[$_POST['discipline_id']].\")]\",\"dissertation\");\n }\n # school\n if ($dissertation['school_id'] != $_POST['school_id'])\n {\n mpact_logger($dissertation['id'].\" updated school [\".$_POST['school_id'].\" (\".$schools[$_POST['school_id']].\")]\",\"dissertation\");\n }\n # year\n if ($dissertation['completedyear'] != $_POST['completedyear'])\n {\n mpact_logger($dissertation['id'].\" updated completedyear [\".$_POST['completedyear'].\"]\",\"dissertation\");\n }\n # title\n if ($dissertation['title'] != $_POST['title'])\n {\n mpact_logger($dissertation['id'].\" updated title [\".$_POST['title'].\"]\",\"dissertation\");\n }\n # abstract\n if ($dissertation['abstract'] != $_POST['abstract'])\n {\n mpact_logger($dissertation['id'].\" updated abstract [\".$_POST['abstract'].\"]\",\"dissertation\");\n }\n # status\n if ($dissertation['status'] != $_POST['status'])\n {\n mpact_logger($dissertation['id'].\" updated status [\".$statuscodes[$_POST['status']].\"]\",\"dissertation\");\n }\n # status\n if ($dissertation['notes'] != $_POST['notes'])\n {\n mpact_logger($dissertation['id'].\" updated notes [\".$_POST['notes'].\"]\",\"dissertation\");\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_person\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if (delete_person($_POST['id']))\n {\n action_box(\"Person Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']); \n }\n \n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"delete_name\":\n \n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $name = find_name($_POST['name_id']);\n $person = find_person($_POST['id']);\n\n $query = \"DELETE FROM names\n WHERE\n id = '\".$_POST['name_id'].\"' AND\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Name Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n\n # log it\n mpact_logger(\"deleted name[\".$_POST['name_id'].\"] (\".$name['fullname'].\") from person[\".$person['id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n \n break;\n\n ###############################################\n default:\n // oops - not supposed to be here\n action_box(\"oops, back to the front page...\",2);\n\n\n }\n\n\n}\n\nxhtml_web_footer();\n\n?>\n", "mpact_include.php": " $val)\n foreach ($aSubtrahends as $aSubtrahend)\n if (array_key_exists($key, $aSubtrahend))\n unset ($ar1[$key]);\n return $ar1;\n}\n\n# -------------------------------------------------------------------------------\nfunction action_box($message,$bounce = \"0\",$location = \"index.php\"){\n\n echo \"\n

\n $message\n

\n

\n \";\n\n if ($bounce != \"0\"){\n echo \"\n \n

\n Forwarding in $bounce seconds (or click here to do the same)\n

\n \";\n }\n\n} \n\n# -------------------------------------------------------------------------------\nfunction xhtml_orig_web_header(){\n \n # make search box happy\n if (!isset($_POST['q'])){$_POST['q'] = \"\";}\n if (!isset($_POST['qta'])){$_POST['qta'] = \"\";}\n if (!isset($_POST['qn'])){$_POST['qn'] = \"\";}\n\n # print out header info\n echo \"\n \n \n \n \n MPACT\n \n \n \n \n\n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n
\n
\n MPACT -\n Database -\n \n People Search: \n
-\n
\n \n Title/Abstract Search: \n
\n\";\n if (is_admin()){\n echo \" -
\n \n Admin Notes Search: \n
\";\n }\n echo \"
\n\";\n if (is_admin()){\n echo $_SESSION['MPACT']['fullname'].\" (\".$_SESSION['MPACT']['username'].\") - Logout\";\n }\n else{\n $host_info = get_environment_info();\n if ($host_info['hostname'] != \"sils\"){\n echo \"Login\";\n }\n }\necho \"\n
\n

\n\n \";\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_web_header(){\n \n # make search box happy\n if (!isset($_POST['q'])){$_POST['q'] = \"\";}\n if (!isset($_POST['qta'])){$_POST['qta'] = \"\";}\n if (!isset($_POST['qn'])){$_POST['qn'] = \"\";}\n\n # print out header info\n echo \"\n \n \n \n \n MPACT\n \n \n \n \n \n \n\";\n\necho \"

\";\nif (is_admin()){\n echo $_SESSION['MPACT']['fullname'].\" (\".$_SESSION['MPACT']['username'].\") - Logout\";\n}\nelse{\n echo \"Login\";\n}\necho \"

\";\necho \"
\";\n\necho \"\n
\n \n \n \n \n \n \n\n \n \n \n
\n \n \n \n \n Publications  • \n Project Statistics\n
\n
\n Glossary  • \n Schools  • \n Disciplines\n
\n
\n \n People Search: \n
\n    \n
\n \n Title/Abstract Search: \n
\";\nif (is_admin()){\n echo \"

Administrator Pages\";\n echo \"
\n \n Admin Notes Search: \n
\";\n}\necho \"
\n \n
\n
\n\n
\n
\n\n
\n\n \";\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_web_footer(){\n echo \"\n\n
\n\n \n \n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction is_email_valid ($address)\n{\n\n\t# http://www.zend.com/codex.php?id=285&single=1\n\n return (preg_match(\n '/^[-!#$%&\\'*+\\\\.\\/0-9=?A-Z^_`{|}~]+'. // the user name\n '@'. // the ubiquitous at-sign\n '([-0-9A-Z]+\\.)+' . // host, sub-, and domain names\n '([0-9A-Z]){2,4}$/i', // top-level domain (TLD)\n trim($address)));\n}\n\n# -------------------------------------------------------------------------------\nfunction find_glossaryterms()\n{\n $query = \"SELECT id, term, definition FROM glossary\";\n $result = mysql_query($query) or die(mysql_error());\n $glossaryterms = array();\n while ( $line = mysql_fetch_array($result)) {\n $glossaryterms['ids'][$line['term']] = $line['id'];\n $glossaryterms['defs'][$line['id']] = $line['definition'];\n }\n return $glossaryterms;\n}\n\n# -------------------------------------------------------------------------------\nfunction show_glossary()\n{\n $query = \"SELECT id, term, definition FROM glossary ORDER BY term ASC\";\n $result = mysql_query($query) or die(mysql_error());\n\n $results = array();\n while ( $line = mysql_fetch_array($result)) {\n array_push($results,$line);\n }\n\n echo \"

Glossary

\\n\";\n\n echo \"

\\n\";\n\n foreach ($results as $one)\n {\n echo \"\".$one['term'].\": \";\n echo $one['definition'];\n if (is_admin())\n {\n echo \" EDIT \";\n }\n echo \"

\";\n }\n\n echo \"

\\n\";\n\n}\n\n# -------------------------------------------------------------------------------\nfunction show_glossaryterm($id)\n{\n $query = \"SELECT id, term, definition FROM glossary WHERE id = $id\";\n $result = mysql_query($query) or die(mysql_error());\n\n $results = array();\n while ( $line = mysql_fetch_array($result)) {\n $glossaryterm = $line;\n }\n\n echo \"

Full Glossary Listing

\";\n\n echo \"

Glossary

\\n\";\n\n echo \"

\\n\";\n\n echo \"\".$glossaryterm['term'].\": \";\n echo $glossaryterm['definition'];\n if (is_admin())\n {\n echo \" EDIT \";\n }\n echo \"

\";\n\n echo \"

\\n\";\n\n}\n\n# -------------------------------------------------------------------------------\nfunction show_alphabet()\n{\n\n $alphabet_letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n $alphabet = preg_split('//', $alphabet_letters, -1, PREG_SPLIT_NO_EMPTY);\n\n echo \"
\\n\";\n echo \"

Dissertation Authors and Mentors by Last Name

\";\n echo \"

\";\n foreach ($alphabet as $letter)\n {\n if ($letter != \"A\"){echo \" - \";}\n echo \"$letter\";\n }\n echo \"

\";\n echo \"
\\n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction search_box($q=\"\")\n{\n echo \"
\\n\";\n echo \"\\n\";\n echo \"

People Search: \";\n if ($q)\n {\n echo \"\\n\"; \n }\n else\n {\n echo \"\\n\"; \n }\n echo \"

\\n\";\n echo \"
\\n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction people_search($q)\n{\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = split(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$pieces[0].\"%' OR\n n.middlename LIKE '%\".$pieces[0].\"%' OR\n n.lastname LIKE '%\".$pieces[0].\"%' OR\n n.suffix LIKE '%\".$pieces[0].\"%')\n \n AND\n \n (n.firstname LIKE '%\".$pieces[1].\"%' OR\n n.middlename LIKE '%\".$pieces[1].\"%' OR\n n.lastname LIKE '%\".$pieces[1].\"%' OR\n n.suffix LIKE '%\".$pieces[1].\"%')\n \n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$pieces[0].\"%' OR\n n.middlename LIKE '%\".$pieces[0].\"%' OR\n n.lastname LIKE '%\".$pieces[0].\"%' OR\n n.suffix LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (n.firstname LIKE '%\".$pieces[1].\"%' OR\n n.middlename LIKE '%\".$pieces[1].\"%' OR\n n.lastname LIKE '%\".$pieces[1].\"%' OR\n n.suffix LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (n.firstname LIKE '%\".$pieces[2].\"%' OR\n n.middlename LIKE '%\".$pieces[2].\"%' OR\n n.lastname LIKE '%\".$pieces[2].\"%' OR\n n.suffix LIKE '%\".$pieces[2].\"%')\n \n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$q.\"%' OR\n n.middlename LIKE '%\".$q.\"%' OR\n n.lastname LIKE '%\".$q.\"%' OR\n n.suffix LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction title_abstract_search($q)\n{\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = split(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$pieces[0].\"%' OR\n d.abstract LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (d.title LIKE '%\".$pieces[1].\"%' OR\n d.abstract LIKE '%\".$pieces[1].\"%')\n \n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$pieces[0].\"%' OR\n d.abstract LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (d.title LIKE '%\".$pieces[1].\"%' OR\n d.abstract LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (d.title LIKE '%\".$pieces[2].\"%' OR\n d.abstract LIKE '%\".$pieces[2].\"%')\n \n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$q.\"%' OR\n d.abstract LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction notes_search($q)\n{\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = split(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (d.notes LIKE '%\".$pieces[1].\"%')\n \n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (d.notes LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (d.notes LIKE '%\".$pieces[2].\"%')\n \n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction encode_linebreaks($bigtext)\n{\n # from http://us3.php.net/str_replace\n $order = array(\"\\r\\n\", \"\\n\", \"\\r\");\n $replace = '
';\n // Processes \\r\\n's first so they aren't converted twice.\n $with_breaks = str_replace($order, $replace, $bigtext);\n return $with_breaks;\n}\n\n# -------------------------------------------------------------------------------\nfunction get_logs($offset=\"0\")\n{\n# echo \"[$offset]\";\n $query = \"SELECT * FROM logs ORDER BY id DESC LIMIT 100\";\n if ($offset != \"\"){$query .= \" OFFSET $offset\";}\n $result = mysql_query($query) or die(mysql_error());\n\n# echo $query;\n $entries = array();\n $counter = 0;\n while ( $line = mysql_fetch_array($result)) {\n $counter++;\n $entries[$counter] = $line;\n }\n return $entries;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction get_dissertation_history($id)\n{\n $query = \"SELECT * FROM logs\n WHERE type='dissertation' AND message LIKE '$id %'\n ORDER BY id DESC\";\n $result = mysql_query($query) or die(mysql_error());\n\n# echo $query;\n $entries = array();\n $counter = 0;\n while ( $line = mysql_fetch_array($result)) {\n $counter++;\n $entries[$counter] = $line;\n }\n return $entries;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction find_all_people()\n{\n # return array of all people_ids in database (slow....)\n # all people\n $query = \"SELECT id as person_id FROM people\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $people[] = $line['person_id'];\n }\n return $people;\n}\n\n# -------------------------------------------------------------------------------\nfunction get_person_link($person_id)\n{\n\n $disciplines = find_disciplines();\n $person = find_person($person_id);\n\n $fullname = trim($person['firstname'].\" \".$person['middlename'].\" \".$person['lastname'].\" \".$person['suffix']);\n\n $dissertation = find_dissertation_by_person($person_id);\n $discipline = isset($dissertation['discipline_id']) ? $disciplines[$dissertation['discipline_id']] : \"\";\n \n $link = \"\".$fullname.\"\";\n\n return $link;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_orphans()\n{\n\n # finding people with no dissertation and no students\n\n # all people\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n\n WHERE\n p.preferred_name_id = n.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $people[$line['person_id']] = $line;\n# echo \" \".$line['person_id'].\"
\\n\";\n }\n \n echo \"people: \".count($people).\"
\\n\";\n\n # with dissertations only\n $query = \"SELECT\n p.id as person_id\n FROM\n people p, dissertations d\n WHERE\n d.person_id = p.id\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $with_dissertations[$line['person_id']] = $line;\n# echo \" \".$line['person_id'].\"
\\n\";\n }\n\n echo \"dissertations: \".count($with_dissertations).\"
\\n\";\n\n # all people - dissertations = teachers only\n $potentialmentors = array_key_diff($people,$with_dissertations);\n\n echo \"potential mentors: \".count($potentialmentors).\"
\\n\";\n\n # orphans = teachers who don't have students\n # get advisorships\n $query = \"SELECT person_id FROM advisorships\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[$line['person_id']] = $line;\n }\n echo \"advisors: \".count($advisors).\"
\\n\";\n # get committeeships\n $query = \"SELECT person_id FROM committeeships\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[$line['person_id']] = $line;\n }\n echo \"committeemembers: \".count($committeemembers).\"
\\n\";\n # subtract advisorships from teachers\n $potentialmentors = array_key_diff($potentialmentors,$advisors);\n # subtract committeeships from remaining teachers\n $orphans = array_key_diff($potentialmentors,$committeemembers);\n echo \"orphans: \".count($orphans).\"
\\n\";\n\n return $orphans;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction is_orphan($person_id)\n{\n # confirm person exists\n $query = \"SELECT * FROM people WHERE id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n $line = mysql_fetch_array($result);\n if (!$line['id']){echo \"not a person\";return 0;}\n # confirm no dissertation\n $query = \"SELECT * FROM dissertations WHERE person_id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n echo \"found a dissertation\";\n return 0;\n }\n # confirm not a committeemember\n $query = \"SELECT * FROM committeeships WHERE person_id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n echo \"found a committeeship\";\n return 0;\n }\n # confirm not an advisor\n $query = \"SELECT * FROM advisorships WHERE person_id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n echo \"found an advisorship\";\n return 0;\n }\n return 1;\n}\n# -------------------------------------------------------------------------------\nfunction delete_person($person_id)\n{\n if (is_orphan($person_id))\n {\n $before = find_person($person_id);\n # delete all names\n $query = \"DELETE FROM names WHERE person_id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n # delete the person\n $query = \"DELETE FROM people WHERE id = '\".$person_id.\"' LIMIT 1\";\n $result = mysql_query($query) or die(mysql_error());\n # log it\n mpact_logger(\"deleted person[\".$person_id.\"] (\".$before['fullname'].\")\");\n return 1;\n }\n else\n {\n action_box(\"Not an orphan - Cannot delete this person.\");\n return 0;\n }\n}\n# -------------------------------------------------------------------------------\nfunction remove_duplicate_names($person_id)\n{\n\n $names = array();\n $deleteme = array();\n\n\n $before = find_person($person_id);\n\n // get the preferred_name_id\n $query = \"SELECT preferred_name_id\n FROM people\n WHERE id = '\".$person_id.\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n // get the full preferred_name\n $query = \"SELECT * FROM names\n WHERE\n id = '\".$preferred_name_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $fullname = \"\".$line['firstname'].\" \".$line['middlename'].\" \".$line['lastname'].\" \".$line['suffix'].\"\";\n $names[$fullname] = $line['id']; \n }\n\n // get the rest of the names for this person\n $query = \"SELECT * FROM names\n WHERE\n person_id = '\".$person_id.\"' AND\n id != '\".$preferred_name_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $fullname = \"\".$line['firstname'].\" \".$line['middlename'].\" \".$line['lastname'].\" \".$line['suffix'].\"\";\n if (isset($names[$fullname]))\n {\n $deleteme[] = $line['id'];\n }\n else\n {\n $names[$fullname] = $line['id']; \n }\n }\n\n // delete each deleteme id\n foreach ($deleteme as $one)\n {\n $query = \"DELETE FROM names\n WHERE\n id = '\".$one.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n }\n\n # log it\n mpact_logger(\"removed duplicate names for person[\".$person_id.\"] (\".$before['fullname'].\")\");\n\n}\n\n# -------------------------------------------------------------------------------\nfunction add_mentor($type,$student_id,$mentor_id)\n{\n $student = find_person($student_id);\n $mentor = find_person($mentor_id);\n $dissertation = find_dissertation_by_person($student_id);\n\n if ($type == \"A\")\n {\n # find existing advisors for this student\n $advisors = find_advisors_for_person($student_id);\n # if new/different - then add them to the student's dissertation\n if (in_array($mentor_id,$advisors))\n {\n # skip - already listed as advisor\n }\n else\n {\n $query = \"INSERT advisorships\n SET\n dissertation_id = '\".$dissertation['id'].\"',\n person_id = '\".$mentor_id.\"'\n \";\n# echo $query;\n $result = mysql_query($query) or die(mysql_error());\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"add advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n # delete existing dotgraphs - they'll need to be regenerated\n # has to happen after we add the advisor link itself\n delete_associated_dotgraphs($student_id);\n }\n }\n elseif ($type == \"C\")\n {\n # find existing committee members for this student\n $committee = find_committee_for_person($student_id);\n # if new/different - then add them to the student's dissertation \n if (in_array($mentor_id,$committee))\n {\n # skip - already on committee\n }\n else\n {\n $query = \"INSERT committeeships\n SET\n dissertation_id = '\".$dissertation['id'].\"',\n person_id = '\".$mentor_id.\"'\n \";\n# echo $query;\n $result = mysql_query($query) or die(mysql_error());\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"add committeeship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n }\n }\n else\n {\n # nothing\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction remove_mentor($type,$student_id,$mentor_id)\n{\n $dissertation = find_dissertation_by_person($student_id);\n\n $student = find_person($student_id);\n $mentor = find_person($mentor_id);\n\n if ($type == \"A\")\n {\n # find dissertation id\n $dissertation = find_dissertation_by_person($student_id);\n # find existing advisors for this student\n $advisors = find_advisors_for_person($student_id);\n # if found in db, remove them\n if (!in_array($mentor_id,$advisors))\n {\n echo \"not an advisor for this student\";\n return 0;\n }\n else\n {\n # delete existing dotgraphs - they'll need to be regenerated\n # has to happen before we delete the advisor link itself\n delete_associated_dotgraphs($student_id);\n # delete the advisorship\n $query = \"DELETE FROM advisorships\n WHERE\n person_id = '\".$mentor_id.\"' AND\n dissertation_id = '\".$dissertation['id'].\"'\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"remove advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n return 1;\n }\n }\n elseif ($type == \"C\")\n {\n # find dissertation id\n $dissertation = find_dissertation_by_person($student_id);\n # find existing committee members for this student\n $committee = find_committee_for_person($student_id);\n # if found in db, remove them \n if (!in_array($mentor_id,$committee))\n {\n echo \"not on committee for this student\";\n return 0;\n }\n else\n {\n $query = \"DELETE FROM committeeships\n WHERE\n person_id = '\".$mentor_id.\"' AND\n dissertation_id = '\".$dissertation['id'].\"'\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"remove advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n return 1;\n }\n }\n else\n {\n echo \"has to be A or C, dude\";\n return 0;\n }\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_all_people_for_selectbox($with_dissertation=\"0\")\n{\n if ($with_dissertation == \"0\")\n {\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n\n WHERE\n p.preferred_name_id = n.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \"; \n }\n else\n {\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n, dissertations d\n WHERE\n p.preferred_name_id = n.id AND\n d.person_id = p.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n }\n // echo $query;\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $people[$line['person_id']] = $line;\n }\n\n return $people;\n}\n\n# -------------------------------------------------------------------------------\nfunction merge_two_people($from_id, $into_id)\n{\n\n $from_person = find_person($from_id);\n $into_person = find_person($into_id);\n \n\n $query = \"UPDATE advisorships\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE dissertations\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE committeeships\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE urls\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n // move each 'from' name to the 'into' person\n \n $query = \"UPDATE names\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n // remove any new duplicates in the names table\n \n remove_duplicate_names($into_person['id']); \n\n // remove 'from' person from the database\n \n $query = \"DELETE FROM people\n WHERE\n id = '\".$from_person['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n # log it\n mpact_logger(\"merged two people [\".$from_id.\"] (\".$from_person['fullname'].\") and [\".$into_id.\"] (\".$into_person['fullname'].\")\");\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_aliases($person_id)\n{\n\n $query = \"SELECT preferred_name_id\n FROM people\n WHERE id = '\".$person_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n $names = array();\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, n.id\n FROM\n names n\n WHERE\n n.person_id = '\".$person_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $names[$line['id']] = $line;\n }\n\n unset($names[$preferred_name_id]);\n \n return $names;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_person($person_id)\n{\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, p.degree,\n p.id, p.preferred_name_id\n FROM\n names n, people p\n WHERE\n p.preferred_name_id = n.id AND\n p.id = \".$person_id.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $person = $line;\n $person['fullname'] = $person['firstname'];\n if ($person['middlename'] != \"\"){$person['fullname'] .= \" \".$person['middlename'];}\n if ($person['lastname'] != \"\"){$person['fullname'] .= \" \".$person['lastname'];}\n if ($person['suffix'] != \"\"){$person['fullname'] .= \" \".$person['suffix'];}\n }\n\n return $person;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_url($url_id)\n{\n\n $url_id = intval($url_id);\n $query = \"SELECT\n u.id, u.url, u.description, u.updated_at, u.person_id\n FROM\n urls u\n WHERE\n u.id = '\".$url_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $url = $line;\n }\n\n return $url;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_urls_by_person($person_id)\n{\n\n $person_id = intval($person_id);\n $query = \"SELECT\n u.id, u.url, u.description, u.updated_at, u.person_id\n FROM\n urls u\n WHERE\n u.person_id = '\".$person_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $urls = array();\n while ( $line = mysql_fetch_array($result)) {\n $urls[$line['id']] = $line;\n }\n\n return $urls;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dissertation($dissertation_id)\n{\n\n $dissertation_id = intval($dissertation_id);\n $query = \"SELECT\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n WHERE\n d.id = '\".$dissertation_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertation = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertation = $line;\n }\n\n return $dissertation;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dissertation_by_person($person_id)\n{\n\n $person_id = intval($person_id);\n $query = \"SELECT\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n WHERE\n d.person_id = '\".$person_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertation = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertation = $line;\n }\n\n return $dissertation;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_name($name_id)\n{\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix\n FROM\n names n\n WHERE\n n.id = \".$name_id.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $name = $line;\n $name['fullname'] = $name['firstname'];\n if ($name['middlename'] != \"\"){$name['fullname'] .= \" \".$name['middlename'];}\n if ($name['lastname'] != \"\"){$name['fullname'] .= \" \".$name['lastname'];}\n if ($name['suffix'] != \"\"){$name['fullname'] .= \" \".$name['suffix'];}\n }\n\n return $name;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline($discipline_id)\n{\n $discipline_id = intval($discipline_id);\n $query = \"SELECT\n d.title, d.description\n FROM\n disciplines d\n WHERE\n d.id = \".$discipline_id.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $discipline = $line;\n }\n\n return $discipline;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_ancestors_for_group($groupofpeople)\n{\n $originalgroup = $groupofpeople;\n // find advisors, and if they're new, add them to the list and recurse\n foreach ($originalgroup as $person)\n {\n $advisors = find_advisors_for_person($person);\n foreach ($advisors as $one)\n {\n $groupofpeople[] = $one;\n }\n }\n $groupofpeople = array_unique($groupofpeople);\n if (count(array_diff($groupofpeople,$originalgroup)) > 0)\n {\n return find_ancestors_for_group($groupofpeople);\n }\n else\n {\n return $originalgroup;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_descendents_for_group($groupofpeople)\n{\n $originalgroup = $groupofpeople;\n // find descendents, and if they're new, add them to the list and recurse\n foreach ($originalgroup as $person)\n {\n $advisees = find_advisorships_under_person($person);\n foreach ($advisees as $one)\n {\n $groupofpeople[] = $one;\n }\n }\n $groupofpeople = array_unique($groupofpeople);\n if (count(array_diff($groupofpeople,$originalgroup)) > 0)\n {\n return find_descendents_for_group($groupofpeople);\n }\n else\n {\n return $originalgroup;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction T_score($person)\n{\n # total number of descendants (nodes) in a person's tree\n $group = array($person);\n $total = count(find_descendents_for_group($group)); # including self\n $descendents = $total - 1; # minus self\n return $descendents;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_mpact_score($person,$score_type)\n{\n $query = \"SELECT $score_type as score FROM people WHERE id='$person'\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n return $score;\n}\n\n# -------------------------------------------------------------------------------\nfunction FMI_score($person)\n{\n $FMI_score = count(find_advisorships_under_person($person));\n# print \"person $person -- fmi $FMI_score
\";\n $committeeships = find_committeeships_under_person($person);\n foreach ($committeeships as $one)\n {\n $numA = count(find_advisors_for_person($one));\n# echo \" - #A [$numA] ----
\";\n $numC = count(find_committee_for_person($one));\n# echo \"#C [$numC] ---- \\n\";\n $FMI_score += 1/($numA + $numC);\n# echo \"
\";\n }\n // echo \"fractional mentorship, inclusive (FMI = A + eachC(1/(#A+#C)) )
\\n\";\n return round($FMI_score,3);\n}\n\n# -------------------------------------------------------------------------------\nfunction FME_score($person)\n{\n $FME_score = count(find_advisorships_under_person($person));\n# print \"person $person -- fme $FME_score
\";\n $committeeships = find_committeeships_under_person($person);\n foreach ($committeeships as $one)\n {\n $numC = count(find_committee_for_person($one));\n# echo \"#C [$numC] ---- \\n\";\n $FME_score += 1/($numC);\n# echo \"
\";\n }\n // echo \"fractional mentorship, inclusive (FMI = A + eachC(1/(#A+#C)) )
\\n\";\n return round($FME_score,3);\n}\n\n# -------------------------------------------------------------------------------\nfunction TA_score($person)\n{\n # total number of descendants who have advised students themselves\n $without_students = array();\n $descendents = find_descendents_for_group(array($person)); # including self\n foreach ($descendents as $d)\n {\n if (count(find_descendents_for_group(array($d))) == 1)\n {\n $without_students[] = $d;\n }\n }\n $descendents_who_advised = array_diff($descendents,$without_students); # including self\n return max(count($descendents_who_advised) - 1,0); # minus self\n}\n\n# -------------------------------------------------------------------------------\nfunction W_score($person)\n{\n # should handle multigenerational advisorships correctly...\n\n # return the max of the widths of each generation of descendents\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n# print \"$gencount <-- gen
\";\n# print count($advisees).\" advisees - \";\n# print_r($advisees);\n# print \"
\";\n# print \"
\";\n# print count($remaining).\" remaining - \";\n# print_r($remaining);\n# print \"
\";\n# print \"
\";\n while (count($remaining) > 0)\n {\n $gencount++;\n# print \"$gencount <-- gen
\";\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n# print count($advisees).\" advisees - \";\n# print_r($advisees);\n# print \"
\";\n# print \"
\";\n# print count($remaining).\" remaining - \";\n# print_r($remaining);\n# print \"
\";\n# print \"
\";\n }\n# print_r($gen_widths);\n return max($gen_widths);\n}\n\n# -------------------------------------------------------------------------------\nfunction TD_score($person)\n{\n # there is currently a bug in this implementation\n # if a student has two advisors, and they, themselves are related by mentorship\n # this algorithm currently counts gen_width based on advisee count only\n # since $td is calculated based on gen_width values, TD will be missing data\n # A is advisor to B and C\n # B is advisor to C\n # A should have a TD score of 2 (full credit for both advisees)\n # upon further reflection, perhaps this is working correctly, by accident\n\n # return the decayed score\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n while (count($remaining) > 0)\n {\n $gencount++;\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n }\n# print_r($gen_widths);\n $td = 0;\n foreach($gen_widths as $one => $two)\n {\n $num = $two;\n $den = (pow(2,($one-1)));\n $f = $num/$den;\n# print \"$num/$den = $f
\";\n $td = $td + $f;\n }\n return $td;\n}\n\n# -------------------------------------------------------------------------------\nfunction G_score($person)\n{\n # there is currently a bug in this implementation\n # if a student has two advisors, and they, themselves are related by mentorship\n # this algorithm currently misses a generation in the calculation of G\n # A is advisor to B and C\n # B is advisor to C\n # A should have a G score of 2, but will only be calculated a 1\n\n\n # return the number of generations of descendents\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n while (count($remaining) > 0)\n {\n $gencount++;\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n }\n if ($gen_widths[1] == 0)\n {\n return 0;\n }\n else\n {\n return count($gen_widths);\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction advisees_of_group($group)\n{\n # W helper function\n $advisees = array();\n foreach ($group as $one)\n {\n $advisees[] = find_advisorships_under_person($one);\n }\n $advisees = flattenArray($advisees);\n# print_r($advisees);\n# print \" <-- advisees of group
\";\n return $advisees;\n}\n\n# -------------------------------------------------------------------------------\nfunction flattenArray($array) \n{\n $flatArray = array();\n foreach( $array as $subElement ) {\n if( is_array($subElement) )\n $flatArray = array_merge($flatArray, flattenArray($subElement));\n else\n $flatArray[] = $subElement;\n }\n return $flatArray;\n}\n\n# -------------------------------------------------------------------------------\nfunction calculate_scores($person_id)\n{\n $A_score = count(find_advisorships_under_person($person_id));\n $C_score = count(find_committeeships_under_person($person_id));\n $AC_score = $A_score + $C_score;\n $G_score = G_score($person_id);\n $W_score = W_score($person_id);\n $T_score = T_score($person_id);\n $TA_score = TA_score($person_id);\n $TD_score = TD_score($person_id);\n $FMI_score = FMI_score($person_id);\n $FME_score = FME_score($person_id);\n\n $query = \"UPDATE people\n SET\n a_score = '$A_score',\n c_score = '$C_score',\n ac_score = '$AC_score',\n g_score = '$G_score',\n w_score = '$W_score',\n t_score = '$T_score',\n ta_score = '$TA_score',\n td_score = '$TD_score',\n fmi_score = '$FMI_score',\n fme_score = '$FME_score',\n scores_calculated = now()\n WHERE\n id = \".$person_id.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n}\n\n# -------------------------------------------------------------------------------\nfunction mpact_scores($passed_person)\n{\n $glossaryterms = find_glossaryterms();\n\n $query = \"SELECT\n a_score, c_score, ac_score, g_score, w_score,\n t_score, ta_score, td_score, fmi_score, fme_score,\n scores_calculated\n FROM people\n WHERE id = \".$passed_person.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n \n $mpact['A'] = $a_score;\n $mpact['C'] = $c_score;\n $mpact['AC'] = $ac_score;\n $scores_output = \"A = $a_score
\\n\";\n $scores_output .= \"C = $c_score
\\n\";\n $scores_output .= \"A+C = $ac_score
\\n\";\n\n $mpact['FMI'] = $fmi_score;\n $mpact['FME'] = $fme_score;\n $FMIdivFULL = ($ac_score>0) ? $fmi_score / $ac_score : 0;\n $FMIdivFULL = round($FMIdivFULL,3);\n $mpact['FMIdivFULL'] = $FMIdivFULL;\n $FMEdivFULL = ($ac_score>0) ? $fme_score / $ac_score : 0;\n $FMEdivFULL = round($FMEdivFULL,3);\n $mpact['FMEdivFULL'] = $FMEdivFULL;\n if (is_admin())\n {\n $scores_output .= \"FMI = $fmi_score
\\n\";\n $scores_output .= \"FME = $fme_score
\\n\";\n $scores_output .= \"FMI/(A+C) = $FMIdivFULL
\\n\";\n $scores_output .= \"FME/(A+C) = $FMEdivFULL
\\n\";\n }\n\n $mpact['T'] = $t_score;\n $scores_output .= \"T = $t_score
\\n\";\n $mpact['G'] = $g_score;\n $scores_output .= \"G = $g_score
\\n\";\n $mpact['W'] = $w_score;\n $scores_output .= \"W = $w_score
\\n\";\n $mpact['TD'] = $td_score;\n $scores_output .= \"D']].\"\\\">TD = $td_score
\\n\";\n $mpact['TA'] = $ta_score;\n $scores_output .= \"A']].\"\\\">TA = $ta_score
\\n\";\n $scores_output .= \"calculated $scores_calculated
\\n\";\n $mpact['output'] = $scores_output;\n\n return $mpact;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_advisors_for_person($person_id)\n{\n\n // get person's own advisor(s)\n\n $listing = array();\n\n\n $query = \"SELECT a.person_id\n FROM\n dissertations d,\n advisorships a\n WHERE\n d.person_id = \".$person_id.\" AND\n a.dissertation_id = d.id\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_committee_for_person($person_id)\n{\n\n // get person's own committee member(s)\n\n $listing = array();\n\n $query = \"SELECT c.person_id\n FROM\n dissertations d,\n committeeships c\n WHERE\n d.person_id = \".$person_id.\" AND\n c.dissertation_id = d.id\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_advisorships_under_person($person_id)\n{\n\n // get person's advisorships (below)\n\n $listing = array();\n\n $query = \"SELECT d.person_id\n FROM\n dissertations d,\n advisorships a\n WHERE\n a.person_id = \".$person_id.\" AND\n a.dissertation_id = d.id\n ORDER BY\n d.completedyear ASC\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_committeeships_under_person($person_id)\n{\n\n // get person's committeeships (below)\n\n $listing = array();\n\n $query = \"SELECT d.person_id\n FROM\n dissertations d,\n committeeships c\n WHERE\n c.person_id = '\".$person_id.\"' AND\n c.dissertation_id = d.id\n ORDER BY\n d.completedyear\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction set_preferred_name($person_id,$name_id)\n{\n\n # delete current family tree of dotgraphs\n delete_associated_dotgraphs($person_id);\n\n # set it\n\n $listing = array();\n\n $before = find_person($person_id);\n\n $query = \"UPDATE people\n SET\n preferred_name_id = '\".$name_id.\"'\n WHERE\n id = '\".$person_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $after = find_person($person_id);\n\n # log it\n mpact_logger(\"set preferred name for person[\".$person_id.\"] from name[\".$before['preferred_name_id'].\"] (\".$before['fullname'].\") to name[\".$name_id.\"] (\".$after['fullname'].\")\");\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_profs_at_dept($school_id,$discipline_id)\n{\n\n $dissertations = array();\n $listing = array();\n $advisors = array();\n $committeemembers = array();\n\n // get all dissertations at this dept\n\n $query = \"SELECT d.id\n FROM dissertations d, schools s\n WHERE\n d.school_id = s.id AND\n s.id = '\".$school_id.\"' AND\n d.discipline_id = '\".$discipline_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $dissertations[] = $line['id'];\n }\n\n if (count($dissertations)>0)\n {\n // get all advisors for these dissertations\n\n $query = \"SELECT a.person_id\n FROM dissertations d, advisorships a\n WHERE\n a.dissertation_id IN (\";\n $query .= implode(\", \", $dissertations);\n $query .= \") AND\n a.dissertation_id = d.id\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $advisors[$line['person_id']] = $line['person_id'];\n }\n \n // get all committeemembers for these dissertations\n\n $query = \"SELECT c.person_id\n FROM dissertations d, committeeships c\n WHERE\n c.dissertation_id IN (\";\n $query .= implode(\", \", $dissertations);\n $query .= \") AND\n c.dissertation_id = d.id\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $committeemembers[$line['person_id']] = $line['person_id'];\n }\n }\n\n // return the combined list (uniquified when combined)\n\n// echo \"\\na - \".count($advisors);\n// echo \"\\nc - \".count($committeemembers);\n $listing = $advisors + $committeemembers;\n// echo \"\\ncombined before - \".count($listing);\n return $listing;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_profs_at_dept($school_id,$discipline_id)\n{\n $query = \"SELECT professors\n FROM profs_at_dept\n WHERE\n school_id = '$school_id' AND\n discipline_id = '$discipline_id'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result))\n {\n $listing = unserialize($line['professors']);\n }\n return $listing;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_disciplines($school_id=null)\n{\n\n $disciplines = array();\n if ($school_id)\n {\n // get all disciplines at this school\n $query = \"SELECT d.id, d.title\n FROM\n disciplines d, schools s, dissertations diss\n WHERE\n diss.school_id = s.id AND\n diss.discipline_id = d.id AND\n s.id = '$school_id'\n ORDER BY\n d.title\n \";\n }\n else\n {\n $query = \"SELECT id, title\n FROM\n disciplines d\n ORDER BY\n title\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $disciplines[$line['id']] = $line['title'];\n }\n\n if (isset($disciplines))\n {\n return $disciplines;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction is_duplicate_discipline($title)\n{\n $disciplinefound = 0;\n\n $query = \"SELECT id FROM disciplines WHERE title = '$title'\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $disciplinefound = $line['id'];\n }\n\n if ($disciplinefound > 0){\n return true;\n }\n\n return false;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_empty_discipline($discipline_id)\n{\n $query = \"SELECT count(*) as howmany FROM dissertations WHERE discipline_id = $discipline_id\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n extract($line);\n }\n\n if ($howmany > 0){\n return false;\n }\n\n return true;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_duplicate_school($fullname)\n{\n $schoolfound = 0;\n\n $query = \"SELECT id FROM schools WHERE fullname = '$fullname'\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $schoolfound = $line['id'];\n }\n\n if ($schoolfound > 0){\n return true;\n }\n\n return false;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_empty_school($school_id)\n{\n $query = \"SELECT count(*) as howmany FROM dissertations WHERE school_id = $school_id\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n extract($line);\n }\n\n if ($howmany > 0){\n return false;\n }\n\n return true;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline_counts()\n{\n \n // get all discipline counts from the database\n\n $disciplinecounts = array();\n \n $query = \"SELECT discipline_id, count(*) as disciplinecount\n FROM dissertations\n GROUP BY discipline_id\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $disciplinecounts[$line['discipline_id']] = $line['disciplinecount'];\n }\n\n if (isset($disciplinecounts))\n {\n return $disciplinecounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline_statuses($discipline_id)\n{\n\n // get status counts for this discipline\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n \n $query = \"SELECT status, count(*) as disciplinecount\n FROM dissertations\n WHERE discipline_id='$discipline_id'\n GROUP BY status\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disciplinecount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dept_counts($school_id,$discipline_id)\n{\n \n // get all department counts from the database\n\n $deptcounts = array();\n \n $query = \"SELECT discipline_id, count(*) as disciplinecount\n FROM dissertations\n GROUP BY discipline_id\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $deptcounts[$line['discipline_id']] = $line['disciplinecount'];\n }\n\n if (isset($deptcounts))\n {\n return $deptcounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dept_statuses($school_id,$discipline_id)\n{\n\n // get status counts for this school in this discipline\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n \n $query = \"SELECT status, count(*) as disciplinecount\n FROM dissertations\n WHERE\n discipline_id='$discipline_id' AND\n school_id='$school_id'\n GROUP BY status\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disciplinecount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_schools($discipline_id=null)\n{\n // get all schools in a discipline (or all disciplines)\n $schools = array();\n if ($discipline_id)\n {\n // look up schools at dissertations in this discipline\n $query = \"SELECT s.id, s.fullname\n FROM\n dissertations d, schools s\n WHERE\n d.school_id = s.id AND\n d.discipline_id = '$discipline_id'\n GROUP BY\n d.school_id\n ORDER BY\n s.fullname ASC\n \";\n }\n else\n {\n $query = \"SELECT id, fullname\n FROM\n schools s\n ORDER BY fullname\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result))\n {\n $schools[$line['id']] = $line['fullname'];\n }\n\n if (isset($schools))\n {\n return $schools;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school_counts()\n{\n \n // get all school dissertation counts from the database\n\n $schoolcounts = array();\n \n $query = \"SELECT school_id, count(*) as disscount\n FROM dissertations\n GROUP BY school_id\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $schoolcounts[$line['school_id']] = $line['disscount'];\n }\n\n if (isset($schoolcounts))\n {\n return $schoolcounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school_statuses($school_id)\n{\n\n // get status counts for this school\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n \n $query = \"SELECT status, count(*) as disscount\n FROM dissertations\n WHERE school_id='$school_id'\n GROUP BY status\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disscount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction find_persons_school($passed_person)\n{\n\n // get person's degree school\n\n $query = \"SELECT\n d.id as dissertation_id,\n d.completedyear,\n d.title,\n d.abstract,\n s.fullname,\n s.country,\n s.id as schoolid\n FROM\n dissertations d,\n schools s\n WHERE\n d.person_id = \".$passed_person.\" AND\n d.school_id = s.id\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n $thisperson['dissertation_id'] = $line['dissertation_id'];\n $thisperson['completedyear'] = $line['completedyear'];\n $thisperson['title'] = $line['title'];\n $thisperson['abstract'] = $line['abstract'];\n $thisperson['country'] = $line['country'];\n $thisperson['school'] = $line['fullname'];\n $thisperson['schoolid'] = $line['schoolid'];\n }\n\n if (isset($thisperson))\n {\n return $thisperson;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school($school_id)\n{\n\n // get school\n\n $query = \"SELECT\n s.fullname,\n s.country\n FROM\n schools s\n WHERE\n s.id = \".$school_id.\"\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n $school['country'] = $line['country'];\n $school['fullname'] = $line['fullname'];\n }\n\n if (isset($school))\n {\n return $school;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction get_environment_info()\n{\n $host_info = array();\n $hostname = $_SERVER['SERVER_NAME'];\n if ($hostname == \"\"){$hostname = exec(hostname);}\n# echo \"hostname = [$hostname]
\";\n if ($hostname == \"www.ibiblio.org\" || $hostname == \"www-dev.ibiblio.org\" || $hostname == \"login1.ibiblio.org\")\n {\n # the main install on ibiblio\n $host_info['hostname'] = \"ibiblio\";\n $host_info['ownername'] = \"mpact\";\n $host_info['dotlocation'] = \"/export/sunsite/users/mpact/terrelllocal/bin/dot\";\n $host_info['appdir'] = \"/public/html/mpact\";\n $host_info['webdir'] = \"http://www.ibiblio.org/mpact\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"Times-Roman\";\n }\n else if ($hostname == \"trel.dyndns.org\")\n {\n # my local development machine\n $host_info['hostname'] = \"home\";\n $host_info['ownername'] = \"trel\";\n $host_info['dotlocation'] = \"/sw/bin/dot\";\n $host_info['appdir'] = \"/Library/WebServer/Documents/MPACTlocal/app\";\n $host_info['webdir'] = \"http://trel.dyndns.org:9000/mpactlocal/app\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"cour\";\n }\n else if ($hostname == \"localhost.com\" || $hostname == \"trelpancake\")\n {\n # my laptop\n $host_info['hostname'] = \"laptop\";\n $host_info['ownername'] = \"trel\";\n $host_info['dotlocation'] = \"/opt/local/bin/dot\";\n $host_info['appdir'] = \"/Users/trel/Sites/MPACT\";\n $host_info['webdir'] = \"http://localhost.com/~trel/MPACT\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"cour\";\n }\n else\n {\n # unknown host\n #exit;\n }\n\n return $host_info;\n}\n\n# -------------------------------------------------------------------------------\nfunction delete_associated_dotgraphs($passed_person)\n{\n $host_info = get_environment_info();\n $group = array($passed_person);\n $ancestors = find_ancestors_for_group($group);\n $descendents = find_descendents_for_group($group);\n $entire_family_tree = array_unique($ancestors + $descendents);\n foreach ($entire_family_tree as $one)\n {\n # set the filenames\n $dotfilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.dot\";\n $imagefilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.\".$host_info['dotfiletype'];\n $imagemapfilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.map\";\n # delete each if they exist\n if (file_exists($dotfilename))\n {\n `rm $dotfilename`;\n }\n if (file_exists($imagefilename))\n {\n `rm $imagefilename`;\n }\n if (file_exists($imagemapfilename))\n {\n `rm $imagemapfilename`;\n }\n # mark as 'dirty' so cronjob can recreate images\n mark_record_as_dirty($one);\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction mark_record_as_dirty($passed_person)\n{\n # mark database record for this person as dirty\n # a cronjob will pick these up and regenerate their dotgraphs\n # gets around permission issues on the server if necessary\n $query = \"UPDATE people SET regenerate_dotgraph = '1' WHERE id = '\".$passed_person.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n}\n\n# -------------------------------------------------------------------------------\nfunction narray_slice($array, $offset, $length) {\n # http://us3.php.net/manual/en/function.array-slice.php#73882\n\n //Check if this version already supports it\n if (str_replace('.', '', PHP_VERSION) >= 502)\n return array_slice($array, $offset, $length, true);\n\n foreach ($array as $key => $value) {\n\n if ($a >= $offset && $a - $offset <= $length)\n $output_array[$key] = $value;\n $a++;\n\n }\n return $output_array;\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_dotfile($passed_person){\n $a = find_person($passed_person);\n if ($a == null)\n {\n return 0;\n }\n else\n {\n $dotfilecontents = \"\";\n $dotfilecontents .= \"digraph familytree\\n\";\n $dotfilecontents .= \"{\\n\";\n $dotfilecontents .= \"rankdir=\\\"LR\\\"\\n\";\n $dotfilecontents .= \"node [fontname = Times, fontsize=10, shape = rect, height=.15]\\n\";\n # ancestors\n $upgroup = array();\n $upgroup[] = $passed_person;\n $ancestors = find_ancestors_for_group($upgroup);\n foreach ($ancestors as $one)\n {\n $person = find_person($one);\n $dotfilecontents .= \"$one [label = \\\"\".$person['fullname'].\"\\\" URL=\\\"mpact.php?op=show_tree&id=\".$one.\"\\\"];\\n\";\n $advisors = find_advisors_for_person($one);\n foreach ($advisors as $adv)\n {\n $dotfilecontents .= \"$adv -> $one;\\n\";\n }\n }\n # descendents\n $downgroup = array();\n $downgroup[] = $passed_person;\n $descendents = find_descendents_for_group($downgroup);\n foreach ($descendents as $one)\n {\n $person = find_person($one);\n $dotfilecontents .= \"$one [label = \\\"\".$person['fullname'].\"\\\" URL=\\\"mpact.php?op=show_tree&id=\".$one.\"\\\"\";\n if ($one == $passed_person){\n $dotfilecontents .= \" color=\\\"red\\\" style=\\\"filled\\\" fillcolor=\\\"grey\\\"\";\n }\n $dotfilecontents .= \"];\\n\";\n $advisees = find_advisorships_under_person($one);\n foreach ($advisees as $adv)\n {\n $dotfilecontents .= \"$one -> $adv;\\n\";\n }\n }\n $dotfilecontents .= \"}\\n\";\n\n return $dotfilecontents;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_tree_dotgraph($passed_person)\n{\n $person = $passed_person;\n $host_info = get_environment_info();\n if (isset($host_info['appdir']))\n {\n $webfilename = generate_dotgraph($person);\n if ($webfilename == \"marked_as_dirty\"){\n echo \"generating graph, please reload\";\n }\n else{\n echo \"\\\"Directed
\";\n }\n }\n else\n {\n echo \"graphics libraries are not configured\";\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_dotgraph($passed_person, $forcenew=\"no\")\n{\n $person = $passed_person;\n $host_info = get_environment_info();\n# print_r($host_info);\n $appcache = $host_info['appdir'].\"/\".$host_info['dotcachedir'];\n $webcache = $host_info['webdir'].\"/\".$host_info['dotcachedir'];\n $appfilename = \"$appcache/$person.\".$host_info['dotfiletype'];\n# echo \"appfilename = $appfilename
\\n\";\n $dotfilename = \"$appcache/$person.dot\";\n# echo \"dotfilename = $dotfilename
\\n\";\n $webfilename = \"$webcache/$person.\".$host_info['dotfiletype'];\n# echo \"webfilename = $webfilename
\\n\";\n $appimagemap = \"$appcache/$person.map\";\n# echo \"appimagemap = $appimagemap
\\n\";\n\n if (!file_exists($appfilename)) {\n # assumption is that the cachedir exists... (run setupmpact.sh)\n # generate dotfile\n if (!file_exists($dotfilename) or $forcenew == \"force\") {\n# print \" - creating dotfile...\\n\";\n $dotfilecontents = generate_dotfile($person);\n $fh = fopen($dotfilename, 'w');\n fwrite($fh, $dotfilecontents);\n fclose($fh);\n exec(\"chmod 666 $dotfilename\");\n }\n # generate graph\n $getandgenerategraph = \"/bin/cat $dotfilename | \".$host_info['dotlocation'].\" -Nfontname=\".$host_info['dotfontface'].\" -Gcharset=latin1 -Tcmapx -o$appimagemap -T\".$host_info['dotfiletype'].\" -o$appfilename 2>&1\";\n# echo \"getandgenerategraph = $getandgenerategraph
\";\n exec($getandgenerategraph);\n exec(\"chmod 666 $appimagemap\");\n exec(\"chmod 666 $appfilename\");\n if (!file_exists($appfilename)) {\n # mark as dirty if it didn't work\n mark_record_as_dirty($person);\n return \"marked_as_dirty\";\n }\n }\n else\n {\n# echo \"SHOWING CACHED COPY
\";\n }\n\n return $webfilename;\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_graph($passed_person)\n{\n if (!$passed_person){action_box(\"No ID given.\");}\n\n $person = $passed_person;\n $host_info = get_environment_info();\n if (isset($host_info['appdir']))\n {\n $appcache = $host_info['appdir'].\"/\".$host_info['dotcachedir'];\n $webcache = $host_info['webdir'].\"/\".$host_info['dotcachedir'];\n $appfilename = \"$appcache/$person.\".$host_info['dotfiletype'];\n #echo \"appfilename = $appfilename
\";\n $webfilename = \"$webcache/$person.\".$host_info['dotfiletype'];\n #echo \"webfilename = $webfilename
\";\n $appimagemap = \"$appcache/$person.map\";\n #echo \"appimagemap = $appimagemap
\";\n\n\n echo \"\";\n echo file_get_contents($appimagemap);\n }\n else\n {\n echo \"graphics libraries are not configured\";\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_tree($passed_person)\n{\n GLOBAL $statuscodes;\n GLOBAL $inspectioncodes;\n\n // shows a person\n\n if (!$passed_person){action_box(\"No ID given.\");}\n else\n {\n $personcount = 0;\n $thisperson = array();\n $dissertation = array();\n\n // get person's preferred name\n\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, p.degree\n FROM\n names n, people p\n WHERE\n p.preferred_name_id = n.id AND\n p.id = '\".$passed_person.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n $thisperson['firstname'] = $line['firstname'];\n $thisperson['middlename'] = $line['middlename'];\n $thisperson['lastname'] = $line['lastname'];\n $thisperson['suffix'] = $line['suffix'];\n $thisperson['degree'] = $line['degree'];\n $personcount++;\n }\n\n $schoolinfo = find_persons_school($passed_person);\n $thisperson['dissertation_id'] = $schoolinfo['dissertation_id'];\n $thisperson['completedyear'] = $schoolinfo['completedyear'];\n $thisperson['country'] = $schoolinfo['country'];\n $thisperson['school'] = $schoolinfo['school'];\n $thisperson['schoolid'] = $schoolinfo['schoolid'];\n\n if ($thisperson['dissertation_id'] == \"\")\n {\n $thisperson['status'] = \"\";\n $thisperson['notes'] = \"\";\n $thisperson['title'] = \"N/A\";\n $thisperson['abstract'] = \"N/A\";\n $thisperson['abstract_html'] = \"N/A\";\n }\n else\n {\n $dissertation = find_dissertation($thisperson['dissertation_id']);\n $thisperson['status'] = $dissertation['status'];\n $thisperson['notes'] = $dissertation['notes'];\n $thisperson['discipline_id'] = $dissertation['discipline_id'];\n $thisperson['title'] = $dissertation['title'];\n $thisperson['abstract'] = $dissertation['abstract'];\n $thisperson['abstract_html'] = encode_linebreaks($dissertation['abstract']);\n if ($thisperson['title'] == \"\") { $thisperson['title'] = \"N/A\";}\n if ($thisperson['abstract'] == \"\")\n {\n $thisperson['abstract'] = \"N/A\";\n $thisperson['abstract_html'] = \"N/A\";\n }\n }\n\n $thisperson['advisors'] = find_advisors_for_person($passed_person);\n $thisperson['cmembers'] = find_committee_for_person($passed_person);\n $thisperson['advisorships'] = find_advisorships_under_person($passed_person);\n $thisperson['committeeships'] = find_committeeships_under_person($passed_person);\n\n\n if ($personcount < 1)\n {\n action_box(\"Person \".$passed_person.\" Not Found\");\n }\n else\n {\n\n echo \"
\\n\";\n\n # Name / Aliases\n $count = 0;\n $printme = \"\";\n $fullname = $thisperson['firstname'].\" \".$thisperson['middlename'].\" \".$thisperson['lastname'].\" \".$thisperson['suffix'];\n $printme .= \"

Dissertation Information for $fullname

\";\n $printme .= \"

\";\n if (is_admin())\n {\n if (isset($thisperson['completedyear']))\n {\n $printme .= \" (Edit)\";\n }\n else\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n $printme .= \"
\\n\";\n }\n $printme .= \"

\";\n $printme .= \"

\";\n $printme .= \"NAME: \";\n if (is_admin())\n {\n $printme .= \"(Add)\";\n }\n $printme .= \"
\";\n $printme .= \" - \";\n $printme .= get_person_link($passed_person);\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n $printme .= \"
\\n\";\n\n $aliases = 0;\n foreach (find_aliases($passed_person) as $one)\n {\n $printme .= \" - (Alias) \";\n $printme .= $one['firstname'].\" \";\n $printme .= $one['middlename'].\" \";\n $printme .= $one['lastname'].\" \";\n $printme .= $one['suffix'].\" \";\n if (is_admin())\n {\n $printme .= \"(Set as Primary)\";\n $printme .= \" (Delete)\";\n }\n $printme .= \"
\";\n $aliases++;\n }\n $printme .= \"

\";\n echo $printme;\n\n # Degree\n $printme = \"

\\n\";\n $printme .= \"DEGREE:
\\n\";\n $printme .= \" - \".$thisperson['degree'];\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n $printme .= \"

\";\n echo $printme;\n\n # Discipline\n $printme = \"

\\n\";\n $printme .= \"DISCIPLINE:
\\n\";\n if (isset($thisperson['discipline_id']))\n {\n $discipline = find_discipline($thisperson['discipline_id']);\n $printme .= \" - \".$discipline['title'].\"\";\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n }\n else\n {\n $printme .= \" - None\";\n if (is_admin())\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n }\n $printme .= \"

\";\n echo $printme;\n\n # School\n $printme = \"

\\n\";\n $printme .= \"SCHOOL:
\\n\";\n if (isset($thisperson['completedyear']))\n {\n $printme .= \" - \".$thisperson['school'].\" (\".$thisperson['country'].\") (\".$thisperson['completedyear'].\")\";\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n }\n else\n {\n $printme .= \" - None\";\n if (is_admin())\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n }\n $printme .= \"

\\n\";\n echo $printme;\n\n\n # Advisors\n $count = 0;\n $printme = \"\";\n $printme .= \"

\";\n $printme .= \"ADVISORS: \";\n if (is_admin() && isset($thisperson['completedyear']))\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
\";\n if (isset($thisperson['advisors'])){\n foreach ($thisperson['advisors'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
\";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

\";\n echo $printme;\n\n # Committee Members\n $count = 0;\n $printme = \"\";\n $printme .= \"

\";\n $printme .= \"COMMITTEE MEMBERS: \";\n if (is_admin() && isset($thisperson['completedyear']))\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
\";\n if (isset($thisperson['cmembers'])){\n foreach ($thisperson['cmembers'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
\";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

\\n\\n\";\n\n # Admin Notes\n if (is_admin())\n {\n if ($thisperson['notes'] != \"\")\n {\n $printme .= \"

\";\n $printme .= \"\\n\";\n $printme .= \"\\n\";\n $printme .= \"
\\n\";\n $printme .= \"Admin Notes: \".$thisperson['notes'].\"
\\n\";\n $printme .= \"
\\n\";\n $printme .= \"

\\n\\n\";\n }\n }\n\n $glossaryterms = find_glossaryterms();\n # Status and Inspection\n $printme .= \"

\";\n $printme .= \"MPACT Status: \".$statuscodes[$thisperson['status']].\"
\\n\";\n $printme .= \"

\\n\\n\";\n\n # Title and Abstract\n $printme .= \"

\";\n $printme .= \"Title: \".$thisperson['title'].\"
\";\n $printme .= \"

\\n\";\n $printme .= \"

\";\n $printme .= \"Abstract: \".$thisperson['abstract_html'].\"
\";\n $printme .= \"

\\n\\n\";\n\n # print it all out...\n echo $printme;\n\n # URLS\n\n if (is_admin())\n {\n $urls = find_urls_by_person($passed_person);\n echo \"

\\n\";\n echo \"REFERENCE URLS\";\n echo \" (Add)\";\n echo \"
\\n\";\n if (count($urls) > 0)\n {\n echo \"\\n\";\n }\n else\n {\n echo \" - None\\n\";\n }\n foreach ($urls as $one)\n {\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n }\n if (count($urls) > 0)\n {\n echo \"
Updated: \".$one['updated_at'].\"\";\n echo \" (Edit)\";\n echo \" (Delete)\";\n echo \"
\".$one['url'].\"
\".$one['description'].\"
\\n\";\n }\n echo \"

\\n\";\n }\n\n # EDIT HISTORY\n \n if (is_admin())\n {\n $entries = get_dissertation_history($thisperson['dissertation_id']);\n if (count($entries) > 0)\n {\n echo \"

\\n\";\n echo \"EDIT HISTORY (Show/Hide)\\n\";\n echo \"\";\n echo \"\\n\";\n }\n\n foreach ($entries as $one)\n {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n if (count($entries) > 0)\n {\n echo \"
\".$one['logged_at'].\"\".$one['user'].\"\".$one['message'].\"
\\n\";\n echo \"

\\n\";\n }\n }\n\n\n\n echo \"
\\n\";\n\n # MPACT Scores\n $printme = \"\";\n $printme .= \"

MPACT Scores for $fullname

\";\n $printme .= \"

\";\n $mpact = mpact_scores($passed_person);\n $printme .= $mpact['output'];\n $printme .= \"

\\n\";\n if (is_admin())\n {\n $printme .= \"

(Recalculate)

\";\n }\n echo $printme;\n\n # Draw FamilyTree Graph for this person\n echo \"

Advisors and Advisees Graph

\\n\";\n echo \"

\";\n draw_tree_dotgraph($passed_person);\n echo \"

\";\n\n echo \"
\\n\";\n\n\n # Students\n echo \"

Students under $fullname

\\n\\n\";\n\n # Advisees\n $count = 0;\n $printme = \"\";\n $printme .= \"

\";\n $printme .= \"ADVISEES: \";\n if (is_admin())\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
\";\n if (isset($thisperson['advisorships'])){\n foreach ($thisperson['advisorships'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n $schoolinfo = find_persons_school($one);\n if (isset($schoolinfo['completedyear']))\n {\n $printme .= \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
\";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

\\n\";\n echo $printme;\n\n # Committeeships\n $ccount = 0;\n $printme = \"\";\n $printme .= \"

\";\n $printme .= \"COMMITTEESHIPS: \";\n if (is_admin())\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
\";\n if (isset($thisperson['committeeships'])){\n foreach ($thisperson['committeeships'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n $schoolinfo = find_persons_school($one);\n if (isset($schoolinfo['completedyear']))\n {\n $printme .= \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
\";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

\";\n echo $printme;\n\n }\n \n }\n\n\n}\n\n\n?>\n"}, "files_after": {"mpact.php": " \"N/A\",\n \"-1\" => \"N/A\",\n \"0\" => \"Incomplete - Not_Inspected\",\n \"1\" => \"Incomplete - Inspected\",\n \"2\" => \"Incomplete - Ambiguous\",\n \"3\" => \"Complete - Except Indecipherables\",\n \"4\" => \"Fully Complete\"\n);\n\n$inspectioncodes = array(\n NULL => \"N/A\",\n \"0\" => \"No\",\n \"1\" => \"Yes\"\n);\n\n$degree_types = array(\n \"Unknown\",\n \"Unknown - Investigated\",\n \"A.L.A.\",\n \"B.A.\",\n \"B.S.\",\n \"B.L.S.\",\n \"L.L.B.\",\n \"H.A.\",\n \"M.A.\",\n \"M.S.\",\n \"M.F.A.\",\n \"M.P.A.\",\n \"D.E.A.\",\n \"Ed.M.\",\n \"F.L.A. (by thesis)\",\n \"LL.M.\",\n \"LL.D.\",\n \"M.L.S.\",\n \"D.S.N.\",\n \"D.S.W.\",\n \"D.Engr.\",\n \"D.Lib.\",\n \"Ed.D.\",\n \"Th.D.\",\n \"Pharm.D.\",\n \"D.Sc.\",\n \"D.L.S.\",\n \"J.D.\",\n \"M.D.\",\n \"Ph.D.\"\n);\n\n// Begin Session\nsession_start();\n\n// Delete server session if client cookie doesn't exist\nif (!isset($_COOKIE['MPACT_userid'])){\n unset($_SESSION['MPACT']);\n}\n\n// Check for good cookie (and expired session) - (re)set session values accordingly\nif (isset($_COOKIE['MPACT_userid']) && !isset($_SESSION['MPACT'])){\n $query = \"SELECT id, username, fullname FROM users WHERE id='\".$_COOKIE['MPACT_userid'].\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $line = mysqli_fetch_array($result);\n $_SESSION['MPACT']['userid'] = $line['id'];\n $_SESSION['MPACT']['username'] = $line['username'];\n $_SESSION['MPACT']['fullname'] = $line['fullname'];\n}\n\n###############################################\n// DISPLAY SOMETHING - something from the URL\nif ($_SERVER['REQUEST_METHOD'] == 'GET')\n{\n // Display header\n xhtml_web_header();\n\n// echo \"-----\\n\";\n// print_r($_COOKIE);\n// echo \"-----\\n\";\n// print_r($_SESSION);\n// echo \"-----\\n\";\n if (isset($_GET['op']))\n {\n switch ($_GET['op'])\n {\n ###############################################\n case \"login\";\n\n $host_info = get_environment_info();\n if ($host_info['hostname'] == \"sils\"){\n # no logins here - go to dev server\n action_box(\"No Logins Here...\",2,$_SERVER['SCRIPT_NAME']);\n }\n else{\n if (!isset($_SESSION['MPACT']['userid'])){\n # login form\n echo \"

Welcome

\\n\";\n echo \"

Please login if you have an account.

\\n\";\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"

Username:

Password:

     
\\n\";\n echo \"
\";\n }\n else{\n # um, already logged in...\n action_box(\"Already Logged In...\",2,$_SERVER['SCRIPT_NAME']);\n }\n }\n\n break;\n ###############################################\n case \"logout\";\n\n setcookie('MPACT_userid',$_SESSION['MPACT']['userid'],time()-1000);\n unset($_SESSION['MPACT']);\n action_box(\"Logged Out\",2,$_SERVER['SCRIPT_NAME']);\n\n break;\n ###############################################\n case \"glossary\";\n\n if ( isset($_GET['id']) ){\n show_glossaryterm($_GET['id']);\n }\n else\n {\n show_glossary();\n }\n\n break;\n ###############################################\n case \"admin\";\n\n if (is_admin())\n {\n echo \"

Administrator Pages

\\n\";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"
\\n\";\n\n echo \"

\\n\";\n echo \"Show Logs\\n\";\n echo \"

\\n\";\n\n echo \"

\\n\";\n echo \"Show Orphans\\n\";\n echo \"
\\n\";\n echo \"Citation Correlation\\n\";\n echo \"

\\n\";\n\n echo \"

\\n\";\n echo \"People with Multiple Dissertations (Errors in DB)\\n\";\n echo \"
\\n\";\n echo \"Year 0000\\n\";\n echo \"

\\n\";\n\n echo \"

\\n\";\n echo \"Add a New Person to the Database\\n\";\n echo \"

\\n\";\n\n echo \"
\\n\";\n\n echo \"

\\n\";\n echo \"No Title/Abstract\\n\";\n echo \"
\\n\";\n echo \"LIS, No Title/Abstract\\n\";\n echo \"
\\n\";\n echo \"LIS, No Title\\n\";\n echo \"
\\n\";\n echo \"LIS, No Abstract\\n\";\n echo \"
\\n\";\n echo \"
\\n\";\n echo \"LIS, No Committee\\n\";\n echo \"

\\n\";\n\n echo \"
\\n\";\n\n echo \"

\\n\";\n echo \"LIS, Graduates By Year\\n\";\n echo \"
\\n\";\n echo \"LIS History\\n\";\n echo \"

\\n\";\n\n echo \"

\\n\";\n echo \"LIS Professors Summary\\n\";\n echo \"
\\n\";\n echo \"LIS Professors with MPACT\\n\";\n echo \"
\\n\";\n echo \"LIS Professors and their Degrees (large CSV)\\n\";\n echo \"
\\n\";\n echo \"LIS Professors with Unknown Degree\\n\";\n echo \"
\\n\";\n echo \"LIS Professors with Unknown-Investigated Degree\\n\";\n echo \"
\\n\";\n echo \"LIS Professors without Dissertations\\n\";\n echo \"
\\n\";\n echo \"LIS Professors without LIS Dissertations\\n\";\n echo \"

\\n\";\n\n echo \"
\\n\";\n\n echo \"
\";\n\n show_alphabet();\n\n }\n else\n {\n not_admin();\n }\n\n break;\n ###############################################\n case \"glossary_edit\";\n\n if ( isset($_GET['id']) && is_admin() ){\n\n echo \"

Edit a Glossary Definition

\\n\";\n\n $query = \"SELECT id, term, definition FROM glossary WHERE id='\".$_GET['id'].\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $results['term'] = $line['term'];\n $results['definition'] = $line['definition'];\n }\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\".$results['term'].\":
\\n\";\n echo \"\\n\";\n echo \"
\\n\";\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n\n\n }\n else\n {\n not_admin();\n }\n\n break;\n ###############################################\n case \"show_tree\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n draw_tree((int)$_GET['id']);\n }\n\n break;\n\n ###############################################\n case \"show_graph\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n echo \"

\\n\";\n echo \"Advisors and Advisees of \".get_person_link($_GET['id']);\n echo \"

\\n\";\n draw_graph((int)$_GET['id']);\n }\n\n break;\n\n ###############################################\n case \"statistics\":\n\n echo \"

\\n\";\n echo \"LIS Incomplete - \\n\";\n echo \"Top A -\\n\";\n echo \"Top C -\\n\";\n echo \"Top A+C -\\n\";\n echo \"Top T -\\n\";\n echo \"Top G -\\n\";\n echo \"Top W -\\n\";\n echo \"Top TD -\\n\";\n echo \"Top TA\\n\";\n echo \"

\\n\";\n\n echo \"

Overall MPACT Statistics

\\n\";\n\n echo \"\\n\";\n\n # disciplines\n $query = \"SELECT count(*) as disciplinecount FROM disciplines\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # schools\n $query = \"SELECT count(*) as schoolcount FROM schools\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # diss\n $query = \"SELECT count(*) as disscount FROM dissertations\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # a\n $query = \"SELECT count(*) as advisorcount FROM advisorships\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # c\n $query = \"SELECT count(*) as committeeshipscount FROM committeeships\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # full\n $query = \"SELECT count(*) as peoplecount FROM people\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n echo \"
Disciplines\".$disciplinecount.\"
Schools\".$schoolcount.\"
Dissertations\".$disscount.\"
Advisorships\".$advisorcount.\"
Committeeships\".$committeeshipscount.\"
People\".$peoplecount.\"
\\n\";\n\n\n # dissertations by country\n echo \"

\\n\";\n echo \"

Dissertations by Country:


\\n\";\n $query = \"SELECT count(*) as dissnone FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"\\\")\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as dissusa FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"USA\\\")\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as disscanada FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"Canada\\\")\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as dissother FROM dissertations WHERE school_id IN\n (SELECT id FROM schools WHERE (country != \\\"\\\" AND country != \\\"USA\\\" AND country != \\\"Canada\\\"))\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"
USA\".$dissusa.\"\".sprintf(\"%.2f\",100*$dissusa/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa)/$disscount).\"%
Canada\".$disscanada.\"\".sprintf(\"%.2f\",100*$disscanada/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada)/$disscount).\"%
Other\".$dissother.\"\".sprintf(\"%.2f\",100*$dissother/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada+$dissother)/$disscount).\"%
None Listed\".$dissnone.\"\".sprintf(\"%.2f\",100*$dissnone/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada+$dissother+$dissnone)/$disscount).\"%
Total\".$disscount.\"\".sprintf(\"%.2f\",100*$disscount/$disscount).\"%
\\n\";\n\n # dissertations by year\n echo \"

\\n\";\n echo \"

Dissertations by Year:


\\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations GROUP BY completedyear\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n ksort($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
\";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n\n break;\n\n\n ###############################################\n case \"show_logs\":\n\n if (is_admin())\n {\n echo \"

Recent Activity

\\n\";\n\n if (isset($_GET['offset']))\n {\n $entries = get_logs($_GET['offset']);\n }\n else\n {\n $entries = get_logs();\n }\n echo \"\\n\";\n foreach ($entries as $entry)\n {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
\".$entry['logged_at'].\"
\".$entry['ip'].\"
\".$entry['user'].\"\".$entry['message'].\"
\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_multi_dissertations\":\n\n if (is_admin())\n {\n echo \"

People With Multiple Dissertations (db needs to be edited by hand)

\\n\";\n\n $query = \"SELECT\n count(d.id) as howmany,\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n GROUP BY\n d.person_id\n ORDER BY\n howmany DESC\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $multicount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n if ($d['howmany'] > 1)\n {\n print \"person id = \".$d['person_id'];\n print \"
\";\n print \"
\";\n $multicount++;\n }\n }\n if ($multicount == 0)\n {\n print \" - None - database is clear.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_zero_year\":\n\n if (is_admin())\n {\n echo \"

Dissertations from the year 0000

\\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.discipline_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.completedyear = '0000'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n # get school\n $query = \"SELECT fullname\n FROM\n schools\n WHERE id = '\".$d['school_id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $schoolname = $line['fullname'];\n }\n # get degree\n $query = \"SELECT degree\n FROM\n people\n WHERE id = '\".$d['person_id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $degree = $line['degree'];\n }\n $discipline = find_discipline($d['discipline_id']);\n echo \"\";\n echo \"\";\n echo \"\";\n print \"\";\n print \"\";\n print \"\";\n print \"\";\n }\n if ($zerocount == 0)\n {\n print \"\";\n }\n echo \"
$zerocount.\".get_person_link($d['person_id']).\"$degree\".$discipline['title'].\"$schoolname
None - database is clear.
\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_lis\":\n\n if (is_admin())\n {\n echo \"

LIS Dissertations Without Title

\\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.title = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
\";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have titles.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_abstract_lis\":\n\n if (is_admin())\n {\n echo \"

LIS Dissertations Without Abstract

\\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.abstract = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
\";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have abstracts.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_abstract\":\n\n if (is_admin())\n {\n echo \"

Dissertations Without Title/Abstract

\\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.title = '' OR d.abstract = ''\n ORDER BY\n d.school_id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
\";\n }\n if ($zerocount == 0)\n {\n print \" - None - All dissertations have titles and abstracts.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_abstract_lis\":\n\n if (is_admin())\n {\n echo \"

LIS Dissertations Without Title/Abstract

\\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.title = '' OR d.abstract = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

\\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
\";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have titles and abstracts.\";\n }\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_unknown_degree\":\n\n if (is_admin())\n {\n echo \"

LIS Professors with Unknown Degree

\\n\";\n\n # advisors or committee members with unknown degree,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n $lis_with_unknown = array();\n\n # get advisors for each diss, check for advisor's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $advisors = array();\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n foreach($advisors as $aid){\n $adv = find_person($aid);\n if ($adv['degree'] == \"Unknown\"){\n $lis_with_unknown[] = $aid;\n }\n }\n }\n\n # get committeeships for each diss, check for comm's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $committeemembers = array();\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n foreach($committeemembers as $cid){\n $com = find_person($cid);\n if ($com['degree'] == \"Unknown\"){\n $lis_with_unknown[] = $cid;\n }\n }\n }\n\n # uniquify\n $lis_with_unknown = array_unique($lis_with_unknown);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($lis_with_unknown as $pid){\n $count++;\n $person = find_person($pid);\n print \"$count. \";\n print get_person_link($pid);\n print \"
\\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_unknowninvestigated\":\n case \"lis_profs_unknowninvestigated_degree\":\n\n# if (is_admin())\n# {\n echo \"

LIS Professors with Unknown-Investigated Degree

\\n\";\n\n # advisors or committee members with unknown-investigated degree,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n $lis_with_unknown = array();\n\n # get advisors for each diss, check for advisor's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $advisors = array();\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n foreach($advisors as $aid){\n $adv = find_person($aid);\n if ($adv['degree'] == \"Unknown - Investigated\"){\n $lis_with_unknown[] = $aid;\n }\n }\n }\n\n # get committeeships for each diss, check for comm's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $committeemembers = array();\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n foreach($committeemembers as $cid){\n $com = find_person($cid);\n if ($com['degree'] == \"Unknown - Investigated\"){\n $lis_with_unknown[] = $cid;\n }\n }\n }\n\n # uniquify\n $lis_with_unknown = array_unique($lis_with_unknown);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($lis_with_unknown as $pid){\n $count++;\n $person = find_person($pid);\n print \"$count. \";\n print get_person_link($pid);\n $advisorcount = count(find_advisorships_under_person($pid));\n $commcount = count(find_committeeships_under_person($pid));\n $totalcommitteeships = $advisorcount + $commcount;\n if ($totalcommitteeships > 1){print \"\";}\n print \" : $advisorcount + $commcount = $totalcommitteeships\";\n if ($totalcommitteeships > 1){print \"\";}\n print \"
\\n\";\n $allcommitteeships += $totalcommitteeships;\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n\n print \"
TOTAL COMMITTEESHIPS = $allcommitteeships
\";\n\n echo \"

\\n\";\n\n# }\n# else\n# {\n# not_admin();\n# }\n\n break;\n\n\n ###############################################\n case \"lis_profswithoutdiss\":\n\n if (is_admin())\n {\n echo \"

LIS Professors without Dissertations

\\n\";\n\n # advisors or committee members with no dissertation,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n $total = array_merge($advisors,$committeemembers);\n $unique = array_unique($total);\n\n $unique_list = implode(\",\",$unique);\n $listed = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $listed[] = $line['person_id'];\n }\n $notlisted = array_diff($unique,$listed);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($notlisted as $pid){\n $count++;\n print \"$count. \";\n print get_person_link($pid);\n print \"
\\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_degrees\":\n\n if (is_admin())\n {\n echo \"

LIS Professors and their Degrees

\\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n print \"

Copy and Paste the text below into a .csv file.

\";\n\n # big loop\n print \"
\\n\";\n          print \"
\";\n print \"Count,DissID,DissYear,DissLastName,DissFirstName,DissSchool,DissCountry,AdvisorID,AdvisorType,AdvisorLastName,AdvisorFirstName,\";\n print \"AdvisorDegree,AdvisorYear,AdvisorDiscipline,AdvisorSchool,AdvisorCountry\\n\";\n $count = 0;\n foreach($lis_dissertations as $did){\n # loop through advisors\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $did\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n\n # advisor line\n\n # Count\n $count++;\n print \"\\\"$count\\\",\";\n # DissID\n print \"\\\"$did\\\",\";\n # DissYear\n $diss = find_dissertation($did);\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # DissLastName\n $author = find_person($diss['person_id']);\n print \"\\\"\".$author['lastname'].\"\\\",\";\n # DissFirstName\n print \"\\\"\".$author['firstname'].\"\\\",\";\n # DissSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # DissCountry\n print \"\\\"\".$school['country'].\"\\\",\";\n # AdvisorID\n $pid = $line['person_id'];\n print \"\\\"$pid\\\",\";\n # AdvisorType\n print \"\\\"Advisor\\\",\";\n # AdvisorLastName\n $person = find_person($pid);\n print \"\\\"\".$person['lastname'].\"\\\",\";\n # AdvisorFirstName\n print \"\\\"\".$person['firstname'].\"\\\",\";\n # AdvisorDegree\n print \"\\\"\".$person['degree'].\"\\\",\";\n $diss = find_dissertation_by_person($pid);\n if ($diss){\n # AdvisorYear\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # AdvisorDiscipline\n $disc = find_discipline($diss['discipline_id']);\n print \"\\\"\".$disc['title'].\"\\\",\";\n # AdvisorSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # AdvisorCountry\n print \"\\\"\".$school['country'].\"\\\"\";\n }\n else{\n # no dissertation for this person\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\"\";\n }\n print \"\\n\";\n\n }\n # loop through committeeships\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $did\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n\n # committeeship line\n\n # Count\n $count++;\n print \"\\\"$count\\\",\";\n # DissID\n print \"\\\"$did\\\",\";\n # DissYear\n $diss = find_dissertation($did);\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # DissLastName\n $author = find_person($diss['person_id']);\n print \"\\\"\".$author['lastname'].\"\\\",\";\n # DissFirstName\n print \"\\\"\".$author['firstname'].\"\\\",\";\n # DissSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # DissCountry\n print \"\\\"\".$school['country'].\"\\\",\";\n # AdvisorID\n $pid = $line['person_id'];\n print \"\\\"$pid\\\",\";\n # AdvisorType\n print \"\\\"Committee\\\",\";\n # AdvisorLastName\n $person = find_person($pid);\n print \"\\\"\".$person['lastname'].\"\\\",\";\n # AdvisorFirstName\n print \"\\\"\".$person['firstname'].\"\\\",\";\n # AdvisorDegree\n print \"\\\"\".$person['degree'].\"\\\",\";\n $diss = find_dissertation_by_person($pid);\n if ($diss){\n # AdvisorYear\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # AdvisorDiscipline\n $disc = find_discipline($diss['discipline_id']);\n print \"\\\"\".$disc['title'].\"\\\",\";\n # AdvisorSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # AdvisorCountry\n print \"\\\"\".$school['country'].\"\\\"\";\n }\n else{\n # no dissertation for this person\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\"\";\n }\n print \"\\n\";\n\n }\n }\n echo \"
\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profsnotfromlis\":\n\n if (is_admin())\n {\n\n echo \"

LIS Professors without LIS Dissertations

\\n\";\n\n # and then once the data collection is done\n # cassidy wants a list of all the people who were advisors and committee\n # members for lis, but were not themselves lis\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n $total = array_merge($advisors,$committeemembers);\n $unique = array_unique($total);\n\n $unique_list = implode(\",\",$unique);\n $listed = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $listed[] = $line['person_id'];\n }\n $notlisted = array_diff($unique,$listed);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($notlisted as $pid){\n $count++;\n print \"$count. \";\n print get_person_link($pid);\n print \"
\\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_nocommittee\":\n\n if (is_admin())\n {\n\n echo \"

LIS Dissertations with no committee

\\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT count(*) as howmany\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n if ($line['howmany'] > 0){$hascomm[] = $id;};\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT count(*) as howmany\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n if ($line['howmany'] > 0){$hascomm[] = $id;};\n }\n }\n $unique = array_unique($hascomm);\n $nocomm = array_diff($lis_dissertations,$unique);\n\n # print them out\n echo \"

\\n\";\n $count = 0;\n foreach($nocomm as $did){\n $count++;\n print \"$count. \";\n $d = find_dissertation($did);\n print get_person_link($d['person_id']);\n print \"
\\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_with_mpact\":\n\n if (is_admin())\n {\n echo \"

LIS Professors With MPACT

\\n\";\n\n # advisors or committee members\n # that served on an lis dissertation\n\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n\n $total = array_merge($advisors,$committeemembers);\n\n $unique = array_unique($total);\n\n echo \"
\\n\";\n          echo \"Count|Name|Year|A|C|A+C|T\\n\";\n          foreach ($unique as $prof){\n            $mpact = mpact_scores($prof);\n            $person = find_person($prof);\n            $dissertation = find_dissertation_by_person($prof);\n            # count\n            $count += 1;\n            echo \"$count\";\n            echo \"|\";\n            # name\n            echo $person['fullname'];\n            echo \"|\";\n            # year\n            echo $dissertation['completedyear'];\n            echo \"|\";\n            # a\n            echo $mpact['A'];\n            echo \"|\";\n            # c\n            echo $mpact['C'];\n            echo \"|\";\n            # a+c\n            echo $mpact['AC'];\n            echo \"|\";\n            # t\n            echo $mpact['T'];\n            echo \"\\n\";\n          }\n          echo \"
\\n\";\n }\n\n break;\n\n ###############################################\n case \"lis_profs_summary\":\n\n if (is_admin())\n {\n echo \"

LIS Professors Summary

\\n\";\n\n # advisors or committee members\n # that served on an lis dissertation\n\n echo \"\\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n echo \"\\n\";\n\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n echo \"\\n\";\n\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n echo \"\\n\";\n\n $total = array_merge($advisors,$committeemembers);\n echo \"\\n\";\n\n $unique = array_unique($total);\n echo \"\\n\";\n\n $unique_list = implode(\",\",$unique);\n $known = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $known[] = $line['person_id'];\n }\n echo \"\\n\";\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n discipline_id != 16\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n completedyear != 0000\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n completedyear != 107\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n echo \"
Total LIS Dissertations\".count($lis_dissertations).\"
Total LIS Dissertation Advisorships\";\n echo count($advisors);\n echo \"
Total LIS Dissertation Committeeships\";\n echo count($committeemembers);\n echo \"
Total LIS Dissertation Advisorships and Committeeships:\";\n echo count($total);\n echo \"
Total number of unique advisor/committee members on LIS dissertations:\";\n\n echo count($unique);\n echo \"
\";\n echo \"Subset of \".count($unique).\" without a listed dissertation:\";\n echo count(array_diff($unique,$known));\n echo \"
Subset of \".count($unique).\" with a listed dissertation:\";\n echo count($known);\n echo \"
- Subset of \".count($known).\" with known discipline:\";\n echo $howmany;\n echo \"
- Subset of \".count($known).\" with known year:\";\n echo $howmany;\n echo \"
- Subset of \".count($known).\" with known school:\";\n echo $howmany;\n echo \"
\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_allyears\":\n\n if (is_admin())\n {\n echo \"

LIS, Graduates By Year

\\n\";\n print \"
\\n\";\n\n            # get list of dissertations\n            $query = \"SELECT\n                      d.id, d.person_id, d.completedyear\n                    FROM\n                      dissertations d\n                    WHERE\n                      d.discipline_id = '1'\n                    ORDER BY\n                      d.completedyear ASC,\n                      d.school_id ASC\n                    \";\n            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n            $schools = array();\n            $count = 0;\n            while ( $line = mysqli_fetch_array($result)) {\n              $dissertation = find_dissertation($line['id']);\n              $person = find_person($line['person_id']);\n              $schoolinfo = find_persons_school($line['person_id']);\n              $count++;\n              print $count;\n              print \"|\";\n              print $line['completedyear'];\n              print \"|\";\n              print $schoolinfo['school'];\n              print \"|\";\n              print $person['fullname'];\n#              print \"|\";\n#              print $dissertation['title'];\n#              print \"|\";\n#              print $dissertation['abstract'];\n              print \"\\n\";\n            }\n\n            print \"
\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_history\":\n\n if (is_admin())\n {\n echo \"

LIS Dissertations by School by Year

\\n\";\n\n $firstyear = 1920;\n $lastyear = 2008;\n\n print \"
\\n\";\n            print \"school|\";\n            for ($i = $firstyear; $i <= $lastyear; $i++)\n            {\n                print \"$i|\";\n            }\n            print \"\\n\";\n\n            # get list of schools (all of them)\n            $query = \"SELECT\n                    s.id, s.fullname\n                    FROM\n                      schools s\n                    ORDER BY\n                      s.fullname\n                    \";\n            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n            $schools = array();\n            while ( $line = mysqli_fetch_array($result)) {\n              $schools[] = $line;\n            }\n            foreach ($schools as $s)\n            {\n              # loop through each school and find count by year\n              $query = \"SELECT\n                    d.id, d.person_id, d.completedyear, COUNT(d.completedyear) AS yeartotal\n                    FROM\n                      dissertations d\n                    WHERE\n                      d.discipline_id = '1' AND\n                      d.school_id = '\".$s['id'].\"'\n                    GROUP BY\n                      d.completedyear\n                  \";\n              $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n              print $s['fullname'].\"|\";\n              $d = array();\n              while ( $line = mysqli_fetch_array($result)) {\n                $d[$s['id']][$line['completedyear']] = $line['yeartotal'];\n              }\n\n              # walk through all years, and print out counts for this school\n              for ($i = $firstyear; $i <= $lastyear; $i++)\n              {\n                if ($d[$s['id']][$i] > 0)\n                  print $d[$s['id']][$i].\"|\";\n                else\n                  print \"0|\";\n              }\n              print \"\\n\";\n            }\n\n            print \"
\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_incomplete\":\n\n echo \"

Incomplete LIS Dissertation Listings

\\n\";\n\n $discipline_id = 1; # hard coded for LIS\n $schools = find_schools($discipline_id);\n\n foreach ($schools as $one => $two)\n {\n\n $year_conferred = array();\n $degree_status = array();\n\n $query = \"SELECT d.person_id, d.completedyear, d.status\n FROM\n dissertations d,\n schools s,\n people p,\n names n\n WHERE\n s.id = '$one' AND\n d.discipline_id = '$discipline_id' AND\n d.school_id = s.id AND\n d.person_id = p.id AND\n p.preferred_name_id = n.id AND\n d.status < 4\n ORDER BY\n s.id ASC, d.completedyear ASC, n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $resultcount = 0;\n\n while ( $line = mysqli_fetch_array($result)) {\n $resultcount++;\n extract($line);\n $year_conferred[$person_id] = $completedyear;\n $degree_status[$person_id] = $status;\n }\n\n if ($resultcount > 0)\n {\n echo \"

$two

\\n\";\n }\n\n $incompletecount = 0;\n echo \"\";\n foreach ($year_conferred as $person => $year)\n {\n $incompletecount++;\n $printme = \"\\n\";\n $printme .= \"\\n\";\n\n $printme .= \"\\n\";\n $printme .= \"\\n\";\n\n echo $printme;\n }\n echo \"
$incompletecount. \";\n $printme .= \"\".get_person_link($person).\" ($year)\".$statuscodes[$degree_status[$person]].\"
\";\n\n }\n echo \"

\";\n\n break;\n\n ###############################################\n case \"all_edges\":\n\n if (is_admin())\n {\n echo \"

All Dissertations and Mentor Relationships

\\n\";\n\n print \"
\\n\";\n            print \"mentor|role|protege|year|school\\n\";\n\n            # each dissertation\n            $query = \"SELECT id, person_id, completedyear, school_id FROM dissertations\";\n            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n            while ( $line = mysqli_fetch_array($result)) {\n              extract($line);\n              $student = find_person($person_id);\n              $query2 = \"SELECT fullname as schoolname FROM schools WHERE id = '$school_id'\";\n              $result2 = mysql_query($query2) or die(mysql_error());\n              $line2 = mysqli_fetch_array($result2);\n              extract($line2);\n              print $student['fullname'].\"|dissertation|null|$completedyear|$schoolname\\n\";\n              # get advisorships\n              $advisors = find_advisors_for_person($person_id);\n              foreach ($advisors as $mentor_id){\n                $mentor = find_person($mentor_id);\n                print $mentor['fullname'].\"|advisorship|\".$student['fullname'].\"|$completedyear|$schoolname\\n\";\n              }\n              # get committeeships\n              $committee = find_committee_for_person($person_id);\n              foreach ($committee as $mentor_id){\n                $mentor = find_person($mentor_id);\n                print $mentor['fullname'].\"|committeeship|\".$student['fullname'].\"|$completedyear|$schoolname\\n\";\n              }\n            }\n            print \"
\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"citation_correlation\":\n\n if (is_admin())\n {\n echo \"

Citation Correlation Data

\\n\";\n\n $correlated_ids = array(\n 953,\n 2098,\n# 5086, bc\n 3659,\n# 1329, dalhousie\n 5087,\n 478,\n 3094,\n 3497,\n 4784,\n 1250,\n 5088,\n 5089,\n 5090,\n 4657,\n# 5091, mcdowell, not phd yet\n 5092,\n 5093,\n 5094,\n 2668,\n 4076,\n 2683,\n 3978,\n 2425,\n 3645,\n 2660,\n 2233,\n 2665,\n 1310,\n 2548,\n 2708,\n 2592,\n 4648,\n 5095,\n 5096,\n 4654,\n 5097,\n 5098,\n 1234,\n 1299,\n 1294,\n 3062,\n 3110,\n 1283,\n 1220,\n 874,\n 584,\n 3127,\n 1142,\n 3116,\n 5099,\n 5100,\n 1025,\n 486,\n 3130,\n 1321,\n 5101,\n 4502,\n 5102,\n 535,\n 5160, # koohang\n 2673,\n 5103,\n 5104,\n 1950,\n 3972,\n 3278,\n 5105,\n 3571,\n 5106,\n 3994,\n 1504,\n 4181,\n 3140,\n 2323, # benoit added\n 5107,\n 800,\n 4438,\n 5108,\n 5109,\n 4760,\n 2570,\n 1866,\n 3238,\n 1846,\n 1806,\n 2527,\n 3703,\n 4758,\n 3683,\n 3846,\n 2603,\n 4011,\n 2343,\n 2329,\n 5110,\n 5111,\n 4706,\n 2761,\n 1413,\n 3028,\n 3590,\n 3668,\n 2883,\n 3063,\n 3091,\n 1705,\n 3031,\n# gary again 486,\n 3979,\n 3018,\n 1855,\n 3409,\n 2747,\n 3093,\n 3065,\n 3060,\n 1685,\n 2114,\n 5112,\n# moore rm 5113,\n 2309,\n# liu rm 2215,\n 4086,\n 4013,\n 1573\n );\n\n echo \"\\n\";\n echo \"\n \n \n \n \n \n \n \n \n \n \\n\";\n $counter = 0;\n foreach ($correlated_ids as $one)\n {\n $counter++;\n echo \"\";\n echo \"\";\n echo \"\";\n $scores = mpact_scores($one);\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
-NameACA+CFMIFMEFMI/(A+C)FME/(A+C)
$counter.\";\n echo get_person_link($one);\n echo \"\".$scores['A'].\"\".$scores['C'].\"\".$scores['AC'].\"\".$scores['FMI'].\"\".$scores['FME'].\"\".$scores['FMIdivFULL'].\"\".$scores['FMEdivFULL'].\"
\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"top_a\":\n case \"top_c\":\n case \"top_ac\":\n case \"top_g\":\n case \"top_td\":\n case \"top_w\":\n case \"top_t\":\n case \"top_ta\":\n\n $list_type = strtoupper(substr($_GET['op'],4));\n echo \"

Top \";\n if ($list_type == \"TD\"){echo \"TD\";}\n else if ($list_type == \"TA\"){echo \"TA\";}\n else if ($list_type == \"AC\"){echo \"A+C\";}\n else {echo $list_type;}\n echo \" List

\\n\";\n $score_type = strtolower($list_type).\"_score\";\n $people = find_all_people();\n foreach ($people as $p)\n {\n $scores[$p] = find_mpact_score($p,$score_type);\n }\n # zero out indecipherables\n $scores[28] = 0;\n $scores[391] = 0;\n asort($scores);\n $scores = array_reverse($scores, true);\n $top = narray_slice($scores, 0, 100); #calls custom function, end of mpact_include (passes true)\n $count = 0;\n $lasttotal = 0;\n echo \"\\n\";\n foreach ($top as $one => $two)\n {\n $count++;\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n $lasttotal = $two;\n }\n echo \"
\";\n if ($two != $lasttotal){echo $count.\".\";}\n echo \"\";\n echo get_person_link($one);\n echo \"\";\n echo $two;\n echo \"
\\n\";\n break;\n\n ###############################################\n case \"create_discipline\":\n\n if (is_admin())\n {\n echo \"

Creating a New Discipline

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
Title
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_discipline\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n elseif (!is_empty_discipline($_GET['id']))\n {\n action_box(\"Discipline must be empty to edit...\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else{\n\n $query = \"SELECT title FROM disciplines WHERE id=\".$_GET['id'];\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

Editing a Discipline

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
Title
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_school\":\n\n if (is_admin())\n {\n echo \"

Creating a New School

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FullnameCountry
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n elseif (!is_empty_school($_GET['id']))\n {\n action_box(\"School must be empty to edit...\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else{\n\n $query = \"SELECT fullname, country FROM schools WHERE id=\".$_GET['id'];\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

Editing a School

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FullnameCountry
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_person\":\n\n if (is_admin())\n {\n echo \"

Creating a New Person

\\n\";\n\n echo \"

\";\n\n echo \"

\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FirstMiddleLastSuffixDegree
\";\n echo \"\\n\";\n echo \"
\";\n\n echo \"\";\n echo \"
\";\n\n echo \"

\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin())\n {\n echo \"

Add a New Person to the Database

\\n\";\n\n echo \"

Adding a Mentor

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"Mentor Type:
\\n\";\n echo \" Advisor
\\n\";\n echo \" Committee Member\\n\";\n echo \"

\\n\";\n\n echo \"Mentor:
\\n\";\n echo \"\\n\";\n\n echo \"

\\n\";\n\n echo \"Student:
\\n\". get_person_link($_GET['id']);\n echo \"

\\n\";\n\n echo \"\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree($_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_student\":\n\n if (is_admin())\n {\n echo \"

Add a New Person to the Database

\\n\";\n\n echo \"

Adding a Student

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"Mentor Type:
\\n\";\n echo \" Advisor
\\n\";\n echo \" Committee Member\\n\";\n echo \"

\\n\";\n\n echo \"Mentor:
\\n\". get_person_link($_GET['id']);\n echo \"

\\n\";\n\n\n echo \"Student:
\\n\";\n echo \"\\n\";\n\n echo \"

\\n\";\n echo \"\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree($_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n\n ###############################################\n case \"remove_mentor\":\n\n if (is_admin())\n {\n echo \"

Removing a Mentor

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"Are you sure you want to remove this mentor relationship?

\\n\";\n if ($_GET['type'] == \"A\"){echo \"Advisor: \";}\n if ($_GET['type'] == \"C\"){echo \"Commitee Member: \";}\n echo get_person_link(intval($_GET['mentor_id'])).\"
\\n\";\n echo \"Student: \".get_person_link(intval($_GET['student_id'])).\"
\\n\";\n echo \"
\\n\";\n\n echo \"\";\n echo \" If NOT, please go BACK\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree(intval($_GET['student_id']));\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_url\";\n\n if (is_admin())\n {\n echo \"

Adding a Reference URL

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
URL:
Description:
\\n\";\n\n echo \"\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree(intval($_GET['id']));\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_url\";\n\n if (is_admin())\n {\n $url = find_url(intval($_GET['id']));\n echo \"

Editing a Reference URL

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
URL:
Description:
Last Updated:\".$url['updated_at'].\"
\\n\";\n\n echo \"\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree($url['person_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_url\";\n\n if (is_admin())\n {\n $url = find_url(intval($_GET['id']));\n echo \"

Deleting a Reference URL

\\n\";\n\n echo \"
\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n\n echo \"Are you sure you want to delete this Reference URL?

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
URL:\".$url['url'].\"
Description:\".$url['description'].\"
Last Updated:\".$url['updated_at'].\"
\\n\";\n echo \"
\\n\";\n\n echo \"\";\n echo \" If NOT, please go BACK\";\n\n echo \"

\";\n echo \"
\";\n\n draw_tree($url['person_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_degree\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

Editing a Degree

\";\n echo \"

\";\n\n echo \"

\";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
NameDegree
\".$person['fullname'].\"\";\n echo \"\\n\";\n echo \"
\";\n\n echo \"\";\n\n echo \"
\";\n\n echo \"

\";\n\n\n echo \"
\";\n draw_tree($_GET['id']);\n echo \"
\";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

Adding an Alias

\";\n echo \"

\";\n\n echo \"

\";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FirstMiddleLastSuffix
\";\n\n echo \"\";\n\n echo \"
\";\n\n echo \"

\";\n\n\n echo \"
\";\n draw_tree($_GET['id']);\n echo \"
\";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

Editing a Name

\";\n echo \"

\";\n\n echo \"

\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
FirstMiddleLastSuffix
\";\n\n echo \"\";\n\n echo \"
\";\n\n echo \"

\";\n\n\n echo \"
\";\n draw_tree($_GET['id']);\n echo \"
\";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_dissertation\":\n\n if (is_admin())\n {\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n\n if (!$_GET['person_id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['person_id']);\n if (!$person)\n {\n action_box(\"Person not found.\");\n }\n else{\n\n echo \"

CREATE DISSERTATION

\\n\";\n\n echo \"
\";\n echo \"\";\n echo \"\";\n\n echo \"

\";\n echo get_person_link($person['id']);\n echo \"
\";\n\n echo \"Degree: \\n\";\n echo \"
\";\n\n echo \"Status: \\n\";\n echo \"
\";\n\n echo \"Discipline: \\n\";\n echo \"
\";\n\n\n echo \"School: \";\n echo \"\\n\";\n echo \"
Year:\\n\";\n echo \"
\";\n echo \"Title:

\";\n echo \"Abstract:

\";\n echo \"\";\n echo \"

\";\n\n echo \"
\";\n\n echo \"

\";\n echo \"Currently:\";\n echo \"

\";\n echo \"
\";\n draw_tree($person['id']);\n echo \"
\";\n }\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"edit_dissertation\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n $dissertation = find_dissertation(intval($_GET['id']));\n if (!$dissertation)\n {\n action_box(\"Dissertation not found.\");\n }\n else{\n\n $person = find_person($dissertation['person_id']);\n\n echo \"

EDIT DISSERTATION DETAILS

\\n\";\n\n echo \"
\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"

\";\n echo get_person_link($person['id']);\n echo \"
\";\n\n echo \"Degree: \\n\";\n echo \"
\";\n\n echo \"Status: \\n\";\n echo \"
\";\n\n echo \"Discipline: \\n\";\n echo \"
\";\n\n echo \"School: \\n\";\n\n echo \"
Year:\\n\";\n echo \"
\";\n echo \"Title:

\";\n echo \"Abstract:

\";\n echo \"Admin Notes:

\";\n echo \"\";\n echo \"

\";\n\n echo \"
\";\n\n echo \"

\";\n echo \"Currently:\";\n echo \"

\";\n echo \"
\";\n draw_tree($person['id']);\n echo \"
\";\n }\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_name($_GET['name']);\n\n echo \"

\";\n\n echo \"Are you sure you want to delete this name?\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\";\n\n echo \"

\";\n echo \"[ \".$person['firstname'].\" \".$person['middlename'].\" \".$person['lastname'].\" \".$person['suffix'].\" ]
\";\n echo \"

\";\n\n\n echo \"

\";\n echo \"\";\n echo \"   Cancel

\";\n\n echo \"
\";\n\n echo \"

\";\n\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"set_preferred_name\":\n\n if (is_admin())\n {\n\n set_preferred_name($_GET['id'],$_GET['name']);\n\n action_box(\"Preferred Name Selected\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"recalculate_mpact\":\n\n if (is_admin()){\n\n # recalculate MPACT scores for passed person id\n calculate_scores($_GET['id']);\n\n action_box(\"MPACT Scores Recalculated\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"show_orphans\":\n\n if (is_admin())\n {\n\n $orphans = find_orphans();\n\n echo \"

Orphans

\\n\";\n\n echo \"

\\n\";\n $counter = 0;\n foreach ($orphans as $orphan)\n {\n $counter++;\n echo $counter.\" \";\n echo get_person_link($orphan['person_id']);\n echo \" (Delete from Database)\";\n echo \"
\\n\";\n }\n if ($counter < 1){echo \" - No orphans at this time.\";}\n echo \"

\\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_person\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n if (is_orphan($_GET['id']))\n {\n echo \"

\";\n\n echo \"Are you sure you want to delete this person?\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

\";\n echo get_person_link($_GET['id']);\n echo \"

\";\n\n\n echo \"

\";\n echo \"

\\n\";\n echo \"\";\n echo \"   Cancel

\";\n\n echo \"
\";\n\n echo \"

\";\n }\n else\n {\n action_box(\"This person cannot be deleted.\");\n }\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"show_disciplines\":\n\n $statustotals = array(0,0,0,0,0);\n $disciplines = find_disciplines();\n $disciplinecounts = find_discipline_counts();\n\n if (is_admin()){\n echo \"

Add a New Discipline to the Database

\\n\";\n }\n\n echo \"

Disciplines Represented Across All Schools

\\n\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($disciplines as $one => $two)\n {\n echo \"\";\n echo \"\";\n $statuscounts = find_discipline_statuses($one);\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n if (!isset($disciplinecounts[$one]) || $disciplinecounts[$one]==0)\n {\n $fraction = 0;\n }\n else\n {\n $fraction = 100*$statuscounts[$three]/intval($disciplinecounts[$one]);\n }\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($disciplinecounts);\n echo \"\";\n }\n echo \"\";\n echo \"
Discipline$statuscodes[$one]
$two (\".intval($disciplinecounts[$one]).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
------------------
\";\n echo count($disciplines).\" Disciplines (\".array_sum($disciplinecounts).\" dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n break;\n\n ###############################################\n case \"show_discipline\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $discipline_id = intval($_GET['id']);\n\n # Show Discipline Name\n $query = \"SELECT d.title as disciplinename\n FROM disciplines d\n WHERE\n d.id = '$discipline_id'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

$disciplinename

\";\n\n # Show Histograph\n $counts = array();\n echo \"

\\n\";\n echo \"Dissertations by Year:
\\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations WHERE discipline_id='$discipline_id' GROUP BY completedyear\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n if (count($counts)>0)\n {\n $bigyear = max($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*intval(200/$bigyear);\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
\";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n }\n echo \"

\\n\";\n }\n\n $schools = find_schools($discipline_id);\n $dissertation_count = 0;\n $statustotals = array(0,0,0,0,0);\n echo \"

Schools Represented

\\n\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($schools as $one => $two)\n {\n $statuscounts = find_dept_statuses($one,$discipline_id);\n $dissertation_count += array_sum($statuscounts);\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n\n if (array_sum($statustotals)==0)\n {\n $fraction = 0;\n }\n else\n {\n $fraction = 100*$statustotals[$three]/array_sum($statustotals);\n }\n echo \"\";\n }\n echo \"\";\n echo \"
School$statuscodes[$one]
$two (\".array_sum($statuscounts).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
------------------
\";\n echo count($schools).\" Schools ($dissertation_count dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n # link to edit the discipline name\n if (is_empty_discipline($_GET['id']))\n {\n echo \"

\";\n echo \"

Edit Discipline Name

\\n\";\n }\n\n break;\n\n ###############################################\n case \"show_school\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $school_id = intval($_GET['id']);\n\n # Show School Name\n $query = \"SELECT s.fullname as schoolname, s.country\n FROM schools s\n WHERE\n s.id = '$school_id'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

$schoolname ($country)

\";\n\n # Show Histograph\n echo \"

\\n\";\n echo \"Dissertations by Year:
\\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations WHERE school_id='$school_id' GROUP BY completedyear\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n $bigyear = max($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*intval(200/$bigyear);\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
\";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n\n $disciplines = find_disciplines($school_id);\n $dissertation_count = 0;\n $statustotals = array(0,0,0,0,0);\n echo \"

Disciplines Represented

\\n\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($disciplines as $one => $two)\n {\n $statuscounts = find_dept_statuses($school_id,$one);\n $dissertation_count += array_sum($statuscounts);\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($statustotals);\n echo \"\";\n }\n echo \"\";\n echo \"
Discipline$statuscodes[$one]
$two (\".array_sum($statuscounts).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
------------------
\";\n echo count($disciplines).\" Disciplines ($dissertation_count dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
\\n\";\n echo \"

\\n\";\n }\n\n # link to edit the school info\n if (is_empty_school($_GET['id']))\n {\n echo \"

\";\n echo \"

Edit School Information

\\n\";\n }\n\n break;\n\n ###############################################\n case \"show_schools\":\n\n $statustotals = array(0,0,0,0,0);\n $schools = find_schools();\n $schoolcounts = find_school_counts();\n\n if (is_admin()){\n echo \"

Add a New School to the Database

\\n\";\n }\n echo \"

Schools Represented Across All Disciplines

\\n\";\n\n echo \"

\\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($schools as $one => $two)\n {\n echo \"\";\n echo \"\";\n $statuscounts = find_school_statuses($one);\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n if (intval($schoolcounts[$one]) == 0){\n $fraction = 0;\n }\n else{\n $fraction = 100*$statuscounts[$three]/intval($schoolcounts[$one]);\n }\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($schoolcounts);\n echo \"\";\n }\n echo \"\";\n echo \"
School$statuscodes[$one]
$two (\".intval($schoolcounts[$one]).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
------------------
\";\n echo count($schools).\" Schools (\".array_sum($schoolcounts).\" dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n break;\n\n ###############################################\n case \"show_department\":\n\n if (!$_GET['d'] || !$_GET['s']){action_box(\"No ID given.\");}\n else\n {\n\n $school_id = $_GET['s'];\n $discipline_id = $_GET['d'];\n\n\n # Show Discipline Name\n $query = \"SELECT d.title as disciplinename\n FROM disciplines d\n WHERE\n d.id = '$discipline_id'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n # Show School Name\n $query = \"SELECT s.fullname as schoolname, s.country\n FROM schools s\n WHERE\n s.id = '$school_id'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"\n

\n $disciplinename\n @\n $schoolname ($country)\n

\n \";\n\n # Advisor and Committee Activity\n echo \"

Dissertation Activity and MPACT Scores (click table headings to sort)

\";\n\n echo \"

\";\n $theprofs = find_profs_at_dept($school_id,$discipline_id);\n if (count($theprofs)>0)\n {\n $sortedprofs = array();\n $proflist = \"\";\n $query = \"SELECT id FROM people WHERE id IN (\";\n foreach ($theprofs as $prof){$proflist .= \"$prof,\";}\n $proflist = rtrim($proflist, \",\");\n $query .= \"$proflist) ORDER BY ac_score DESC\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $sortedprofs[] = $line['id'];\n }\n $profcount = 0;\n echo \"\\n\";\n echo \"\n \n \n \n \n \n \n \n \n \n \n \\n\";\n foreach ($sortedprofs as $one)\n {\n echo \"\";\n $profcount++;\n echo \"\";\n echo \"\";\n $scores = mpact_scores($one);\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
-NameACA+CGTTATDW
$profcount.\";\n echo get_person_link($one);\n echo \"\".$scores['A'].\"\".$scores['C'].\"\".$scores['AC'].\"\".$scores['G'].\"\".$scores['T'].\"\".$scores['TA'].\"\".$scores['TD'].\"\".$scores['W'].\"
\\n\";\n echo \"

\";\n }\n else\n {\n echo \"

- None Listed

\\n\";\n }\n echo \"
\";\n\n\n\n\n # Dissertations Conferred\n echo \"

Dissertations Conferred

\";\n\n\n\n\n # Show Histograph\n echo \"

\\n\";\n echo \"Dissertations by Year:
\\n\";\n $query = \"SELECT completedyear, count(*) as disscount\n FROM dissertations\n WHERE\n school_id='$school_id' AND\n discipline_id=$discipline_id\n GROUP BY\n completedyear\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*10;\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
\";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n echo \"

\\n\";\n\n\n\n\n\n $query = \"SELECT d.person_id, d.completedyear, d.status\n FROM\n dissertations d,\n schools s,\n people p,\n names n\n WHERE\n s.id = '$school_id' AND\n d.discipline_id = '$discipline_id' AND\n d.school_id = s.id AND\n d.person_id = p.id AND\n p.preferred_name_id = n.id\n ORDER BY\n d.completedyear ASC, n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n $year_conferred[$person_id] = $completedyear;\n $degree_status[$person_id] = $status;\n }\n\n $schoolcount = 0;\n echo \"

\";\n foreach ($year_conferred as $person => $year)\n {\n $schoolcount++;\n echo \"
$schoolcount. \";\n echo get_person_link($person);\n echo \" ($year)\";\n if ($degree_status[$person] < 4)\n {\n echo \" ---------------------------------- \".$statuscodes[$degree_status[$person]];\n }\n }\n echo \"

\";\n\n }\n\n break;\n\n ###############################################\n default:\n // oops - not supposed to be here\n action_box(\"invalid action\",1);\n }\n }\n else\n {\n\n if (isset($_GET['show']))\n {\n if ($_GET['show'] == \"all\")\n {\n $alphabet_limiter = \"\"; // set it to show everything\n }\n else\n {\n $alphabet_limiter = $_GET['show'];\n }\n\n show_alphabet();\n\n if (is_admin())\n {\n echo \"

Add a New Person to the Database

\\n\";\n }\n\n if (is_admin()){\n echo \"
\";\n echo \"\";\n echo \"\";\n echo \"\";\n }\n\n // GET ALL DISSERTATIONS IN A HASH\n $disciplines = find_disciplines();\n $query = \"SELECT id, person_id, discipline_id FROM dissertations\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $graduates[$line['person_id']] = $line['discipline_id'];\n }\n\n // LOOP THROUGH ALL PEOPLE FOR THIS LETTER\n echo \"\\n\";\n echo \"\\n\";\n if (is_admin()){echo \"\\n\";}\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n $query = \"SELECT n.id, n.firstname,\n n.middlename, n.lastname, n.suffix,\n p.id as person_id\n FROM names n, people p\n WHERE\n n.id = p.preferred_name_id AND\n n.lastname LIKE '\".$alphabet_limiter.\"%'\n ORDER BY n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $rowcount = 0;\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n\n $rowcount++;\n\n echo \"\";\n if (is_admin()){\n echo \"\";\n }\n echo \"\";\n echo \"\";\n $discipline = isset($graduates[$person_id]) ? $disciplines[$graduates[$person_id]] : \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n if (is_admin()){\n if ($rowcount % 25 == 0){\n echo \"\";\n }\n }\n\n }\n\n echo \"
MergeCountLast NameFull NameDissertation Discipline
$rowcount.$lastname$firstname $middlename $lastname $suffix$discipline
\\n\";\n\n if (is_admin()){\n echo \"\";\n echo \"
\";\n }\n\n echo \"

\\n\";\n\n show_alphabet();\n\n }\n else\n {\n // DISPLAY THE FRONT PAGE\n\n action_box(\"Front Page...\",0.1,\"./\");\n\n }\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n###############################################\n// SOMETHING WAS SUBMITTED - through a form\nelse\n{\n\n if ($_POST['op'] != \"login\"){\n // Display header\n xhtml_web_header();\n }\n\n switch ($_POST['op'])\n {\n ###############################################\n case \"login\";\n\n $host_info = get_environment_info();\n if ($host_info['hostname'] == \"sils\"){\n # no logins here - go to dev server\n action_box(\"No Logins Here...\",2,$_SERVER['SCRIPT_NAME']);\n }\n else{\n # check credentials / start session\n $query = \"SELECT id, username, fullname FROM users\n WHERE username = '\".addslashes($_POST['username']).\"'\n AND password = '\".addslashes($_POST['password']).\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $line = mysqli_fetch_array($result);\n if (isset($line['id'])){\n # save cookie info for one week\n setcookie('MPACT_userid',$line['id'],time()+60*60*24*7);\n # redirect\n header(\"Location: \".$_SERVER['SCRIPT_NAME']);\n }\n else{\n // Display header\n xhtml_web_header();\n # incorrect credentials\n action_box(\"Please try again...\",2,$_SERVER['SCRIPT_NAME'].\"?op=login\");\n }\n }\n\n break;\n\n ###############################################\n case \"glossary_edit\";\n if (is_admin())\n {\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $query = \"UPDATE glossary\n SET\n definition = '\".$_POST['definition'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # log it\n mpact_logger(\"updated glossary [\".$_POST['term'].\" (\".$_POST['id'].\")] to (\".$_POST['definition'].\")\");\n\n action_box(\"Definition Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=glossary\");\n }\n else\n {\n not_admin();\n }\n break;\n\n ###############################################\n case \"merge_confirm\":\n\n if (is_admin()){\n\n echo \"
\";\n echo \"\";\n echo \"\";\n\n foreach ($_POST['mergers'] as $one)\n {\n echo \"
\";\n echo \"

[$one]

\";\n echo draw_tree( $one );\n echo \"\";\n echo \"
\";\n }\n\n echo \"\";\n echo \"
\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"search\":\n\n $results = people_search($_POST['q']);\n\n if (count($results) > 0)\n {\n echo \"

People Search Results for [\".$_POST['q'].\"]:

\";\n }\n\n echo \"

\\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
\\n\";\n }\n if ($count < 1)\n {\n echo \"

\\n\";\n echo \"There were no results for [\".$_POST['q'].\"].\";\n if (strlen($_POST['q']) < 2)\n {\n echo \"

\\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

\\n\";\n echo \"

Add a New Person to the Database

\\n\";\n }\n }\n echo \"

\\n\";\n }\n\n echo \"

\\n\";\n\n break;\n\n ###############################################\n case \"search_title_abstract\":\n\n $results = title_abstract_search($_POST['qta']);\n\n if (count($results) > 0)\n {\n echo \"

Title/Abstract Search Results for [\".$_POST['qta'].\"]:

\";\n }\n\n echo \"

\\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
\\n\";\n }\n if ($count < 1)\n {\n echo \"

\\n\";\n echo \"There were no results for [\".$_POST['qta'].\"].\";\n if (strlen($_POST['qta']) < 2)\n {\n echo \"

\\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

\\n\";\n }\n }\n echo \"

\\n\";\n }\n\n echo \"

\\n\";\n\n break;\n\n ###############################################\n case \"search_notes\":\n\n if (is_admin()){\n\n $results = notes_search($_POST['qn']);\n\n if (count($results) > 0)\n {\n echo \"

Admin Notes Search Results for [\".$_POST['qn'].\"]:

\";\n }\n\n echo \"

\\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
\\n\";\n }\n if ($count < 1)\n {\n echo \"

\\n\";\n echo \"There were no results for [\".$_POST['qm'].\"].\";\n if (strlen($_POST['qn']) < 2)\n {\n echo \"

\\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

\\n\";\n }\n }\n echo \"

\\n\";\n }\n\n echo \"

\\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"merge_doit\":\n\n if (is_admin()){\n\n # delete the family tree's dotgraphs of each person\n foreach ($_POST['mergers'] as $one)\n {\n delete_associated_dotgraphs($one);\n }\n\n # pop off one of the people_ids\n $into = array_pop($_POST['mergers']);\n\n # merge each remaining person into the one above\n foreach ($_POST['mergers'] as $one)\n {\n merge_two_people($one,$into);\n }\n\n # recalculate MPACT scores for merged person id\n calculate_scores($into);\n\n action_box(\"Merge was Successful\",2,$_SERVER['SCRIPT_NAME'].\"?show=\".$_POST['show']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"create_discipline\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['title'] == \"\")\n {\n action_box(\"Need to have at least a Discipline Title.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_discipline\");\n }\n elseif (is_duplicate_discipline($_POST['title']))\n {\n action_box(\"Discipline (\".$_POST['title'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else\n {\n\n # Create Discipline\n $query = \"INSERT disciplines\n SET\n title = '\".$_POST['title'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # Get the just created discipline_id\n $query = \"SELECT id as new_discipline_id, title FROM disciplines\n WHERE\n title = '\".$_POST['title'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n # log it\n mpact_logger(\"created discipline[\".$new_discipline_id.\"] (\".$title.\")\");\n\n action_box(\"Discipline Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_discipline\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['title'] == \"\")\n {\n action_box(\"Need to have at least a Discipline Title.\",3,$_SERVER['SCRIPT_NAME'].\"?op=edit_discipline&id=\".$_POST['discipline_id'].\"\");\n }\n elseif (is_duplicate_discipline($_POST['title']))\n {\n action_box(\"Discipline (\".$_POST['title'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else\n {\n\n # Edit Discipline\n $query = \"UPDATE disciplines\n SET\n title = '\".$_POST['title'].\"'\n WHERE\n id = '\".$_POST['discipline_id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # log it\n mpact_logger(\"edited discipline[\".$_POST['discipline_id'].\"] (\".$_POST['title'].\")\");\n\n action_box(\"Discipline Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_school\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $_POST = array_map('trim',$_POST);\n\n if ($_POST['fullname'] == \"\" || $_POST['country'] == \"\")\n {\n action_box(\"Need to have at least a School name and Country.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_school\");\n }\n elseif (is_duplicate_school($_POST['fullname']))\n {\n action_box(\"School (\".$_POST['fullname'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else\n {\n\n # Create School\n $query = \"INSERT schools\n SET\n fullname = '\".$_POST['fullname'].\"',\n country = '\".$_POST['country'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # Get the just created school_id\n $query = \"SELECT id as new_school_id, fullname FROM schools\n WHERE\n fullname = '\".$_POST['fullname'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n # log it\n mpact_logger(\"created school[\".$new_school_id.\"] (\".$fullname.\")\");\n\n action_box(\"School Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['fullname'] == \"\" || $_POST['country'] == \"\")\n {\n action_box(\"Need to have at least a School name and Country.\",3,$_SERVER['SCRIPT_NAME'].\"?op=edit_school&id=\".$_POST['school_id'].\"\");\n }\n elseif (is_duplicate_school($_POST['fullname']))\n {\n action_box(\"School (\".$_POST['fullname'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else\n {\n\n # Edit School\n $query = \"UPDATE schools\n SET\n fullname = '\".$_POST['fullname'].\"',\n country = '\".$_POST['country'].\"'\n WHERE\n id = '\".$_POST['school_id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # log it\n mpact_logger(\"edited school[\".$_POST['school_id'].\"] (\".$_POST['fullname'].\")\");\n\n action_box(\"School Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_person\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['lastname'] == \"\")\n {\n action_box(\"Need to have at least a Last Name.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_person\");\n }\n else\n {\n # Create Name\n $query = \"INSERT names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # Get the just created name_id\n $query = \"SELECT id as new_name_id FROM names\n WHERE\n firstname = '\".$_POST['firstname'].\"' AND\n middlename = '\".$_POST['middlename'].\"' AND\n lastname = '\".$_POST['lastname'].\"' AND\n suffix = '\".$_POST['suffix'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n # Create Person with new_name_id\n $query = \"INSERT people\n SET\n preferred_name_id = '\".$new_name_id.\"',\n degree = '\".$_POST['degree'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # Get the just created person_id\n $query = \"SELECT id as new_person_id FROM people\n WHERE\n preferred_name_id = '\".$new_name_id.\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n # Sync them together with new_person_id\n $query = \"UPDATE names\n SET\n person_id = '\".$new_person_id.\"'\n WHERE\n id = '\".$new_name_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $after = find_person($new_person_id);\n\n action_box(\"Person Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$new_person_id);\n\n # log it\n mpact_logger(\"created person[\".$new_person_id.\"] (\".$after['fullname'].\")\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"remove_mentor\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if (remove_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']))\n {\n action_box(\"Mentor Removed\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['student_id']);\n }\n else\n {\n action_box(\"Nope.\");\n }\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);\n\n action_box(\"Mentor Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['student_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_student\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);\n\n action_box(\"Student Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['mentor_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_name\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person($_POST['id']);\n\n $query = \"INSERT names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"',\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # get the just created name_id\n $query = \"SELECT id as new_name_id FROM names\n WHERE\n firstname = '\".$_POST['firstname'].\"' AND\n middlename = '\".$_POST['middlename'].\"' AND\n lastname = '\".$_POST['lastname'].\"' AND\n suffix = '\".$_POST['suffix'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n # find that full name from the DB\n $added = find_name($new_name_id);\n\n action_box(\"Name Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n # log it\n mpact_logger(\"added name (\".$added['fullname'].\") for person[\".$_POST['id'].\"] (\".$person['fullname'].\")\");\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_name\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $before = find_name($_POST['name_id']);\n\n $query = \"UPDATE names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"'\n WHERE\n id = '\".$_POST['name_id'].\"' AND\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $after = find_name($_POST['name_id']);\n\n # delete dotgraph for this person\n delete_associated_dotgraphs($_POST['id']);\n\n action_box(\"Name Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n # log it\n mpact_logger(\"edited name[\".$_POST['name_id'].\"] for person[\".$_POST['id'].\"] from (\".$before['fullname'].\") to (\".$after['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person(intval($_POST['person_id']));\n\n $query = \"INSERT urls\n SET\n url = '\".$_POST['url'].\"',\n description = '\".$_POST['description'].\"',\n updated_at = now(),\n person_id = '\".$_POST['person_id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Reference URL Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id'].\"#urls\");\n # log it\n mpact_logger(\"added URL[\".substr($_POST['url'], 0, 30).\"] for person[\".$_POST['person_id'].\"] (\".$person['fullname'].\")\");\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $url = find_url(intval($_POST['id']));\n $person = find_person($url['person_id']);\n\n $query = \"UPDATE urls\n SET\n url = '\".$_POST['url'].\"',\n description = '\".$_POST['description'].\"',\n updated_at = now()\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Reference URL Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$url['person_id'].\"#urls\");\n # log it\n mpact_logger(\"edited URL[\".substr($_POST['url'], 0, 30).\"] for person[\".$url['person_id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $url = find_url(intval($_POST['id']));\n $person = find_person($url['person_id']);\n\n $query = \"DELETE FROM urls\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Reference URL Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$url['person_id'].\"#urls\");\n # log it\n mpact_logger(\"deleted URL[\".substr($url['url'], 0, 30).\"] for person[\".$url['person_id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_degree\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person(intval($_POST['id']));\n\n $query = \"UPDATE people\n SET\n degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Degree Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$person['id']);\n # log it\n mpact_logger(\"edited degree[\".$_POST['degree'].\"] for person[\".$person['id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_dissertation\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $schools = find_schools();\n\n $person = find_person($_POST['person_id']);\n\n $query = \"INSERT INTO dissertations\n SET\n person_id = '\".$_POST['person_id'].\"',\n discipline_id = '\".$_POST['discipline_id'].\"',\n school_id = '\".$_POST['school_id'].\"',\n completedyear = '\".$_POST['completedyear'].\"',\n status = '\".$_POST['status'].\"',\n title = '\".$_POST['title'].\"',\n abstract = '\".$_POST['abstract'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE people\n SET degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['person_id'].\"'\";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Dissertation Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id']);\n # log it\n $dissertation = find_dissertation_by_person($_POST['person_id']);\n mpact_logger(\"create dissertation[\".$dissertation['id'].\"] (\".$person['fullname'].\") with school[\".$dissertation['school_id'].\"] (\".$schools[$dissertation['school_id']].\") in year(\".$dissertation['completedyear'].\") with status (\".$statuscodes[$_POST['status']].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"edit_dissertation\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n\n $dissertation = find_dissertation($_POST['id']);\n $person = find_person($dissertation['person_id']);\n\n $query = \"UPDATE dissertations\n SET\n school_id = '\".$_POST['school_id'].\"',\n discipline_id = '\".$_POST['discipline_id'].\"',\n completedyear = '\".$_POST['completedyear'].\"',\n status = '\".$_POST['status'].\"',\n notes = '\".$_POST['notes'].\"',\n title = '\".$_POST['title'].\"',\n abstract = '\".$_POST['abstract'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE people\n SET degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['person_id'].\"'\";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Dissertation Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id']);\n # log it\n mpact_logger(\"edit dissertation[\".$_POST['id'].\"] (\".$person['fullname'].\") from school[\".$dissertation['school_id'].\"] (\".$schools[$dissertation['school_id']].\") in year(\".$dissertation['completedyear'].\") to school[\".$_POST['school_id'].\"] (\".$schools[$_POST['school_id']].\") in year(\".$_POST['completedyear'].\")\");\n # look for changes\n # degree\n if ($person['degree'] != $_POST['degree'])\n {\n mpact_logger($dissertation['id'].\" updated degree [\".$_POST['degree'].\"]\",\"dissertation\");\n }\n # discipline\n if ($dissertation['discipline_id'] != $_POST['discipline_id'])\n {\n mpact_logger($dissertation['id'].\" updated discipline [\".$_POST['discipline_id'].\" (\".$disciplines[$_POST['discipline_id']].\")]\",\"dissertation\");\n }\n # school\n if ($dissertation['school_id'] != $_POST['school_id'])\n {\n mpact_logger($dissertation['id'].\" updated school [\".$_POST['school_id'].\" (\".$schools[$_POST['school_id']].\")]\",\"dissertation\");\n }\n # year\n if ($dissertation['completedyear'] != $_POST['completedyear'])\n {\n mpact_logger($dissertation['id'].\" updated completedyear [\".$_POST['completedyear'].\"]\",\"dissertation\");\n }\n # title\n if ($dissertation['title'] != $_POST['title'])\n {\n mpact_logger($dissertation['id'].\" updated title [\".$_POST['title'].\"]\",\"dissertation\");\n }\n # abstract\n if ($dissertation['abstract'] != $_POST['abstract'])\n {\n mpact_logger($dissertation['id'].\" updated abstract [\".$_POST['abstract'].\"]\",\"dissertation\");\n }\n # status\n if ($dissertation['status'] != $_POST['status'])\n {\n mpact_logger($dissertation['id'].\" updated status [\".$statuscodes[$_POST['status']].\"]\",\"dissertation\");\n }\n # status\n if ($dissertation['notes'] != $_POST['notes'])\n {\n mpact_logger($dissertation['id'].\" updated notes [\".$_POST['notes'].\"]\",\"dissertation\");\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_person\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if (delete_person($_POST['id']))\n {\n action_box(\"Person Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n }\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"delete_name\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $name = find_name($_POST['name_id']);\n $person = find_person($_POST['id']);\n\n $query = \"DELETE FROM names\n WHERE\n id = '\".$_POST['name_id'].\"' AND\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Name Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n\n # log it\n mpact_logger(\"deleted name[\".$_POST['name_id'].\"] (\".$name['fullname'].\") from person[\".$person['id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n break;\n\n ###############################################\n default:\n // oops - not supposed to be here\n action_box(\"oops, back to the front page...\",2);\n\n\n }\n\n\n}\n\nxhtml_web_footer();\n\n?>\n", "mpact_include.php": " $val)\n foreach ($aSubtrahends as $aSubtrahend)\n if (array_key_exists($key, $aSubtrahend))\n unset ($ar1[$key]);\n return $ar1;\n}\n\n# -------------------------------------------------------------------------------\nfunction action_box($message,$bounce = \"0\",$location = \"index.php\"){\n\n echo \"\n

\n $message\n

\n

\n \";\n\n if ($bounce != \"0\"){\n echo \"\n \n

\n Forwarding in $bounce seconds (or click here to do the same)\n

\n \";\n }\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_orig_web_header(){\n\n # make search box happy\n if (!isset($_POST['q'])){$_POST['q'] = \"\";}\n if (!isset($_POST['qta'])){$_POST['qta'] = \"\";}\n if (!isset($_POST['qn'])){$_POST['qn'] = \"\";}\n\n # print out header info\n echo \"\n\n \n \n \n MPACT\n\n \n \n \n\n \n \n\n \n\n \n \n \n\n
\n \n \n \n \n \n
\n
\n MPACT -\n Database -\n \n People Search: \n
-\n
\n \n Title/Abstract Search: \n
\n\";\n if (is_admin()){\n echo \" -
\n \n Admin Notes Search: \n
\";\n }\n echo \"
\n\";\n if (is_admin()){\n echo $_SESSION['MPACT']['fullname'].\" (\".$_SESSION['MPACT']['username'].\") - Logout\";\n }\n else{\n $host_info = get_environment_info();\n if ($host_info['hostname'] != \"sils\"){\n echo \"Login\";\n }\n }\necho \"\n
\n

\n\n \";\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_web_header(){\n\n # make search box happy\n if (!isset($_POST['q'])){$_POST['q'] = \"\";}\n if (!isset($_POST['qta'])){$_POST['qta'] = \"\";}\n if (!isset($_POST['qn'])){$_POST['qn'] = \"\";}\n\n # print out header info\n echo \"\n\n \n \n \n MPACT\n \n \n \n \n \n\n\";\n\necho \"

\";\nif (is_admin()){\n echo $_SESSION['MPACT']['fullname'].\" (\".$_SESSION['MPACT']['username'].\") - Logout\";\n}\nelse{\n echo \"Login\";\n}\necho \"

\";\necho \"
\";\n\necho \"\n
\n \n \n\n \n\n \n\n \n\n \n
\n \n \n \n \n Publications  • \n Project Statistics\n
\n
\n Glossary  • \n Schools  • \n Disciplines\n
\n
\n \n People Search: \n
\n    \n
\n \n Title/Abstract Search: \n
\";\nif (is_admin()){\n echo \"

Administrator Pages\";\n echo \"
\n \n Admin Notes Search: \n
\";\n}\necho \"
\n \n
\n
\n\n
\n
\n\n
\n\n \";\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_web_footer(){\n echo \"\n\n
\n\n \n \n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction is_email_valid ($address)\n{\n\n\t# http://www.zend.com/codex.php?id=285&single=1\n\n return (preg_match(\n '/^[-!#$%&\\'*+\\\\.\\/0-9=?A-Z^_`{|}~]+'. // the user name\n '@'. // the ubiquitous at-sign\n '([-0-9A-Z]+\\.)+' . // host, sub-, and domain names\n '([0-9A-Z]){2,4}$/i', // top-level domain (TLD)\n trim($address)));\n}\n\n# -------------------------------------------------------------------------------\nfunction find_glossaryterms()\n{\n global $dbh;\n $query = \"SELECT id, term, definition FROM glossary\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $glossaryterms = array();\n while ( $line = mysqli_fetch_array($result)) {\n $glossaryterms['ids'][$line['term']] = $line['id'];\n $glossaryterms['defs'][$line['id']] = $line['definition'];\n }\n return $glossaryterms;\n}\n\n# -------------------------------------------------------------------------------\nfunction show_glossary()\n{\n global $dbh;\n $query = \"SELECT id, term, definition FROM glossary ORDER BY term ASC\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $results = array();\n while ( $line = mysqli_fetch_array($result)) {\n array_push($results,$line);\n }\n\n echo \"

Glossary

\\n\";\n\n echo \"

\\n\";\n\n foreach ($results as $one)\n {\n echo \"\".$one['term'].\": \";\n echo $one['definition'];\n if (is_admin())\n {\n echo \" EDIT \";\n }\n echo \"

\";\n }\n\n echo \"

\\n\";\n\n}\n\n# -------------------------------------------------------------------------------\nfunction show_glossaryterm($id)\n{\n global $dbh;\n $query = \"SELECT id, term, definition FROM glossary WHERE id = $id\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $results = array();\n while ( $line = mysqli_fetch_array($result)) {\n $glossaryterm = $line;\n }\n\n echo \"

Full Glossary Listing

\";\n\n echo \"

Glossary

\\n\";\n\n echo \"

\\n\";\n\n echo \"\".$glossaryterm['term'].\": \";\n echo $glossaryterm['definition'];\n if (is_admin())\n {\n echo \" EDIT \";\n }\n echo \"

\";\n\n echo \"

\\n\";\n\n}\n\n# -------------------------------------------------------------------------------\nfunction show_alphabet()\n{\n\n $alphabet_letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n $alphabet = preg_split('//', $alphabet_letters, -1, PREG_SPLIT_NO_EMPTY);\n\n echo \"
\\n\";\n echo \"

Dissertation Authors and Mentors by Last Name

\";\n echo \"

\";\n foreach ($alphabet as $letter)\n {\n if ($letter != \"A\"){echo \" - \";}\n echo \"$letter\";\n }\n echo \"

\";\n echo \"
\\n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction search_box($q=\"\")\n{\n echo \"
\\n\";\n echo \"\\n\";\n echo \"

People Search: \";\n if ($q)\n {\n echo \"\\n\";\n }\n else\n {\n echo \"\\n\";\n }\n echo \"

\\n\";\n echo \"
\\n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction people_search($q)\n{\n global $dbh;\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = explode(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$pieces[0].\"%' OR\n n.middlename LIKE '%\".$pieces[0].\"%' OR\n n.lastname LIKE '%\".$pieces[0].\"%' OR\n n.suffix LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (n.firstname LIKE '%\".$pieces[1].\"%' OR\n n.middlename LIKE '%\".$pieces[1].\"%' OR\n n.lastname LIKE '%\".$pieces[1].\"%' OR\n n.suffix LIKE '%\".$pieces[1].\"%')\n\n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$pieces[0].\"%' OR\n n.middlename LIKE '%\".$pieces[0].\"%' OR\n n.lastname LIKE '%\".$pieces[0].\"%' OR\n n.suffix LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (n.firstname LIKE '%\".$pieces[1].\"%' OR\n n.middlename LIKE '%\".$pieces[1].\"%' OR\n n.lastname LIKE '%\".$pieces[1].\"%' OR\n n.suffix LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (n.firstname LIKE '%\".$pieces[2].\"%' OR\n n.middlename LIKE '%\".$pieces[2].\"%' OR\n n.lastname LIKE '%\".$pieces[2].\"%' OR\n n.suffix LIKE '%\".$pieces[2].\"%')\n\n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$q.\"%' OR\n n.middlename LIKE '%\".$q.\"%' OR\n n.lastname LIKE '%\".$q.\"%' OR\n n.suffix LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction title_abstract_search($q)\n{\n global $dbh;\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = explode(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$pieces[0].\"%' OR\n d.abstract LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (d.title LIKE '%\".$pieces[1].\"%' OR\n d.abstract LIKE '%\".$pieces[1].\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$pieces[0].\"%' OR\n d.abstract LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (d.title LIKE '%\".$pieces[1].\"%' OR\n d.abstract LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (d.title LIKE '%\".$pieces[2].\"%' OR\n d.abstract LIKE '%\".$pieces[2].\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$q.\"%' OR\n d.abstract LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction notes_search($q)\n{\n global $dbh;\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = explode(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (d.notes LIKE '%\".$pieces[1].\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (d.notes LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (d.notes LIKE '%\".$pieces[2].\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction encode_linebreaks($bigtext)\n{\n # from http://us3.php.net/str_replace\n $order = array(\"\\r\\n\", \"\\n\", \"\\r\");\n $replace = '
';\n // Processes \\r\\n's first so they aren't converted twice.\n $with_breaks = str_replace($order, $replace, $bigtext);\n return $with_breaks;\n}\n\n# -------------------------------------------------------------------------------\nfunction get_logs($offset=\"0\")\n{\n global $dbh;\n# echo \"[$offset]\";\n $query = \"SELECT * FROM logs ORDER BY id DESC LIMIT 100\";\n if ($offset != \"\"){$query .= \" OFFSET $offset\";}\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n# echo $query;\n $entries = array();\n $counter = 0;\n while ( $line = mysqli_fetch_array($result)) {\n $counter++;\n $entries[$counter] = $line;\n }\n return $entries;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction get_dissertation_history($id)\n{\n global $dbh;\n $query = \"SELECT * FROM logs\n WHERE type='dissertation' AND message LIKE '$id %'\n ORDER BY id DESC\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n# echo $query;\n $entries = array();\n $counter = 0;\n while ( $line = mysqli_fetch_array($result)) {\n $counter++;\n $entries[$counter] = $line;\n }\n return $entries;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction find_all_people()\n{\n global $dbh;\n # return array of all people_ids in database (slow....)\n # all people\n $query = \"SELECT id as person_id FROM people\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $people[] = $line['person_id'];\n }\n return $people;\n}\n\n# -------------------------------------------------------------------------------\nfunction get_person_link($person_id)\n{\n\n $disciplines = find_disciplines();\n $person = find_person($person_id);\n\n $fullname = trim($person['firstname'].\" \".$person['middlename'].\" \".$person['lastname'].\" \".$person['suffix']);\n\n $dissertation = find_dissertation_by_person($person_id);\n $discipline = isset($dissertation['discipline_id']) ? $disciplines[$dissertation['discipline_id']] : \"\";\n\n $link = \"\".$fullname.\"\";\n\n return $link;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_orphans()\n{\n global $dbh;\n\n # finding people with no dissertation and no students\n\n # all people\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n\n WHERE\n p.preferred_name_id = n.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $people[$line['person_id']] = $line;\n# echo \" \".$line['person_id'].\"
\\n\";\n }\n\n echo \"people: \".count($people).\"
\\n\";\n\n # with dissertations only\n $query = \"SELECT\n p.id as person_id\n FROM\n people p, dissertations d\n WHERE\n d.person_id = p.id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $with_dissertations[$line['person_id']] = $line;\n# echo \" \".$line['person_id'].\"
\\n\";\n }\n\n echo \"dissertations: \".count($with_dissertations).\"
\\n\";\n\n # all people - dissertations = teachers only\n $potentialmentors = array_key_diff($people,$with_dissertations);\n\n echo \"potential mentors: \".count($potentialmentors).\"
\\n\";\n\n # orphans = teachers who don't have students\n # get advisorships\n $query = \"SELECT person_id FROM advisorships\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[$line['person_id']] = $line;\n }\n echo \"advisors: \".count($advisors).\"
\\n\";\n # get committeeships\n $query = \"SELECT person_id FROM committeeships\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[$line['person_id']] = $line;\n }\n echo \"committeemembers: \".count($committeemembers).\"
\\n\";\n # subtract advisorships from teachers\n $potentialmentors = array_key_diff($potentialmentors,$advisors);\n # subtract committeeships from remaining teachers\n $orphans = array_key_diff($potentialmentors,$committeemembers);\n echo \"orphans: \".count($orphans).\"
\\n\";\n\n return $orphans;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction is_orphan($person_id)\n{\n global $dbh;\n # confirm person exists\n $query = \"SELECT * FROM people WHERE id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $line = mysqli_fetch_array($result);\n if (!$line['id']){echo \"not a person\";return 0;}\n # confirm no dissertation\n $query = \"SELECT * FROM dissertations WHERE person_id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n echo \"found a dissertation\";\n return 0;\n }\n # confirm not a committeemember\n $query = \"SELECT * FROM committeeships WHERE person_id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n echo \"found a committeeship\";\n return 0;\n }\n # confirm not an advisor\n $query = \"SELECT * FROM advisorships WHERE person_id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n echo \"found an advisorship\";\n return 0;\n }\n return 1;\n}\n# -------------------------------------------------------------------------------\nfunction delete_person($person_id)\n{\n global $dbh;\n if (is_orphan($person_id))\n {\n $before = find_person($person_id);\n # delete all names\n $query = \"DELETE FROM names WHERE person_id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # delete the person\n $query = \"DELETE FROM people WHERE id = '\".$person_id.\"' LIMIT 1\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # log it\n mpact_logger(\"deleted person[\".$person_id.\"] (\".$before['fullname'].\")\");\n return 1;\n }\n else\n {\n action_box(\"Not an orphan - Cannot delete this person.\");\n return 0;\n }\n}\n# -------------------------------------------------------------------------------\nfunction remove_duplicate_names($person_id)\n{\n global $dbh;\n\n $names = array();\n $deleteme = array();\n\n\n $before = find_person($person_id);\n\n // get the preferred_name_id\n $query = \"SELECT preferred_name_id\n FROM people\n WHERE id = '\".$person_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n // get the full preferred_name\n $query = \"SELECT * FROM names\n WHERE\n id = '\".$preferred_name_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $fullname = \"\".$line['firstname'].\" \".$line['middlename'].\" \".$line['lastname'].\" \".$line['suffix'].\"\";\n $names[$fullname] = $line['id'];\n }\n\n // get the rest of the names for this person\n $query = \"SELECT * FROM names\n WHERE\n person_id = '\".$person_id.\"' AND\n id != '\".$preferred_name_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $fullname = \"\".$line['firstname'].\" \".$line['middlename'].\" \".$line['lastname'].\" \".$line['suffix'].\"\";\n if (isset($names[$fullname]))\n {\n $deleteme[] = $line['id'];\n }\n else\n {\n $names[$fullname] = $line['id'];\n }\n }\n\n // delete each deleteme id\n foreach ($deleteme as $one)\n {\n $query = \"DELETE FROM names\n WHERE\n id = '\".$one.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n }\n\n # log it\n mpact_logger(\"removed duplicate names for person[\".$person_id.\"] (\".$before['fullname'].\")\");\n\n}\n\n# -------------------------------------------------------------------------------\nfunction add_mentor($type,$student_id,$mentor_id)\n{\n global $dbh;\n $student = find_person($student_id);\n $mentor = find_person($mentor_id);\n $dissertation = find_dissertation_by_person($student_id);\n\n if ($type == \"A\")\n {\n # find existing advisors for this student\n $advisors = find_advisors_for_person($student_id);\n # if new/different - then add them to the student's dissertation\n if (in_array($mentor_id,$advisors))\n {\n # skip - already listed as advisor\n }\n else\n {\n $query = \"INSERT advisorships\n SET\n dissertation_id = '\".$dissertation['id'].\"',\n person_id = '\".$mentor_id.\"'\n \";\n# echo $query;\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"add advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n # delete existing dotgraphs - they'll need to be regenerated\n # has to happen after we add the advisor link itself\n delete_associated_dotgraphs($student_id);\n }\n }\n elseif ($type == \"C\")\n {\n # find existing committee members for this student\n $committee = find_committee_for_person($student_id);\n # if new/different - then add them to the student's dissertation\n if (in_array($mentor_id,$committee))\n {\n # skip - already on committee\n }\n else\n {\n $query = \"INSERT committeeships\n SET\n dissertation_id = '\".$dissertation['id'].\"',\n person_id = '\".$mentor_id.\"'\n \";\n# echo $query;\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"add committeeship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n }\n }\n else\n {\n # nothing\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction remove_mentor($type,$student_id,$mentor_id)\n{\n global $dbh;\n $dissertation = find_dissertation_by_person($student_id);\n\n $student = find_person($student_id);\n $mentor = find_person($mentor_id);\n\n if ($type == \"A\")\n {\n # find dissertation id\n $dissertation = find_dissertation_by_person($student_id);\n # find existing advisors for this student\n $advisors = find_advisors_for_person($student_id);\n # if found in db, remove them\n if (!in_array($mentor_id,$advisors))\n {\n echo \"not an advisor for this student\";\n return 0;\n }\n else\n {\n # delete existing dotgraphs - they'll need to be regenerated\n # has to happen before we delete the advisor link itself\n delete_associated_dotgraphs($student_id);\n # delete the advisorship\n $query = \"DELETE FROM advisorships\n WHERE\n person_id = '\".$mentor_id.\"' AND\n dissertation_id = '\".$dissertation['id'].\"'\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"remove advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n return 1;\n }\n }\n elseif ($type == \"C\")\n {\n # find dissertation id\n $dissertation = find_dissertation_by_person($student_id);\n # find existing committee members for this student\n $committee = find_committee_for_person($student_id);\n # if found in db, remove them\n if (!in_array($mentor_id,$committee))\n {\n echo \"not on committee for this student\";\n return 0;\n }\n else\n {\n $query = \"DELETE FROM committeeships\n WHERE\n person_id = '\".$mentor_id.\"' AND\n dissertation_id = '\".$dissertation['id'].\"'\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"remove advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n return 1;\n }\n }\n else\n {\n echo \"has to be A or C, dude\";\n return 0;\n }\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_all_people_for_selectbox($with_dissertation=\"0\")\n{\n global $dbh;\n if ($with_dissertation == \"0\")\n {\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n\n WHERE\n p.preferred_name_id = n.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n }\n else\n {\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n, dissertations d\n WHERE\n p.preferred_name_id = n.id AND\n d.person_id = p.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n }\n // echo $query;\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $people[$line['person_id']] = $line;\n }\n\n return $people;\n}\n\n# -------------------------------------------------------------------------------\nfunction merge_two_people($from_id, $into_id)\n{\n global $dbh;\n\n $from_person = find_person($from_id);\n $into_person = find_person($into_id);\n\n\n $query = \"UPDATE advisorships\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE dissertations\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE committeeships\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE urls\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n // move each 'from' name to the 'into' person\n\n $query = \"UPDATE names\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n // remove any new duplicates in the names table\n\n remove_duplicate_names($into_person['id']);\n\n // remove 'from' person from the database\n\n $query = \"DELETE FROM people\n WHERE\n id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # log it\n mpact_logger(\"merged two people [\".$from_id.\"] (\".$from_person['fullname'].\") and [\".$into_id.\"] (\".$into_person['fullname'].\")\");\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_aliases($person_id)\n{\n global $dbh;\n\n $query = \"SELECT preferred_name_id\n FROM people\n WHERE id = '\".$person_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n $names = array();\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, n.id\n FROM\n names n\n WHERE\n n.person_id = '\".$person_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $names[$line['id']] = $line;\n }\n\n unset($names[$preferred_name_id]);\n\n return $names;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_person($person_id)\n{\n global $dbh;\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, p.degree,\n p.id, p.preferred_name_id\n FROM\n names n, people p\n WHERE\n p.preferred_name_id = n.id AND\n p.id = \".$person_id.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $person = $line;\n $person['fullname'] = $person['firstname'];\n if ($person['middlename'] != \"\"){$person['fullname'] .= \" \".$person['middlename'];}\n if ($person['lastname'] != \"\"){$person['fullname'] .= \" \".$person['lastname'];}\n if ($person['suffix'] != \"\"){$person['fullname'] .= \" \".$person['suffix'];}\n }\n\n return $person;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_url($url_id)\n{\n global $dbh;\n\n $url_id = intval($url_id);\n $query = \"SELECT\n u.id, u.url, u.description, u.updated_at, u.person_id\n FROM\n urls u\n WHERE\n u.id = '\".$url_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $url = $line;\n }\n\n return $url;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_urls_by_person($person_id)\n{\n global $dbh;\n\n $person_id = intval($person_id);\n $query = \"SELECT\n u.id, u.url, u.description, u.updated_at, u.person_id\n FROM\n urls u\n WHERE\n u.person_id = '\".$person_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $urls = array();\n while ( $line = mysqli_fetch_array($result)) {\n $urls[$line['id']] = $line;\n }\n\n return $urls;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dissertation($dissertation_id)\n{\n global $dbh;\n\n $dissertation_id = intval($dissertation_id);\n $query = \"SELECT\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n WHERE\n d.id = '\".$dissertation_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertation = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertation = $line;\n }\n\n return $dissertation;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dissertation_by_person($person_id)\n{\n global $dbh;\n\n $person_id = intval($person_id);\n $query = \"SELECT\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n WHERE\n d.person_id = '\".$person_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertation = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertation = $line;\n }\n\n return $dissertation;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_name($name_id)\n{\n global $dbh;\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix\n FROM\n names n\n WHERE\n n.id = \".$name_id.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $name = $line;\n $name['fullname'] = $name['firstname'];\n if ($name['middlename'] != \"\"){$name['fullname'] .= \" \".$name['middlename'];}\n if ($name['lastname'] != \"\"){$name['fullname'] .= \" \".$name['lastname'];}\n if ($name['suffix'] != \"\"){$name['fullname'] .= \" \".$name['suffix'];}\n }\n\n return $name;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline($discipline_id)\n{\n global $dbh;\n $discipline_id = intval($discipline_id);\n $query = \"SELECT\n d.title, d.description\n FROM\n disciplines d\n WHERE\n d.id = \".$discipline_id.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $discipline = $line;\n }\n\n return $discipline;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_ancestors_for_group($groupofpeople)\n{\n $originalgroup = $groupofpeople;\n // find advisors, and if they're new, add them to the list and recurse\n foreach ($originalgroup as $person)\n {\n $advisors = find_advisors_for_person($person);\n foreach ($advisors as $one)\n {\n $groupofpeople[] = $one;\n }\n }\n $groupofpeople = array_unique($groupofpeople);\n if (count(array_diff($groupofpeople,$originalgroup)) > 0)\n {\n return find_ancestors_for_group($groupofpeople);\n }\n else\n {\n return $originalgroup;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_descendents_for_group($groupofpeople)\n{\n $originalgroup = $groupofpeople;\n // find descendents, and if they're new, add them to the list and recurse\n foreach ($originalgroup as $person)\n {\n $advisees = find_advisorships_under_person($person);\n foreach ($advisees as $one)\n {\n $groupofpeople[] = $one;\n }\n }\n $groupofpeople = array_unique($groupofpeople);\n if (count(array_diff($groupofpeople,$originalgroup)) > 0)\n {\n return find_descendents_for_group($groupofpeople);\n }\n else\n {\n return $originalgroup;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction T_score($person)\n{\n # total number of descendants (nodes) in a person's tree\n $group = array($person);\n $total = count(find_descendents_for_group($group)); # including self\n $descendents = $total - 1; # minus self\n return $descendents;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_mpact_score($person,$score_type)\n{\n global $dbh;\n $query = \"SELECT $score_type as score FROM people WHERE id='$person'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n return $score;\n}\n\n# -------------------------------------------------------------------------------\nfunction FMI_score($person)\n{\n $FMI_score = count(find_advisorships_under_person($person));\n# print \"person $person -- fmi $FMI_score
\";\n $committeeships = find_committeeships_under_person($person);\n foreach ($committeeships as $one)\n {\n $numA = count(find_advisors_for_person($one));\n# echo \" - #A [$numA] ----
\";\n $numC = count(find_committee_for_person($one));\n# echo \"#C [$numC] ---- \\n\";\n $FMI_score += 1/($numA + $numC);\n# echo \"
\";\n }\n // echo \"fractional mentorship, inclusive (FMI = A + eachC(1/(#A+#C)) )
\\n\";\n return round($FMI_score,3);\n}\n\n# -------------------------------------------------------------------------------\nfunction FME_score($person)\n{\n $FME_score = count(find_advisorships_under_person($person));\n# print \"person $person -- fme $FME_score
\";\n $committeeships = find_committeeships_under_person($person);\n foreach ($committeeships as $one)\n {\n $numC = count(find_committee_for_person($one));\n# echo \"#C [$numC] ---- \\n\";\n $FME_score += 1/($numC);\n# echo \"
\";\n }\n // echo \"fractional mentorship, inclusive (FMI = A + eachC(1/(#A+#C)) )
\\n\";\n return round($FME_score,3);\n}\n\n# -------------------------------------------------------------------------------\nfunction TA_score($person)\n{\n # total number of descendants who have advised students themselves\n $without_students = array();\n $descendents = find_descendents_for_group(array($person)); # including self\n foreach ($descendents as $d)\n {\n if (count(find_descendents_for_group(array($d))) == 1)\n {\n $without_students[] = $d;\n }\n }\n $descendents_who_advised = array_diff($descendents,$without_students); # including self\n return max(count($descendents_who_advised) - 1,0); # minus self\n}\n\n# -------------------------------------------------------------------------------\nfunction W_score($person)\n{\n # should handle multigenerational advisorships correctly...\n\n # return the max of the widths of each generation of descendents\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n# print \"$gencount <-- gen
\";\n# print count($advisees).\" advisees - \";\n# print_r($advisees);\n# print \"
\";\n# print \"
\";\n# print count($remaining).\" remaining - \";\n# print_r($remaining);\n# print \"
\";\n# print \"
\";\n while (count($remaining) > 0)\n {\n $gencount++;\n# print \"$gencount <-- gen
\";\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n# print count($advisees).\" advisees - \";\n# print_r($advisees);\n# print \"
\";\n# print \"
\";\n# print count($remaining).\" remaining - \";\n# print_r($remaining);\n# print \"
\";\n# print \"
\";\n }\n# print_r($gen_widths);\n return max($gen_widths);\n}\n\n# -------------------------------------------------------------------------------\nfunction TD_score($person)\n{\n # there is currently a bug in this implementation\n # if a student has two advisors, and they, themselves are related by mentorship\n # this algorithm currently counts gen_width based on advisee count only\n # since $td is calculated based on gen_width values, TD will be missing data\n # A is advisor to B and C\n # B is advisor to C\n # A should have a TD score of 2 (full credit for both advisees)\n # upon further reflection, perhaps this is working correctly, by accident\n\n # return the decayed score\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n while (count($remaining) > 0)\n {\n $gencount++;\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n }\n# print_r($gen_widths);\n $td = 0;\n foreach($gen_widths as $one => $two)\n {\n $num = $two;\n $den = (pow(2,($one-1)));\n $f = $num/$den;\n# print \"$num/$den = $f
\";\n $td = $td + $f;\n }\n return $td;\n}\n\n# -------------------------------------------------------------------------------\nfunction G_score($person)\n{\n # there is currently a bug in this implementation\n # if a student has two advisors, and they, themselves are related by mentorship\n # this algorithm currently misses a generation in the calculation of G\n # A is advisor to B and C\n # B is advisor to C\n # A should have a G score of 2, but will only be calculated a 1\n\n\n # return the number of generations of descendents\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n while (count($remaining) > 0)\n {\n $gencount++;\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n }\n if ($gen_widths[1] == 0)\n {\n return 0;\n }\n else\n {\n return count($gen_widths);\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction advisees_of_group($group)\n{\n # W helper function\n $advisees = array();\n foreach ($group as $one)\n {\n $advisees[] = find_advisorships_under_person($one);\n }\n $advisees = flattenArray($advisees);\n# print_r($advisees);\n# print \" <-- advisees of group
\";\n return $advisees;\n}\n\n# -------------------------------------------------------------------------------\nfunction flattenArray($array)\n{\n $flatArray = array();\n foreach( $array as $subElement ) {\n if( is_array($subElement) )\n $flatArray = array_merge($flatArray, flattenArray($subElement));\n else\n $flatArray[] = $subElement;\n }\n return $flatArray;\n}\n\n# -------------------------------------------------------------------------------\nfunction calculate_scores($person_id)\n{\n global $dbh;\n $A_score = count(find_advisorships_under_person($person_id));\n $C_score = count(find_committeeships_under_person($person_id));\n $AC_score = $A_score + $C_score;\n $G_score = G_score($person_id);\n $W_score = W_score($person_id);\n $T_score = T_score($person_id);\n $TA_score = TA_score($person_id);\n $TD_score = TD_score($person_id);\n $FMI_score = FMI_score($person_id);\n $FME_score = FME_score($person_id);\n\n $query = \"UPDATE people\n SET\n a_score = '$A_score',\n c_score = '$C_score',\n ac_score = '$AC_score',\n g_score = '$G_score',\n w_score = '$W_score',\n t_score = '$T_score',\n ta_score = '$TA_score',\n td_score = '$TD_score',\n fmi_score = '$FMI_score',\n fme_score = '$FME_score',\n scores_calculated = now()\n WHERE\n id = \".$person_id.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n}\n\n# -------------------------------------------------------------------------------\nfunction mpact_scores($passed_person)\n{\n global $dbh;\n $glossaryterms = find_glossaryterms();\n\n $query = \"SELECT\n a_score, c_score, ac_score, g_score, w_score,\n t_score, ta_score, td_score, fmi_score, fme_score,\n scores_calculated\n FROM people\n WHERE id = \".$passed_person.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n $mpact['A'] = $a_score;\n $mpact['C'] = $c_score;\n $mpact['AC'] = $ac_score;\n $scores_output = \"A = $a_score
\\n\";\n $scores_output .= \"C = $c_score
\\n\";\n $scores_output .= \"A+C = $ac_score
\\n\";\n\n $mpact['FMI'] = $fmi_score;\n $mpact['FME'] = $fme_score;\n $FMIdivFULL = ($ac_score>0) ? $fmi_score / $ac_score : 0;\n $FMIdivFULL = round($FMIdivFULL,3);\n $mpact['FMIdivFULL'] = $FMIdivFULL;\n $FMEdivFULL = ($ac_score>0) ? $fme_score / $ac_score : 0;\n $FMEdivFULL = round($FMEdivFULL,3);\n $mpact['FMEdivFULL'] = $FMEdivFULL;\n if (is_admin())\n {\n $scores_output .= \"FMI = $fmi_score
\\n\";\n $scores_output .= \"FME = $fme_score
\\n\";\n $scores_output .= \"FMI/(A+C) = $FMIdivFULL
\\n\";\n $scores_output .= \"FME/(A+C) = $FMEdivFULL
\\n\";\n }\n\n $mpact['T'] = $t_score;\n $scores_output .= \"T = $t_score
\\n\";\n $mpact['G'] = $g_score;\n $scores_output .= \"G = $g_score
\\n\";\n $mpact['W'] = $w_score;\n $scores_output .= \"W = $w_score
\\n\";\n $mpact['TD'] = $td_score;\n $scores_output .= \"D']].\"\\\">TD = $td_score
\\n\";\n $mpact['TA'] = $ta_score;\n $scores_output .= \"A']].\"\\\">TA = $ta_score
\\n\";\n $scores_output .= \"calculated $scores_calculated
\\n\";\n $mpact['output'] = $scores_output;\n\n return $mpact;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_advisors_for_person($person_id)\n{\n global $dbh;\n\n // get person's own advisor(s)\n\n $listing = array();\n\n\n $query = \"SELECT a.person_id\n FROM\n dissertations d,\n advisorships a\n WHERE\n d.person_id = \".$person_id.\" AND\n a.dissertation_id = d.id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_committee_for_person($person_id)\n{\n global $dbh;\n\n // get person's own committee member(s)\n\n $listing = array();\n\n $query = \"SELECT c.person_id\n FROM\n dissertations d,\n committeeships c\n WHERE\n d.person_id = \".$person_id.\" AND\n c.dissertation_id = d.id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_advisorships_under_person($person_id)\n{\n global $dbh;\n\n // get person's advisorships (below)\n\n $listing = array();\n\n $query = \"SELECT d.person_id\n FROM\n dissertations d,\n advisorships a\n WHERE\n a.person_id = \".$person_id.\" AND\n a.dissertation_id = d.id\n ORDER BY\n d.completedyear ASC\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_committeeships_under_person($person_id)\n{\n global $dbh;\n\n // get person's committeeships (below)\n\n $listing = array();\n\n $query = \"SELECT d.person_id\n FROM\n dissertations d,\n committeeships c\n WHERE\n c.person_id = '\".$person_id.\"' AND\n c.dissertation_id = d.id\n ORDER BY\n d.completedyear\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction set_preferred_name($person_id,$name_id)\n{\n global $dbh;\n\n # delete current family tree of dotgraphs\n delete_associated_dotgraphs($person_id);\n\n # set it\n\n $listing = array();\n\n $before = find_person($person_id);\n\n $query = \"UPDATE people\n SET\n preferred_name_id = '\".$name_id.\"'\n WHERE\n id = '\".$person_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $after = find_person($person_id);\n\n # log it\n mpact_logger(\"set preferred name for person[\".$person_id.\"] from name[\".$before['preferred_name_id'].\"] (\".$before['fullname'].\") to name[\".$name_id.\"] (\".$after['fullname'].\")\");\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_profs_at_dept($school_id,$discipline_id)\n{\n global $dbh;\n\n $dissertations = array();\n $listing = array();\n $advisors = array();\n $committeemembers = array();\n\n // get all dissertations at this dept\n\n $query = \"SELECT d.id\n FROM dissertations d, schools s\n WHERE\n d.school_id = s.id AND\n s.id = '\".$school_id.\"' AND\n d.discipline_id = '\".$discipline_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $dissertations[] = $line['id'];\n }\n\n if (count($dissertations)>0)\n {\n // get all advisors for these dissertations\n\n $query = \"SELECT a.person_id\n FROM dissertations d, advisorships a\n WHERE\n a.dissertation_id IN (\";\n $query .= implode(\", \", $dissertations);\n $query .= \") AND\n a.dissertation_id = d.id\";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $advisors[$line['person_id']] = $line['person_id'];\n }\n\n // get all committeemembers for these dissertations\n\n $query = \"SELECT c.person_id\n FROM dissertations d, committeeships c\n WHERE\n c.dissertation_id IN (\";\n $query .= implode(\", \", $dissertations);\n $query .= \") AND\n c.dissertation_id = d.id\";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $committeemembers[$line['person_id']] = $line['person_id'];\n }\n }\n\n // return the combined list (uniquified when combined)\n\n// echo \"\\na - \".count($advisors);\n// echo \"\\nc - \".count($committeemembers);\n $listing = $advisors + $committeemembers;\n// echo \"\\ncombined before - \".count($listing);\n return $listing;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_profs_at_dept($school_id,$discipline_id)\n{\n global $dbh;\n $query = \"SELECT professors\n FROM profs_at_dept\n WHERE\n school_id = '$school_id' AND\n discipline_id = '$discipline_id'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result))\n {\n $listing = unserialize($line['professors']);\n }\n return $listing;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_disciplines($school_id=null)\n{\n global $dbh;\n\n $disciplines = array();\n if ($school_id)\n {\n // get all disciplines at this school\n $query = \"SELECT d.id, d.title\n FROM\n disciplines d, schools s, dissertations diss\n WHERE\n diss.school_id = s.id AND\n diss.discipline_id = d.id AND\n s.id = '$school_id'\n ORDER BY\n d.title\n \";\n }\n else\n {\n $query = \"SELECT id, title\n FROM\n disciplines d\n ORDER BY\n title\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $disciplines[$line['id']] = $line['title'];\n }\n\n if (isset($disciplines))\n {\n return $disciplines;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction is_duplicate_discipline($title)\n{\n global $dbh;\n $disciplinefound = 0;\n\n $query = \"SELECT id FROM disciplines WHERE title = '$title'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $disciplinefound = $line['id'];\n }\n\n if ($disciplinefound > 0){\n return true;\n }\n\n return false;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_empty_discipline($discipline_id)\n{\n global $dbh;\n $query = \"SELECT count(*) as howmany FROM dissertations WHERE discipline_id = $discipline_id\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n extract($line);\n }\n\n if ($howmany > 0){\n return false;\n }\n\n return true;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_duplicate_school($fullname)\n{\n global $dbh;\n $schoolfound = 0;\n\n $query = \"SELECT id FROM schools WHERE fullname = '$fullname'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $schoolfound = $line['id'];\n }\n\n if ($schoolfound > 0){\n return true;\n }\n\n return false;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_empty_school($school_id)\n{\n global $dbh;\n $query = \"SELECT count(*) as howmany FROM dissertations WHERE school_id = $school_id\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n extract($line);\n }\n\n if ($howmany > 0){\n return false;\n }\n\n return true;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline_counts()\n{\n global $dbh;\n\n // get all discipline counts from the database\n\n $disciplinecounts = array();\n\n $query = \"SELECT discipline_id, count(*) as disciplinecount\n FROM dissertations\n GROUP BY discipline_id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $disciplinecounts[$line['discipline_id']] = $line['disciplinecount'];\n }\n\n if (isset($disciplinecounts))\n {\n return $disciplinecounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline_statuses($discipline_id)\n{\n global $dbh;\n\n // get status counts for this discipline\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n\n $query = \"SELECT status, count(*) as disciplinecount\n FROM dissertations\n WHERE discipline_id='$discipline_id'\n GROUP BY status\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disciplinecount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dept_counts($school_id,$discipline_id)\n{\n global $dbh;\n\n // get all department counts from the database\n\n $deptcounts = array();\n\n $query = \"SELECT discipline_id, count(*) as disciplinecount\n FROM dissertations\n GROUP BY discipline_id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $deptcounts[$line['discipline_id']] = $line['disciplinecount'];\n }\n\n if (isset($deptcounts))\n {\n return $deptcounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dept_statuses($school_id,$discipline_id)\n{\n global $dbh;\n\n // get status counts for this school in this discipline\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n\n $query = \"SELECT status, count(*) as disciplinecount\n FROM dissertations\n WHERE\n discipline_id='$discipline_id' AND\n school_id='$school_id'\n GROUP BY status\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disciplinecount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_schools($discipline_id=null)\n{\n global $dbh;\n // get all schools in a discipline (or all disciplines)\n $schools = array();\n if ($discipline_id)\n {\n // look up schools at dissertations in this discipline\n $query = \"SELECT s.id, s.fullname\n FROM\n dissertations d, schools s\n WHERE\n d.school_id = s.id AND\n d.discipline_id = '$discipline_id'\n GROUP BY\n d.school_id\n ORDER BY\n s.fullname ASC\n \";\n }\n else\n {\n $query = \"SELECT id, fullname\n FROM\n schools s\n ORDER BY fullname\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result))\n {\n $schools[$line['id']] = $line['fullname'];\n }\n\n if (isset($schools))\n {\n return $schools;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school_counts()\n{\n global $dbh;\n\n // get all school dissertation counts from the database\n\n $schoolcounts = array();\n\n $query = \"SELECT school_id, count(*) as disscount\n FROM dissertations\n GROUP BY school_id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $schoolcounts[$line['school_id']] = $line['disscount'];\n }\n\n if (isset($schoolcounts))\n {\n return $schoolcounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school_statuses($school_id)\n{\n global $dbh;\n\n // get status counts for this school\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n\n $query = \"SELECT status, count(*) as disscount\n FROM dissertations\n WHERE school_id='$school_id'\n GROUP BY status\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disscount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction find_persons_school($passed_person)\n{\n global $dbh;\n\n // get person's degree school\n\n $query = \"SELECT\n d.id as dissertation_id,\n d.completedyear,\n d.title,\n d.abstract,\n s.fullname,\n s.country,\n s.id as schoolid\n FROM\n dissertations d,\n schools s\n WHERE\n d.person_id = \".$passed_person.\" AND\n d.school_id = s.id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $thisperson['dissertation_id'] = $line['dissertation_id'];\n $thisperson['completedyear'] = $line['completedyear'];\n $thisperson['title'] = $line['title'];\n $thisperson['abstract'] = $line['abstract'];\n $thisperson['country'] = $line['country'];\n $thisperson['school'] = $line['fullname'];\n $thisperson['schoolid'] = $line['schoolid'];\n }\n\n if (isset($thisperson))\n {\n return $thisperson;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school($school_id)\n{\n global $dbh;\n\n // get school\n\n $query = \"SELECT\n s.fullname,\n s.country\n FROM\n schools s\n WHERE\n s.id = \".$school_id.\"\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $school['country'] = $line['country'];\n $school['fullname'] = $line['fullname'];\n }\n\n if (isset($school))\n {\n return $school;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction get_environment_info()\n{\n $host_info = array();\n $hostname = $_SERVER['SERVER_NAME'];\n if ($hostname == \"\"){$hostname = exec(hostname);}\n# echo \"hostname = [$hostname]
\";\n if ($hostname == \"www.ibiblio.org\" || $hostname == \"www-dev.ibiblio.org\" || $hostname == \"login1.ibiblio.org\")\n {\n # the main install on ibiblio\n $host_info['hostname'] = \"ibiblio\";\n $host_info['ownername'] = \"mpact\";\n $host_info['dotlocation'] = \"/export/sunsite/users/mpact/terrelllocal/bin/dot\";\n $host_info['appdir'] = \"/public/html/mpact\";\n $host_info['webdir'] = \"http://www.ibiblio.org/mpact\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"Times-Roman\";\n }\n else if ($hostname == \"trel.dyndns.org\")\n {\n # my local development machine\n $host_info['hostname'] = \"home\";\n $host_info['ownername'] = \"trel\";\n $host_info['dotlocation'] = \"/sw/bin/dot\";\n $host_info['appdir'] = \"/Library/WebServer/Documents/MPACTlocal/app\";\n $host_info['webdir'] = \"http://trel.dyndns.org:9000/mpactlocal/app\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"cour\";\n }\n else if ($hostname == \"localhost.com\" || $hostname == \"trelpancake\")\n {\n # my laptop\n $host_info['hostname'] = \"laptop\";\n $host_info['ownername'] = \"trel\";\n $host_info['dotlocation'] = \"/opt/local/bin/dot\";\n $host_info['appdir'] = \"/Users/trel/Sites/MPACT\";\n $host_info['webdir'] = \"http://localhost.com/~trel/MPACT\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"cour\";\n }\n else\n {\n # unknown host\n #exit;\n }\n\n return $host_info;\n}\n\n# -------------------------------------------------------------------------------\nfunction delete_associated_dotgraphs($passed_person)\n{\n $host_info = get_environment_info();\n $group = array($passed_person);\n $ancestors = find_ancestors_for_group($group);\n $descendents = find_descendents_for_group($group);\n $entire_family_tree = array_unique($ancestors + $descendents);\n foreach ($entire_family_tree as $one)\n {\n # set the filenames\n $dotfilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.dot\";\n $imagefilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.\".$host_info['dotfiletype'];\n $imagemapfilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.map\";\n # delete each if they exist\n if (file_exists($dotfilename))\n {\n `rm $dotfilename`;\n }\n if (file_exists($imagefilename))\n {\n `rm $imagefilename`;\n }\n if (file_exists($imagemapfilename))\n {\n `rm $imagemapfilename`;\n }\n # mark as 'dirty' so cronjob can recreate images\n mark_record_as_dirty($one);\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction mark_record_as_dirty($passed_person)\n{\n global $dbh;\n # mark database record for this person as dirty\n # a cronjob will pick these up and regenerate their dotgraphs\n # gets around permission issues on the server if necessary\n $query = \"UPDATE people SET regenerate_dotgraph = '1' WHERE id = '\".$passed_person.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n}\n\n# -------------------------------------------------------------------------------\nfunction narray_slice($array, $offset, $length) {\n # http://us3.php.net/manual/en/function.array-slice.php#73882\n\n //Check if this version already supports it\n if (str_replace('.', '', PHP_VERSION) >= 502)\n return array_slice($array, $offset, $length, true);\n\n foreach ($array as $key => $value) {\n\n if ($a >= $offset && $a - $offset <= $length)\n $output_array[$key] = $value;\n $a++;\n\n }\n return $output_array;\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_dotfile($passed_person){\n $a = find_person($passed_person);\n if ($a == null)\n {\n return 0;\n }\n else\n {\n $dotfilecontents = \"\";\n $dotfilecontents .= \"digraph familytree\\n\";\n $dotfilecontents .= \"{\\n\";\n $dotfilecontents .= \"rankdir=\\\"LR\\\"\\n\";\n $dotfilecontents .= \"node [fontname = Times, fontsize=10, shape = rect, height=.15]\\n\";\n # ancestors\n $upgroup = array();\n $upgroup[] = $passed_person;\n $ancestors = find_ancestors_for_group($upgroup);\n foreach ($ancestors as $one)\n {\n $person = find_person($one);\n $dotfilecontents .= \"$one [label = \\\"\".$person['fullname'].\"\\\" URL=\\\"mpact.php?op=show_tree&id=\".$one.\"\\\"];\\n\";\n $advisors = find_advisors_for_person($one);\n foreach ($advisors as $adv)\n {\n $dotfilecontents .= \"$adv -> $one;\\n\";\n }\n }\n # descendents\n $downgroup = array();\n $downgroup[] = $passed_person;\n $descendents = find_descendents_for_group($downgroup);\n foreach ($descendents as $one)\n {\n $person = find_person($one);\n $dotfilecontents .= \"$one [label = \\\"\".$person['fullname'].\"\\\" URL=\\\"mpact.php?op=show_tree&id=\".$one.\"\\\"\";\n if ($one == $passed_person){\n $dotfilecontents .= \" color=\\\"red\\\" style=\\\"filled\\\" fillcolor=\\\"grey\\\"\";\n }\n $dotfilecontents .= \"];\\n\";\n $advisees = find_advisorships_under_person($one);\n foreach ($advisees as $adv)\n {\n $dotfilecontents .= \"$one -> $adv;\\n\";\n }\n }\n $dotfilecontents .= \"}\\n\";\n\n return $dotfilecontents;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_tree_dotgraph($passed_person)\n{\n $person = $passed_person;\n $host_info = get_environment_info();\n if (isset($host_info['appdir']))\n {\n $webfilename = generate_dotgraph($person);\n if ($webfilename == \"marked_as_dirty\"){\n echo \"generating graph, please reload\";\n }\n else{\n echo \"\\\"Directed
\";\n }\n }\n else\n {\n echo \"graphics libraries are not configured\";\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_dotgraph($passed_person, $forcenew=\"no\")\n{\n $person = $passed_person;\n $host_info = get_environment_info();\n# print_r($host_info);\n $appcache = $host_info['appdir'].\"/\".$host_info['dotcachedir'];\n $webcache = $host_info['webdir'].\"/\".$host_info['dotcachedir'];\n $appfilename = \"$appcache/$person.\".$host_info['dotfiletype'];\n# echo \"appfilename = $appfilename
\\n\";\n $dotfilename = \"$appcache/$person.dot\";\n# echo \"dotfilename = $dotfilename
\\n\";\n $webfilename = \"$webcache/$person.\".$host_info['dotfiletype'];\n# echo \"webfilename = $webfilename
\\n\";\n $appimagemap = \"$appcache/$person.map\";\n# echo \"appimagemap = $appimagemap
\\n\";\n\n if (!file_exists($appfilename)) {\n # assumption is that the cachedir exists... (run setupmpact.sh)\n # generate dotfile\n if (!file_exists($dotfilename) or $forcenew == \"force\") {\n# print \" - creating dotfile...\\n\";\n $dotfilecontents = generate_dotfile($person);\n $fh = fopen($dotfilename, 'w');\n fwrite($fh, $dotfilecontents);\n fclose($fh);\n exec(\"chmod 666 $dotfilename\");\n }\n # generate graph\n $getandgenerategraph = \"/bin/cat $dotfilename | \".$host_info['dotlocation'].\" -Nfontname=\".$host_info['dotfontface'].\" -Gcharset=latin1 -Tcmapx -o$appimagemap -T\".$host_info['dotfiletype'].\" -o$appfilename 2>&1\";\n# echo \"getandgenerategraph = $getandgenerategraph
\";\n exec($getandgenerategraph);\n exec(\"chmod 666 $appimagemap\");\n exec(\"chmod 666 $appfilename\");\n if (!file_exists($appfilename)) {\n # mark as dirty if it didn't work\n mark_record_as_dirty($person);\n return \"marked_as_dirty\";\n }\n }\n else\n {\n# echo \"SHOWING CACHED COPY
\";\n }\n\n return $webfilename;\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_graph($passed_person)\n{\n if (!$passed_person){action_box(\"No ID given.\");}\n\n $person = $passed_person;\n $host_info = get_environment_info();\n if (isset($host_info['appdir']))\n {\n $appcache = $host_info['appdir'].\"/\".$host_info['dotcachedir'];\n $webcache = $host_info['webdir'].\"/\".$host_info['dotcachedir'];\n $appfilename = \"$appcache/$person.\".$host_info['dotfiletype'];\n #echo \"appfilename = $appfilename
\";\n $webfilename = \"$webcache/$person.\".$host_info['dotfiletype'];\n #echo \"webfilename = $webfilename
\";\n $appimagemap = \"$appcache/$person.map\";\n #echo \"appimagemap = $appimagemap
\";\n\n\n echo \"\";\n echo file_get_contents($appimagemap);\n }\n else\n {\n echo \"graphics libraries are not configured\";\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_tree($passed_person)\n{\n global $dbh;\n GLOBAL $statuscodes;\n GLOBAL $inspectioncodes;\n\n // shows a person\n\n if (!$passed_person){action_box(\"No ID given.\");}\n else\n {\n $personcount = 0;\n $thisperson = array();\n $dissertation = array();\n\n // get person's preferred name\n\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, p.degree\n FROM\n names n, people p\n WHERE\n p.preferred_name_id = n.id AND\n p.id = '\".$passed_person.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $thisperson['firstname'] = $line['firstname'];\n $thisperson['middlename'] = $line['middlename'];\n $thisperson['lastname'] = $line['lastname'];\n $thisperson['suffix'] = $line['suffix'];\n $thisperson['degree'] = $line['degree'];\n $personcount++;\n }\n\n $schoolinfo = find_persons_school($passed_person);\n $thisperson['dissertation_id'] = $schoolinfo['dissertation_id'];\n $thisperson['completedyear'] = $schoolinfo['completedyear'];\n $thisperson['country'] = $schoolinfo['country'];\n $thisperson['school'] = $schoolinfo['school'];\n $thisperson['schoolid'] = $schoolinfo['schoolid'];\n\n if ($thisperson['dissertation_id'] == \"\")\n {\n $thisperson['status'] = \"\";\n $thisperson['notes'] = \"\";\n $thisperson['title'] = \"N/A\";\n $thisperson['abstract'] = \"N/A\";\n $thisperson['abstract_html'] = \"N/A\";\n }\n else\n {\n $dissertation = find_dissertation($thisperson['dissertation_id']);\n $thisperson['status'] = $dissertation['status'];\n $thisperson['notes'] = $dissertation['notes'];\n $thisperson['discipline_id'] = $dissertation['discipline_id'];\n $thisperson['title'] = $dissertation['title'];\n $thisperson['abstract'] = $dissertation['abstract'];\n $thisperson['abstract_html'] = encode_linebreaks($dissertation['abstract']);\n if ($thisperson['title'] == \"\") { $thisperson['title'] = \"N/A\";}\n if ($thisperson['abstract'] == \"\")\n {\n $thisperson['abstract'] = \"N/A\";\n $thisperson['abstract_html'] = \"N/A\";\n }\n }\n\n $thisperson['advisors'] = find_advisors_for_person($passed_person);\n $thisperson['cmembers'] = find_committee_for_person($passed_person);\n $thisperson['advisorships'] = find_advisorships_under_person($passed_person);\n $thisperson['committeeships'] = find_committeeships_under_person($passed_person);\n\n\n if ($personcount < 1)\n {\n action_box(\"Person \".$passed_person.\" Not Found\");\n }\n else\n {\n\n echo \"
\\n\";\n\n # Name / Aliases\n $count = 0;\n $printme = \"\";\n $fullname = $thisperson['firstname'].\" \".$thisperson['middlename'].\" \".$thisperson['lastname'].\" \".$thisperson['suffix'];\n $printme .= \"

Dissertation Information for $fullname

\";\n $printme .= \"

\";\n if (is_admin())\n {\n if (isset($thisperson['completedyear']))\n {\n $printme .= \" (Edit)\";\n }\n else\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n $printme .= \"
\\n\";\n }\n $printme .= \"

\";\n $printme .= \"

\";\n $printme .= \"NAME: \";\n if (is_admin())\n {\n $printme .= \"(Add)\";\n }\n $printme .= \"
\";\n $printme .= \" - \";\n $printme .= get_person_link($passed_person);\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n $printme .= \"
\\n\";\n\n $aliases = 0;\n foreach (find_aliases($passed_person) as $one)\n {\n $printme .= \" - (Alias) \";\n $printme .= $one['firstname'].\" \";\n $printme .= $one['middlename'].\" \";\n $printme .= $one['lastname'].\" \";\n $printme .= $one['suffix'].\" \";\n if (is_admin())\n {\n $printme .= \"(Set as Primary)\";\n $printme .= \" (Delete)\";\n }\n $printme .= \"
\";\n $aliases++;\n }\n $printme .= \"

\";\n echo $printme;\n\n # Degree\n $printme = \"

\\n\";\n $printme .= \"DEGREE:
\\n\";\n $printme .= \" - \".$thisperson['degree'];\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n $printme .= \"

\";\n echo $printme;\n\n # Discipline\n $printme = \"

\\n\";\n $printme .= \"DISCIPLINE:
\\n\";\n if (isset($thisperson['discipline_id']))\n {\n $discipline = find_discipline($thisperson['discipline_id']);\n $printme .= \" - \".$discipline['title'].\"\";\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n }\n else\n {\n $printme .= \" - None\";\n if (is_admin())\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n }\n $printme .= \"

\";\n echo $printme;\n\n # School\n $printme = \"

\\n\";\n $printme .= \"SCHOOL:
\\n\";\n if (isset($thisperson['completedyear']))\n {\n $printme .= \" - \".$thisperson['school'].\" (\".$thisperson['country'].\") (\".$thisperson['completedyear'].\")\";\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n }\n else\n {\n $printme .= \" - None\";\n if (is_admin())\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n }\n $printme .= \"

\\n\";\n echo $printme;\n\n\n # Advisors\n $count = 0;\n $printme = \"\";\n $printme .= \"

\";\n $printme .= \"ADVISORS: \";\n if (is_admin() && isset($thisperson['completedyear']))\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
\";\n if (isset($thisperson['advisors'])){\n foreach ($thisperson['advisors'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
\";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

\";\n echo $printme;\n\n # Committee Members\n $count = 0;\n $printme = \"\";\n $printme .= \"

\";\n $printme .= \"COMMITTEE MEMBERS: \";\n if (is_admin() && isset($thisperson['completedyear']))\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
\";\n if (isset($thisperson['cmembers'])){\n foreach ($thisperson['cmembers'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
\";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

\\n\\n\";\n\n # Admin Notes\n if (is_admin())\n {\n if ($thisperson['notes'] != \"\")\n {\n $printme .= \"

\";\n $printme .= \"\\n\";\n $printme .= \"\\n\";\n $printme .= \"
\\n\";\n $printme .= \"Admin Notes: \".$thisperson['notes'].\"
\\n\";\n $printme .= \"
\\n\";\n $printme .= \"

\\n\\n\";\n }\n }\n\n $glossaryterms = find_glossaryterms();\n # Status and Inspection\n $printme .= \"

\";\n $printme .= \"MPACT Status: \".$statuscodes[$thisperson['status']].\"
\\n\";\n $printme .= \"

\\n\\n\";\n\n # Title and Abstract\n $printme .= \"

\";\n $printme .= \"Title: \".$thisperson['title'].\"
\";\n $printme .= \"

\\n\";\n $printme .= \"

\";\n $printme .= \"Abstract: \".$thisperson['abstract_html'].\"
\";\n $printme .= \"

\\n\\n\";\n\n # print it all out...\n echo $printme;\n\n # URLS\n\n if (is_admin())\n {\n $urls = find_urls_by_person($passed_person);\n echo \"

\\n\";\n echo \"REFERENCE URLS\";\n echo \" (Add)\";\n echo \"
\\n\";\n if (count($urls) > 0)\n {\n echo \"\\n\";\n }\n else\n {\n echo \" - None\\n\";\n }\n foreach ($urls as $one)\n {\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n }\n if (count($urls) > 0)\n {\n echo \"
Updated: \".$one['updated_at'].\"\";\n echo \" (Edit)\";\n echo \" (Delete)\";\n echo \"
\".$one['url'].\"
\".$one['description'].\"
\\n\";\n }\n echo \"

\\n\";\n }\n\n # EDIT HISTORY\n\n if (is_admin())\n {\n $entries = get_dissertation_history($thisperson['dissertation_id']);\n if (count($entries) > 0)\n {\n echo \"

\\n\";\n echo \"EDIT HISTORY (Show/Hide)\\n\";\n echo \"\";\n echo \"\\n\";\n }\n\n foreach ($entries as $one)\n {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n if (count($entries) > 0)\n {\n echo \"
\".$one['logged_at'].\"\".$one['user'].\"\".$one['message'].\"
\\n\";\n echo \"

\\n\";\n }\n }\n\n\n\n echo \"
\\n\";\n\n # MPACT Scores\n $printme = \"\";\n $printme .= \"

MPACT Scores for $fullname

\";\n $printme .= \"

\";\n $mpact = mpact_scores($passed_person);\n $printme .= $mpact['output'];\n $printme .= \"

\\n\";\n if (is_admin())\n {\n $printme .= \"

(Recalculate)

\";\n }\n echo $printme;\n\n # Draw FamilyTree Graph for this person\n echo \"

Advisors and Advisees Graph

\\n\";\n echo \"

\";\n draw_tree_dotgraph($passed_person);\n echo \"

\";\n\n echo \"
\\n\";\n\n\n # Students\n echo \"

Students under $fullname

\\n\\n\";\n\n # Advisees\n $count = 0;\n $printme = \"\";\n $printme .= \"

\";\n $printme .= \"ADVISEES: \";\n if (is_admin())\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
\";\n if (isset($thisperson['advisorships'])){\n foreach ($thisperson['advisorships'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n $schoolinfo = find_persons_school($one);\n if (isset($schoolinfo['completedyear']))\n {\n $printme .= \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
\";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

\\n\";\n echo $printme;\n\n # Committeeships\n $ccount = 0;\n $printme = \"\";\n $printme .= \"

\";\n $printme .= \"COMMITTEESHIPS: \";\n if (is_admin())\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
\";\n if (isset($thisperson['committeeships'])){\n foreach ($thisperson['committeeships'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n $schoolinfo = find_persons_school($one);\n if (isset($schoolinfo['completedyear']))\n {\n $printme .= \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
\";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

\";\n echo $printme;\n\n }\n\n }\n\n\n}\n\n\n?>\n"}} -{"repo": "trac-hacks/trac-dashboard", "pr_number": 2, "title": "Unpack one-element tuple correctly", "state": "closed", "merged_at": "2016-08-27T20:14:18Z", "additions": 2, "deletions": 2, "files_changed": ["dashboard/dashboard.py"], "files_before": {"dashboard/dashboard.py": "from trac.core import *\nfrom pkg_resources import resource_filename\nfrom trac.config import Option, IntOption, ListOption, BoolOption\nfrom trac.web.api import IRequestHandler, Href\nfrom trac.util.translation import _\nfrom trac.web.chrome import add_stylesheet, add_script, INavigationContributor, ITemplateProvider\nfrom trac.web.chrome import Chrome\nfrom trac.util.datefmt import utc, to_timestamp\nfrom genshi.template import TemplateLoader\nfrom genshi.filters.transform import Transformer\nfrom trac.web.api import ITemplateStreamFilter\nfrom trac.perm import IPermissionRequestor\nfrom trac.util import escape, Markup\n\nimport time\nfrom datetime import datetime, timedelta\n\n\n\n\nclass DashBoard(Component):\n implements(IRequestHandler, ITemplateProvider, IPermissionRequestor, INavigationContributor)\n \n permission = Option('dashboard', 'permission', '')\n default_milestone = Option('dashboard', 'default_milestone', '')\n\n def __init__(self):\n self.db = self.env.get_db_cnx()\n self.username = None\n self.backDate = 30\n self.ticket_closed = ['checkedin', 'closed']\n\n self.ticket_closed_sql = \"','\".join(self.ticket_closed)\n\n self.milestone = self.default_milestone\n \n if self.permission:\n self.perm = self.permission\n else:\n self.perm = 'DASHBOARD_VIEW'\n\n self.env.log.debug(\"Using Permission: %s\" % self.permission)\n\n \n # INavigationContributor methods\n def get_active_navigation_item(self, req):\n return 'dashboard'\n\n def get_navigation_items(self, req):\n if self.perm in req.perm or 'TRAC_ADMIN' in req.perm:\n yield 'mainnav', 'dashboard', Markup('Dashboard' % (\n self.env.href.dashboard() ) )\n\n\n\n def get_permission_actions(self):\n yield self.perm\n\n \n # IRequestHandler methods\n def match_request(self, req):\n serve = False\n self.env.log.debug(\"Match Request\")\n\n\n uri = req.path_info.lstrip('/').split('/')\n if uri[0] == 'dashboard':\n serve = True\n\n self.env.log.debug(\"Handle Request: %s\" % serve)\n self.baseURL = req.href('dashboard', '/')\n self.baseQueryURL = req.href('query', '/')\n self.username = req.authname\n if 'milestone' in req.args:\n self.milestone = req.args.get('milestone')\n else:\n self.milestone = self.default_milestone\n\n if self.milestone == '':\n cursor = self.db.cursor()\n sql = \"select name from milestone where (completed = 0) limit 0, 1\"\n cursor.execute(sql)\n for name in cursor:\n self.milestone = name\n\n if 'dev' in req.args:\n self.username = req.args.get('dev')\n else:\n self.username = req.authname\n\n return serve\n\n if not self.perm in req.perm:\n self.env.log.debug(\"NO Permission to view\")\n return False\n\n return serve\n \n def get_updated_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status from ticket where (owner = '%s') and (changetime >= %s) and (status not in ('%s', 'new')) order by changetime desc\" % (self.username, self.stamp, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_new_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, status, component, summary, changetime, priority from ticket where (owner = '%s') and (status in ('new', 'assigned')) and (type = 'defect') order by changetime desc\" % self.username\n cursor.execute(sql)\n out = []\n idx = 0\n for id, status, component, summary, changetime, priority in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'status': status,\n 'component': component,\n 'summary': summary,\n 'priority': priority,\n 'changetime': datetime.fromtimestamp(changetime, utc)\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_closed_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, changetime, status from ticket where (owner = '%s') and (status in ('%s')) and (changetime >= %s) order by component, status, changetime desc\" % (self.username, self.ticket_closed_sql, self.stamp)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, changetime, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status,\n 'changetime': datetime.fromtimestamp(changetime, utc)\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_milestone_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status, priority from ticket where (owner = '%s') and (status not in ('%s', 'new')) and (type in ('defect', 'enhancement')) and (milestone = '%s') order by component, priority\" % (self.username, self.ticket_closed_sql, self.milestone)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status, priority in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status,\n 'priority': priority\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_todo_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status from ticket where (owner = '%s') and (status not in ('%s')) and (type = 'task') order by changetime desc\" % (self.username, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_ticket_counts(self):\n cursor = self.db.cursor()\n sql = \"select count(*) as total, type, status from ticket where (owner = '%s') and (status not in ('%s')) group by type, status order by total desc\" % (self.username, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for total, type, status in cursor:\n data = {\n '__idx__': idx,\n 'total': total,\n 'status': status,\n 'type': type\n }\n idx = idx + 1\n out.append(data)\n\n return out\n\n def get_action_counts(self):\n cursor = self.db.cursor()\n #sql = \"select count(*) as total, concat(oldvalue, ' => ', newvalue) as status from ticket_change where (author = '%s') and (time > %s) and (field = 'status') group by status order by total desc\" % (self.username, self.stamp)\n sql = \"select count(*) as total, (%s) as status from ticket_change where (author = '%s') and (time > %s) and (field = 'status') group by status order by total desc\" % (self.db.concat('oldvalue', \"' => '\", 'newvalue'), self.username, self.stamp)\n cursor.execute(sql)\n \n out = []\n idx = 0\n for total, status in cursor:\n data = {\n '__idx__': idx,\n 'total': total,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n\n return out\n\n\n def get_milestone_data(self):\n cursor = self.db.cursor()\n out = {\n 'total': 0,\n 'closed': 0,\n 'closed_percent': 0,\n 'new': 0,\n 'new_percent': 0,\n 'inprogress': 0,\n 'inprogress_percent': 0,\n 'name': self.milestone\n }\n #sql = \"select count(*) as total, ticket.status from ticket, ticket_custom where (ticket.milestone = '%s') and (ticket.owner = '%s') and (ticket.id = ticket_custom.ticket) and (ticket_custom.name = 'location') and (ticket_custom.value = 'Library Code')\" % (self.milestone, self.username)\n sql = \"select count(*) as total, status from ticket where (milestone = '%s') and (owner = '%s') and (type = 'defect') group by status\" % (self.milestone, self.username)\n cursor.execute(sql)\n\n for total, status in cursor:\n out['total'] = out['total'] + total\n\n if status in self.ticket_closed:\n out['closed'] = out['closed'] + total\n elif status == 'new':\n out['new'] = out['new'] + total\n else:\n out['inprogress'] = out['inprogress'] + total\n\n if out['closed'] > 0:\n out['closed_percent'] = int(round((float(out['closed']) / out['total']), 3) * 100)\n\n if out['new'] > 0:\n out['new_percent'] = int(round((float(out['new']) / out['total']), 1) * 100)\n\n if out['inprogress'] > 0:\n out['inprogress_percent'] = int(round((float(out['inprogress']) / out['total']), 3) * 100)\n\n\n return out\n\n def get_milestones(self):\n cursor = self.db.cursor()\n sql = \"select name from milestone where (name not in ('%s')) and (completed = 0)\" % self.milestone\n cursor.execute(sql)\n data = []\n for name in cursor:\n data.append(name)\n\n return data\n\n def get_users(self):\n devs = self.env.get_known_users()\n odevs = []\n for username,name,email in devs:\n if username != self.username:\n data = {\n 'username': username,\n 'name': name or username\n }\n odevs.append(data)\n return odevs\n\n\n def process_request(self, req):\n data = {}\n self.stamp = time.time() - (60 * 60 * 24 * self.backDate)\n today = datetime.now(req.tz)\n\n\n data['backDate'] = self.backDate\n data['stamp'] = self.stamp\n data['username'] = self.username\n data['milestone'] = self.milestone\n\n #Updated Tickets \n data['updated_tickets'] = self.get_updated_tickets()\n data['has_updated_tickets'] = len(data['updated_tickets'])\n\n #New Tickets\n data['new_tickets'] = self.get_new_tickets()\n data['has_new_tickets'] = len(data['new_tickets'])\n\n #Closed Tickets\n data['closed_tickets'] = self.get_closed_tickets()\n data['has_closed_tickets'] = len(data['closed_tickets'])\n\n #Ticket Counts\n data['ticket_counts'] = self.get_ticket_counts()\n data['has_ticket_counts'] = len(data['ticket_counts'])\n\n #Action Counts\n data['action_counts'] = self.get_action_counts()\n data['has_action_counts'] = len(data['action_counts'])\n\n #TODO Lists\n data['todo_tickets'] = self.get_todo_tickets()\n data['has_todo_tickets'] = len(data['todo_tickets'])\n\n #Milestones\n data['milestone_data'] = self.get_milestone_data()\n data['has_milestones'] = len(data['milestone_data'])\n\n #Milestone Tickets\n data['milestone_tickets'] = self.get_milestone_tickets()\n data['has_milestone_tickets'] = len(data['milestone_tickets'])\n\n #Milestones\n data['milestones'] = self.get_milestones()\n\n #Users\n data['users'] = self.get_users()\n\n\n add_script(req, \"dashboard/dashboard.js\")\n add_stylesheet(req, \"dashboard/dashboard.css\")\n return 'dashboard.html', data, None\n\n\n def get_htdocs_dirs(self):\n \"\"\"Return the absolute path of a directory containing additional\n static resources (such as images, style sheets, etc).\n \"\"\"\n return [('dashboard', resource_filename(__name__, 'htdocs'))]\n \n def get_templates_dirs(self):\n \"\"\"Return the absolute path of the directory containing the provided\n genshi templates.\n \"\"\"\n rtn = [resource_filename(__name__, 'templates')]\n return rtn\n"}, "files_after": {"dashboard/dashboard.py": "from trac.core import *\nfrom pkg_resources import resource_filename\nfrom trac.config import Option, IntOption, ListOption, BoolOption\nfrom trac.web.api import IRequestHandler, Href\nfrom trac.util.translation import _\nfrom trac.web.chrome import add_stylesheet, add_script, INavigationContributor, ITemplateProvider\nfrom trac.web.chrome import Chrome\nfrom trac.util.datefmt import utc, to_timestamp\nfrom genshi.template import TemplateLoader\nfrom genshi.filters.transform import Transformer\nfrom trac.web.api import ITemplateStreamFilter\nfrom trac.perm import IPermissionRequestor\nfrom trac.util import escape, Markup\n\nimport time\nfrom datetime import datetime, timedelta\n\n\n\n\nclass DashBoard(Component):\n implements(IRequestHandler, ITemplateProvider, IPermissionRequestor, INavigationContributor)\n \n permission = Option('dashboard', 'permission', '')\n default_milestone = Option('dashboard', 'default_milestone', '')\n\n def __init__(self):\n self.db = self.env.get_db_cnx()\n self.username = None\n self.backDate = 30\n self.ticket_closed = ['checkedin', 'closed']\n\n self.ticket_closed_sql = \"','\".join(self.ticket_closed)\n\n self.milestone = self.default_milestone\n \n if self.permission:\n self.perm = self.permission\n else:\n self.perm = 'DASHBOARD_VIEW'\n\n self.env.log.debug(\"Using Permission: %s\" % self.permission)\n\n \n # INavigationContributor methods\n def get_active_navigation_item(self, req):\n return 'dashboard'\n\n def get_navigation_items(self, req):\n if self.perm in req.perm or 'TRAC_ADMIN' in req.perm:\n yield 'mainnav', 'dashboard', Markup('Dashboard' % (\n self.env.href.dashboard() ) )\n\n\n\n def get_permission_actions(self):\n yield self.perm\n\n \n # IRequestHandler methods\n def match_request(self, req):\n serve = False\n self.env.log.debug(\"Match Request\")\n\n\n uri = req.path_info.lstrip('/').split('/')\n if uri[0] == 'dashboard':\n serve = True\n\n self.env.log.debug(\"Handle Request: %s\" % serve)\n self.baseURL = req.href('dashboard', '/')\n self.baseQueryURL = req.href('query', '/')\n self.username = req.authname\n if 'milestone' in req.args:\n self.milestone = req.args.get('milestone')\n else:\n self.milestone = self.default_milestone\n\n if self.milestone == '':\n cursor = self.db.cursor()\n sql = \"select name from milestone where (completed = 0) limit 0, 1\"\n cursor.execute(sql)\n for name, in cursor:\n self.milestone = name\n\n if 'dev' in req.args:\n self.username = req.args.get('dev')\n else:\n self.username = req.authname\n\n return serve\n\n if not self.perm in req.perm:\n self.env.log.debug(\"NO Permission to view\")\n return False\n\n return serve\n \n def get_updated_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status from ticket where (owner = '%s') and (changetime >= %s) and (status not in ('%s', 'new')) order by changetime desc\" % (self.username, self.stamp, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_new_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, status, component, summary, changetime, priority from ticket where (owner = '%s') and (status in ('new', 'assigned')) and (type = 'defect') order by changetime desc\" % self.username\n cursor.execute(sql)\n out = []\n idx = 0\n for id, status, component, summary, changetime, priority in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'status': status,\n 'component': component,\n 'summary': summary,\n 'priority': priority,\n 'changetime': datetime.fromtimestamp(changetime, utc)\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_closed_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, changetime, status from ticket where (owner = '%s') and (status in ('%s')) and (changetime >= %s) order by component, status, changetime desc\" % (self.username, self.ticket_closed_sql, self.stamp)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, changetime, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status,\n 'changetime': datetime.fromtimestamp(changetime, utc)\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_milestone_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status, priority from ticket where (owner = '%s') and (status not in ('%s', 'new')) and (type in ('defect', 'enhancement')) and (milestone = '%s') order by component, priority\" % (self.username, self.ticket_closed_sql, self.milestone)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status, priority in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status,\n 'priority': priority\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_todo_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status from ticket where (owner = '%s') and (status not in ('%s')) and (type = 'task') order by changetime desc\" % (self.username, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_ticket_counts(self):\n cursor = self.db.cursor()\n sql = \"select count(*) as total, type, status from ticket where (owner = '%s') and (status not in ('%s')) group by type, status order by total desc\" % (self.username, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for total, type, status in cursor:\n data = {\n '__idx__': idx,\n 'total': total,\n 'status': status,\n 'type': type\n }\n idx = idx + 1\n out.append(data)\n\n return out\n\n def get_action_counts(self):\n cursor = self.db.cursor()\n #sql = \"select count(*) as total, concat(oldvalue, ' => ', newvalue) as status from ticket_change where (author = '%s') and (time > %s) and (field = 'status') group by status order by total desc\" % (self.username, self.stamp)\n sql = \"select count(*) as total, (%s) as status from ticket_change where (author = '%s') and (time > %s) and (field = 'status') group by status order by total desc\" % (self.db.concat('oldvalue', \"' => '\", 'newvalue'), self.username, self.stamp)\n cursor.execute(sql)\n \n out = []\n idx = 0\n for total, status in cursor:\n data = {\n '__idx__': idx,\n 'total': total,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n\n return out\n\n\n def get_milestone_data(self):\n cursor = self.db.cursor()\n out = {\n 'total': 0,\n 'closed': 0,\n 'closed_percent': 0,\n 'new': 0,\n 'new_percent': 0,\n 'inprogress': 0,\n 'inprogress_percent': 0,\n 'name': self.milestone\n }\n #sql = \"select count(*) as total, ticket.status from ticket, ticket_custom where (ticket.milestone = '%s') and (ticket.owner = '%s') and (ticket.id = ticket_custom.ticket) and (ticket_custom.name = 'location') and (ticket_custom.value = 'Library Code')\" % (self.milestone, self.username)\n sql = \"select count(*) as total, status from ticket where (milestone = '%s') and (owner = '%s') and (type = 'defect') group by status\" % (self.milestone, self.username)\n cursor.execute(sql)\n\n for total, status in cursor:\n out['total'] = out['total'] + total\n\n if status in self.ticket_closed:\n out['closed'] = out['closed'] + total\n elif status == 'new':\n out['new'] = out['new'] + total\n else:\n out['inprogress'] = out['inprogress'] + total\n\n if out['closed'] > 0:\n out['closed_percent'] = int(round((float(out['closed']) / out['total']), 3) * 100)\n\n if out['new'] > 0:\n out['new_percent'] = int(round((float(out['new']) / out['total']), 1) * 100)\n\n if out['inprogress'] > 0:\n out['inprogress_percent'] = int(round((float(out['inprogress']) / out['total']), 3) * 100)\n\n\n return out\n\n def get_milestones(self):\n cursor = self.db.cursor()\n sql = \"select name from milestone where (name not in ('%s')) and (completed = 0)\" % self.milestone\n cursor.execute(sql)\n data = []\n for name, in cursor:\n data.append(name)\n\n return data\n\n def get_users(self):\n devs = self.env.get_known_users()\n odevs = []\n for username,name,email in devs:\n if username != self.username:\n data = {\n 'username': username,\n 'name': name or username\n }\n odevs.append(data)\n return odevs\n\n\n def process_request(self, req):\n data = {}\n self.stamp = time.time() - (60 * 60 * 24 * self.backDate)\n today = datetime.now(req.tz)\n\n\n data['backDate'] = self.backDate\n data['stamp'] = self.stamp\n data['username'] = self.username\n data['milestone'] = self.milestone\n\n #Updated Tickets \n data['updated_tickets'] = self.get_updated_tickets()\n data['has_updated_tickets'] = len(data['updated_tickets'])\n\n #New Tickets\n data['new_tickets'] = self.get_new_tickets()\n data['has_new_tickets'] = len(data['new_tickets'])\n\n #Closed Tickets\n data['closed_tickets'] = self.get_closed_tickets()\n data['has_closed_tickets'] = len(data['closed_tickets'])\n\n #Ticket Counts\n data['ticket_counts'] = self.get_ticket_counts()\n data['has_ticket_counts'] = len(data['ticket_counts'])\n\n #Action Counts\n data['action_counts'] = self.get_action_counts()\n data['has_action_counts'] = len(data['action_counts'])\n\n #TODO Lists\n data['todo_tickets'] = self.get_todo_tickets()\n data['has_todo_tickets'] = len(data['todo_tickets'])\n\n #Milestones\n data['milestone_data'] = self.get_milestone_data()\n data['has_milestones'] = len(data['milestone_data'])\n\n #Milestone Tickets\n data['milestone_tickets'] = self.get_milestone_tickets()\n data['has_milestone_tickets'] = len(data['milestone_tickets'])\n\n #Milestones\n data['milestones'] = self.get_milestones()\n\n #Users\n data['users'] = self.get_users()\n\n\n add_script(req, \"dashboard/dashboard.js\")\n add_stylesheet(req, \"dashboard/dashboard.css\")\n return 'dashboard.html', data, None\n\n\n def get_htdocs_dirs(self):\n \"\"\"Return the absolute path of a directory containing additional\n static resources (such as images, style sheets, etc).\n \"\"\"\n return [('dashboard', resource_filename(__name__, 'htdocs'))]\n \n def get_templates_dirs(self):\n \"\"\"Return the absolute path of the directory containing the provided\n genshi templates.\n \"\"\"\n rtn = [resource_filename(__name__, 'templates')]\n return rtn\n"}} -{"repo": "lowendbox/lowendscript", "pr_number": 12, "title": "Added functionality for Drupal installation, made readme file, and fixed some bugs.", "state": "open", "merged_at": null, "additions": 524, "deletions": 24, "files_changed": ["setup-debian.sh"], "files_before": {"setup-debian.sh": "#!/bin/bash\n\nfunction check_install {\n if [ -z \"`which \"$1\" 2>/dev/null`\" ]\n then\n executable=$1\n shift\n while [ -n \"$1\" ]\n do\n DEBIAN_FRONTEND=noninteractive apt-get -q -y install \"$1\"\n print_info \"$1 installed for $executable\"\n shift\n done\n else\n print_warn \"$2 already installed\"\n fi\n}\n\nfunction check_remove {\n if [ -n \"`which \"$1\" 2>/dev/null`\" ]\n then\n DEBIAN_FRONTEND=noninteractive apt-get -q -y remove --purge \"$2\"\n print_info \"$2 removed\"\n else\n print_warn \"$2 is not installed\"\n fi\n}\n\nfunction check_sanity {\n # Do some sanity checking.\n if [ $(/usr/bin/id -u) != \"0\" ]\n then\n die 'Must be run by root user'\n fi\n\n if [ ! -f /etc/debian_version ]\n then\n die \"Distribution is not supported\"\n fi\n}\n\nfunction die {\n echo \"ERROR: $1\" > /dev/null 1>&2\n exit 1\n}\n\nfunction get_domain_name() {\n # Getting rid of the lowest part.\n domain=${1%.*}\n lowest=`expr \"$domain\" : '.*\\.\\([a-z][a-z]*\\)'`\n case \"$lowest\" in\n com|net|org|gov|edu|co)\n domain=${domain%.*}\n ;;\n esac\n lowest=`expr \"$domain\" : '.*\\.\\([a-z][a-z]*\\)'`\n [ -z \"$lowest\" ] && echo \"$domain\" || echo \"$lowest\"\n}\n\nfunction get_password() {\n # Check whether our local salt is present.\n SALT=/var/lib/radom_salt\n if [ ! -f \"$SALT\" ]\n then\n head -c 512 /dev/urandom > \"$SALT\"\n chmod 400 \"$SALT\"\n fi\n password=`(cat \"$SALT\"; echo $1) | md5sum | base64`\n echo ${password:0:13}\n}\n\nfunction install_dash {\n check_install dash dash\n rm -f /bin/sh\n ln -s dash /bin/sh\n}\n\nfunction install_dropbear {\n check_install dropbear dropbear\n check_install /usr/sbin/xinetd xinetd\n\n # Disable SSH\n touch /etc/ssh/sshd_not_to_be_run\n invoke-rc.d ssh stop\n\n # Enable dropbear to start. We are going to use xinetd as it is just\n # easier to configure and might be used for other things.\n cat > /etc/xinetd.d/dropbear < /etc/mysql/conf.d/lowendbox.cnf < ~/.my.cnf < /etc/nginx/conf.d/lowendbox.conf < /etc/init.d/php-cgi <&2\n exit 1\n ;;\nesac\nexit 0\nEND\n chmod 755 /etc/init.d/php-cgi\n mkdir -p /var/run/www\n chown www-data:www-data /var/run/www\n\n cat > /etc/nginx/fastcgi_php < /etc/syslog.conf < /etc/logrotate.d/inetutils-syslogd </dev/null\n endscript\n}\nEND\n\n invoke-rc.d inetutils-syslogd start\n}\n\nfunction install_wordpress {\n check_install wget wget\n if [ -z \"$1\" ]\n then\n die \"Usage: `basename $0` wordpress \"\n fi\n\n # Downloading the WordPress' latest and greatest distribution.\n mkdir /tmp/wordpress.$$\n wget -O - http://wordpress.org/latest.tar.gz | \\\n tar zxf - -C /tmp/wordpress.$$\n mv /tmp/wordpress.$$/wordpress \"/var/www/$1\"\n rm -rf /tmp/wordpress.$$\n chown root:root -R \"/var/www/$1\"\n\n # Setting up the MySQL database\n dbname=`echo $1 | tr . _`\n userid=`get_domain_name $1`\n # MySQL userid cannot be more than 15 characters long\n userid=\"${userid:0:15}\"\n passwd=`get_password \"$userid@mysql\"`\n cp \"/var/www/$1/wp-config-sample.php\" \"/var/www/$1/wp-config.php\"\n sed -i \"s/database_name_here/$dbname/; s/username_here/$userid/; s/password_here/$passwd/\" \\\n \"/var/www/$1/wp-config.php\"\n mysqladmin create \"$dbname\"\n echo \"GRANT ALL PRIVILEGES ON \\`$dbname\\`.* TO \\`$userid\\`@localhost IDENTIFIED BY '$passwd';\" | \\\n mysql\n\n # Setting up Nginx mapping\n cat > \"/etc/nginx/sites-enabled/$1.conf\" <&2\n exit 1\nfi\n\nfunction check_install {\n if [ -z \"`which \"$1\" 2>/dev/null`\" ]\n then\n executable=$1\n shift\n while [ -n \"$1\" ]\n do\n DEBIAN_FRONTEND=noninteractive apt-get -q -y install \"$1\"\n print_info \"$1 installed for $executable\"\n shift\n done\n else\n print_warn \"$2 already installed\"\n fi\n}\n\nfunction check_remove {\n if [ -n \"`which \"$1\" 2>/dev/null`\" ]\n then\n DEBIAN_FRONTEND=noninteractive apt-get -q -y remove --purge \"$2\"\n print_info \"$2 removed\"\n else\n print_warn \"$2 is not installed\"\n fi\n}\n\nfunction check_sanity {\n # Do some sanity checking.\n if [ $(/usr/bin/id -u) != \"0\" ]\n then\n die 'Must be run by root user'\n fi\n\n if [ ! -f /etc/debian_version ]\n then\n die \"Distribution is not supported\"\n fi\n}\n\nfunction die {\n echo \"ERROR: $1\" > /dev/null 1>&2\n exit 1\n}\n\nfunction get_domain_name() {\n # Getting rid of the lowest part.\n domain=${1%.*}\n lowest=`expr \"$domain\" : '.*\\.\\([a-z][a-z]*\\)'`\n case \"$lowest\" in\n com|net|org|gov|edu|co)\n domain=${domain%.*}\n ;;\n esac\n lowest=`expr \"$domain\" : '.*\\.\\([a-z][a-z]*\\)'`\n [ -z \"$lowest\" ] && echo \"$domain\" || echo \"$lowest\"\n}\n\nfunction get_password() {\n # Check whether our local salt is present.\n SALT=/var/lib/radom_salt\n if [ ! -f \"$SALT\" ]\n then\n head -c 512 /dev/urandom > \"$SALT\"\n chmod 400 \"$SALT\"\n fi\n password=`(cat \"$SALT\"; echo $1) | md5sum | base64`\n echo ${password:0:13}\n}\n\nfunction install_dash {\n check_install dash dash\n rm -f /bin/sh\n ln -s dash /bin/sh\n}\n\nfunction install_htop {\n check_install htop htop\n}\n\nfunction install_smart {\n\tcheck_install smartmontools smartmontools\n}\n\nfunction install_locate {\n check_install locate locate\n}\n\nfunction fix_locale {\n dpkg-reconfigure locales\n}\n\nfunction var_www {\n mkdir -p /var/www/\n}\n\nfunction install_dropbear {\n check_install dropbear dropbear\n check_install /usr/sbin/xinetd xinetd\n\n # Disable SSH\n touch /etc/ssh/sshd_not_to_be_run\n invoke-rc.d ssh stop\n\n # Enable dropbear to start. We are going to use xinetd as it is just\n # easier to configure and might be used for other things.\n cat > /etc/xinetd.d/dropbear < /etc/mysql/conf.d/lowendbox.cnf < ~/.my.cnf < /etc/nginx/conf.d/lowendbox.conf < /etc/init.d/php-cgi <&2\n exit 1\n ;;\nesac\nexit 0\nEND\n chmod 755 /etc/init.d/php-cgi\n mkdir -p /var/lib/www\n chown www-data:www-data /var/lib/www\n\n cat > /etc/nginx/fastcgi_php < /etc/syslog.conf < /etc/logrotate.d/inetutils-syslogd </dev/null\n endscript\n}\nEND\n\n invoke-rc.d inetutils-syslogd start\n}\n\nfunction install_wordpress {\n# Needs fixing, soon!!!\n check_install wget wget\n if [ -z \"$1\" ]\n then\n die \"Usage: `basename $0` wordpress \"\n fi\n\n # Downloading the WordPress' latest and greatest distribution.\n mkdir /tmp/wordpress.$$\n wget -O - http://wordpress.org/latest.tar.gz | \\\n tar zxf - -C /tmp/wordpress.$$\n\tmkdir -p /var/www/$1\n mv /tmp/wordpress.$$/wordpress/* \"/var/www/$1\"\n rm -rf /tmp/wordpress.$$\n chown root:root -R \"/var/www/$1\"\n\n # Setting up the MySQL database\n dbname=`echo $1 | tr . _`\n\techo Database Name = 'echo $1 | tr . _'\n userid=`get_domain_name $1`\n # MySQL userid cannot be more than 15 characters long\n userid=\"${userid:0:15}\"\n passwd=`get_password \"$userid@mysql\"`\n cp \"/var/www/$1/wp-config-sample.php\" \"/var/www/$1/wp-config.php\"\n sed -i \"s/database_name_here/$dbname/; s/username_here/$userid/; s/password_here/$passwd/\" \\\n \"/var/www/$1/wp-config.php\"\n mysqladmin create \"$dbname\"\n echo \"GRANT ALL PRIVILEGES ON \\`$dbname\\`.* TO \\`$userid\\`@localhost IDENTIFIED BY '$passwd';\" | \\\n mysql\n\n # Setting up Nginx mapping\n cat > \"/etc/nginx/sites-enabled/$1.conf\" < \"/usr/share/nginx/www/$1/index.html\" < \"/etc/nginx/sites-enabled/$1.conf\" <\"\n fi\n\t\n\t#Download PHP5-gd package\n\tapt-get -q -y install php5-gd\n /etc/init.d/php-cgi restart\n\t\n # Downloading the Drupal' latest and greatest distribution.\n mkdir /tmp/drupal.$$\n wget -O - http://ftp.drupal.org/files/projects/drupal-6.30.tar.gz | \\\n tar zxf - -C /tmp/drupal.$$/\n mkdir -p /var/www/$1\n cp -Rf /tmp/drupal.$$/drupal*/* \"/var/www/$1\"\n rm -rf /tmp/drupal*\n chown root:root -R \"/var/www/$1\"\n\n # Setting up the MySQL database\n dbname=`echo $1 | tr . _`\n\t\n\t# MySQL dbname cannot be more than 15 characters long\n dbname=\"${dbname:0:15}\"\n \n\tuserid=`get_domain_name $1`\n \n\t# MySQL userid cannot be more than 15 characters long\n userid=\"${userid:0:15}\"\n passwd=`get_password \"$userid@mysql\"`\n cp \"/var/www/$1/sites/default/default.settings.php\" \"/var/www/$1/sites/default/settings.php\"\n\tchmod 777 /var/www/$1/sites/default/settings.php\n\tmkdir /var/www/$1/sites/default/files\n\tchmod -R 777 /var/www/$1/sites/default/files\n mysqladmin create \"$dbname\"\n echo \"GRANT ALL PRIVILEGES ON \\`$dbname\\`.* TO \\`$userid\\`@localhost IDENTIFIED BY '$passwd';\" | \\\n mysql\n\n\t#Copy DB Name, User, and Pass to settings.php and set to read only.\n\tsed -i \"91 s/username/$userid/; 91 s/password/$passwd/; 91 s/databasename/$dbname/\" \"/var/www/$1/sites/default/settings.php\"\n\tchmod 644 /var/www/$1/sites/default/settings.php\n \n\t# Setting up Nginx mapping\n cat > \"/etc/nginx/sites-enabled/$1.conf\" <\"\n fi\n\t\n\t#Download PHP5-gd package\n\tapt-get -q -y install php5-gd\n /etc/init.d/php-cgi restart\n\t\n # Downloading the Drupal' latest and greatest distribution.\n mkdir /tmp/drupal.$$\n wget -O - http://ftp.drupal.org/files/projects/drupal-7.26.tar.gz | \\\n tar zxf - -C /tmp/drupal.$$/\n mkdir -p /var/www/$1\n cp -Rf /tmp/drupal.$$/drupal*/* \"/var/www/$1\"\n rm -rf /tmp/drupal*\n chown root:root -R \"/var/www/$1\"\n\n # Setting up the MySQL database\n dbname=`echo $1 | tr . _`\n\t\n\t# MySQL dbname cannot be more than 15 characters long\n dbname=\"${dbname:0:15}\"\n\t\n userid=`get_domain_name $1`\n\t\n # MySQL userid cannot be more than 15 characters long\n userid=\"${userid:0:15}\"\n passwd=`get_password \"$userid@mysql\"`\n\t\n\t# Copy default.settings.php to settings.php and set write permissions.\n cp \"/var/www/$1/sites/default/default.settings.php\" \"/var/www/$1/sites/default/settings.php\"\n\tchmod 777 /var/www/$1/sites/default/settings.php\n\tmkdir /var/www/$1/sites/default/files\n\tchmod -R 777 /var/www/$1/sites/default/files\n \n\t# Create MySQL database\n\tmysqladmin create \"$dbname\"\n echo \"GRANT ALL PRIVILEGES ON \\`$dbname\\`.* TO \\`$userid\\`@localhost IDENTIFIED BY '$passwd';\" | \\\n mysql\n\t\t\n #Copy DB Name, User, and Pass to settings.php and set to read only.\n echo \"\\$databases['default']['default'] = array(\" >> /var/www/$1/sites/default/settings.php\n echo \"'driver' => 'mysql',\" >> /var/www/$1/sites/default/settings.php\n echo \"'database' => '$dbname',\" >> /var/www/$1/sites/default/settings.php\n echo \"'username' => '$userid',\" >> /var/www/$1/sites/default/settings.php\n echo \"'password' => '$passwd',\" >> /var/www/$1/sites/default/settings.php\n echo \"'host' => 'localhost');\" >> /var/www/$1/sites/default/settings.php\n chmod 644 /var/www/$1/sites/default/settings.php\n\t\n\t#Echo DB Name\n\techo -e $COL_BLUE\"*** COPY FOR SAFE KEEPING ***\"\n\tCOL_BLUE=\"\\x1b[34;01m\"\n COL_RESET=\"\\x1b[39;49;00m\"\n echo -e $COL_BLUE\"Database Name: \"$COL_RESET\"$dbname\"\n\t\n #Echo DB User value\n\techo -e $COL_BLUE\"Database User: \"$COL_RESET\"${userid:0:15}\"\n\t\n\t#Echo DB Password\n\techo -e $COL_BLUE\"Database Password: \"$COL_RESET\"$passwd\"\n\t\n\t#Echo Install URL\n\techo -e $COL_BLUE\"Visit to finalize installation: \"$COL_RESET\"http://$1/install.php\"\n\t\n\n\n # Setting up Nginx mapping\n cat > \"/etc/nginx/sites-enabled/$1.conf\" <args = $args;\n\t\t\n\t\tif (!$this->args[\"username\"]){\n\t\t\tthrow new exception(\"No username was given.\");\n\t\t}\n\t\t\n\t\tif (!$this->args[\"password\"]){\n\t\t\tthrow new exception(\"No password was given.\");\n\t\t}\n\t\t\n\t\trequire_once \"knj/http.php\";\n\t\t$this->http = new knj_httpbrowser();\n\t\t$this->http->connect(\"betaling.wannafind.dk\", 443);\n\t\t\n\t\t$html = $this->http->getaddr(\"index.php\");\n\t\t\n\t\t$html = $this->http->post(\"pg.loginauth.php\", array(\n\t\t\t\"username\" => $this->args[\"username\"],\n\t\t\t\"password\" => $this->args[\"password\"]\n\t\t));\n\t\t\n\t\tif (strpos($html, \"Brugernavn eller password, blev ikke godkendt.\") !== false){\n\t\t\tthrow new exception(\"Could not log in.\");\n\t\t}\n\t}\n\t\n\tfunction http(){\n\t\treturn $this->http;\n\t}\n\t\n\tfunction listPayments($args = array()){\n\t\tif ($args[\"awaiting\"]){\n\t\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactions.php\");\n\t\t}else{\n\t\t\t$sargs = array(\n\t\t\t\t\"searchtype\" => \"\",\n\t\t\t\t\"fromday\" => \"01\",\n\t\t\t\t\"frommonth\" => \"01\",\n\t\t\t\t\"fromyear\" => date(\"Y\"),\n\t\t\t\t\"today\" => \"31\",\n\t\t\t\t\"tomonth\" => \"12\",\n\t\t\t\t\"toyear\" => date(\"Y\"),\n\t\t\t\t\"transacknum\" => \"\"\n\t\t\t);\n\t\t\t\n\t\t\tif ($args[\"order_id\"]){\n\t\t\t\t$sargs[\"orderid\"] = $args[\"order_id\"];\n\t\t\t}\n\t\t\t\n\t\t\t$html = $this->http->post(\"pg.frontend/pg.search.php?search=doit\", $sargs);\n\t\t}\n\t\t\n\t\tif (!preg_match_all(\"/([0-9]+)<\\/a><\\/td>\\s*(.+)<\\/td>\\s*(.+)<\\/td>\\s*(.+)<\\/td>\\s*.*<\\/td>\\s*(.*)<\\/td>\\s*(.*)<\\/td>/U\", $html, $matches)){\n\t\t\treturn array(); //no payments were found - return empty array.\n\t\t\t//echo $html . \"\\n\\n\";\n\t\t\tthrow new exception(\"Could not parse payments.\");\n\t\t}\n\t\t\n\t\t$payments = array();\n\t\tforeach($matches[0] AS $key => $value){\n\t\t\t$id = $matches[1][$key];\n\t\t\t\n\t\t\t$amount = str_replace(\" DKK\", \"\", $matches[6][$key]);\n\t\t\t$amount = strtr($amount, array(\n\t\t\t\t\".\" => \"\",\n\t\t\t\t\",\" => \".\"\n\t\t\t));\n\t\t\t\n\t\t\t$card_type = $matches[7][$key];\n\t\t\tif (strpos($card_type, \"dk.png\") !== false){\n\t\t\t\t$card_type = \"dk\";\n\t\t\t}elseif(strpos($card_type, \"visa-elec.png\") !== false){\n\t\t\t\t$card_type = \"visa_electron\";\n\t\t\t}elseif(strpos($card_type, \"mc.png\") !== false){\n\t\t\t\t$card_type = \"mastercard\";\n\t\t\t}elseif(strpos($card_type, \"visa.png\") !== false){\n\t\t\t\t$card_type = \"visa\";\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Unknown card-type image: \" . $card_type);\n\t\t\t}\n\t\t\t\n\t\t\t$date = strtr($matches[5][$key], array(\n\t\t\t\t\"januar\" => 1,\n\t\t\t\t\"februar\" => 2,\n\t\t\t\t\"marts\" => 3,\n\t\t\t\t\"april\" => 4,\n\t\t\t\t\"maj\" => 5,\n\t\t\t\t\"juni\" => 6,\n\t\t\t\t\"juli\" => 7,\n\t\t\t\t\"august\" => 8,\n\t\t\t\t\"september\" => 9,\n\t\t\t\t\"oktober\" => 10,\n\t\t\t\t\"november\" => 11,\n\t\t\t\t\"december\" => 12\n\t\t\t));\n\t\t\t\n\t\t\tif (preg_match(\"/(\\d+) (\\d+) (\\d+) (\\d+):(\\d+):(\\d+)/\", $date, $match)){\n\t\t\t\t$unixt = mktime($match[4], $match[5], $match[6], $match[2], $match[1], $match[3]);\n\t\t\t}elseif(preg_match(\"/(\\d+) ([a-z]{3}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2})/\", $date, $match)){\n\t\t\t\t$month = $match[2];\n\t\t\t\tif ($month == \"jan\"){\n\t\t\t\t\t$month_no = 1;\n\t\t\t\t}elseif($month == \"feb\"){\n\t\t\t\t\t$month_no = 2;\n\t\t\t\t}elseif($month == \"mar\"){\n\t\t\t\t\t$month_no = 3;\n\t\t\t\t}elseif($month == \"apr\"){\n\t\t\t\t\t$month_no = 4;\n\t\t\t\t}elseif($month == \"maj\"){\n\t\t\t\t\t$month_no = 5;\n\t\t\t\t}elseif($month == \"jun\"){\n\t\t\t\t\t$month_no = 6;\n\t\t\t\t}elseif($month == \"jul\"){\n\t\t\t\t\t$month_no = 7;\n\t\t\t\t}elseif($month == \"aug\"){\n\t\t\t\t\t$month_no = 8;\n\t\t\t\t}elseif($month == \"sep\"){\n\t\t\t\t\t$month_no = 9;\n\t\t\t\t}elseif($month == \"okt\"){\n\t\t\t\t\t$month_no = 10;\n\t\t\t\t}elseif($month == \"nov\"){\n\t\t\t\t\t$month_no = 11;\n\t\t\t\t}elseif($month == \"dec\"){\n\t\t\t\t\t$month_no = 12;\n\t\t\t\t}else{\n\t\t\t\t\tthrow new exception(\"Unknown month string: \" . $month);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$unixt = mktime($match[4], $match[5], $match[6], $month_no, $match[1], $match[3]);\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Could not parse date: \" . $date);\n\t\t\t}\n\t\t\t\n\t\t\t$state = $matches[8][$key];\n\t\t\tif ($state == \"Gennemf\u00f8rt\"){\n\t\t\t\t$state = \"done\";\n\t\t\t}elseif(strpos($state, \"Gennemf\u00f8r\") !== false){\n\t\t\t\t$state = \"waiting\";\n\t\t\t}elseif($state == \"Annulleret\"){\n\t\t\t\t$state = \"canceled\";\n\t\t\t}elseif($state == \"Refunderet\"){\n\t\t\t\t$state = \"returned\";\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Unknown state: \" . $state);\n\t\t\t}\n\t\t\t\n\t\t\tif ($this->payments[$id]){\n\t\t\t\t$payment = $this->payments[$id];\n\t\t\t\t$payment->set(\"state\", $state);\n\t\t\t}else{\n\t\t\t\t$payment = new wfpayment_payment($this, array(\n\t\t\t\t\t\"id\" => $id,\n\t\t\t\t\t\"order_id\" => substr($matches[4][$key], 4),\n\t\t\t\t\t\"customer_id\" => $matches[3][$key],\n\t\t\t\t\t\"customer_string\" => $matches[4][$key],\n\t\t\t\t\t\"date\" => $unixt,\n\t\t\t\t\t\"amount\" => $amount,\n\t\t\t\t\t\"card_type\" => $card_type,\n\t\t\t\t\t\"state\" => $state\n\t\t\t\t));\n\t\t\t}\n\t\t\t\n\t\t\t$payments[] = $payment;\n\t\t}\n\t\t\n\t\treturn $payments;\n\t}\n}\n\nclass wfpayment_payment{\n\tfunction __construct($wfpayment, $args){\n\t\t$this->wfpayment = $wfpayment;\n\t\t$this->http = $this->wfpayment->http();\n\t\t$this->args = $args;\n\t}\n\t\n\tfunction set($key, $value){\n\t\t$this->args[$key] = $value;\n\t}\n\t\n\tfunction get($key){\n\t\tif (!array_key_exists($key, $this->args)){\n\t\t\tthrow new exception(\"No such key: \" . $key);\n\t\t}\n\t\t\n\t\treturn $this->args[$key];\n\t}\n\t\n\tfunction args(){\n\t\treturn $this->args;\n\t}\n\t\n\tfunction accept(){\n\t\tif ($this->state() == \"done\"){\n\t\t\tthrow new exception(\"This payment is already accepted.\");\n\t\t}\n\t\t\n\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactions.php?capture=singlecapture&transid=\" . $this->get(\"id\") . \"&page=1&orderby=&direction=\");\n\t\t\n\t\tif ($this->state() != \"done\"){\n\t\t\tthrow new exception(\"Could not accept the payment. State: \" . $this->state());\n\t\t}\n\t}\n\t\n\tfunction cancel(){\n\t\tif ($this->state() != \"waiting\"){\n\t\t\tthrow new exception(\"This is not waiting and cannot be canceled.\");\n\t\t}\n\t\t\n\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactionview.php?action=cancel&id=\" . $this->get(\"id\") . \"&page=1\");\n\t\t\n\t\tif ($this->state() != \"canceled\"){\n\t\t\tthrow new exception(\"Could not cancel the payment.\");\n\t\t}\n\t}\n\t\n\tfunction state(){\n\t\t$payments = $this->wfpayment->listPayments(array(\"order_id\" => $this->get(\"order_id\")));\n\t\tif (!$payments or !$payments[0]){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn $payments[0]->get(\"state\");\n\t}\n}", "strings.php": " $value){\n\t\t\t\t$array[] = $value;\n\t\t\t\t$string = str_replace($matches[0][$key], \"\", $string);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (strlen($string) > 0){\n\t\t\tforeach(preg_split(\"/\\s/\", $string) AS $value){\n\t\t\t\tif (strlen(trim($value)) > 0){\n\t\t\t\t\t$array[] = $value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $array;\n\t}\n\t\n\tstatic function parseImageHTML($content){\n\t\tif (preg_match_all(\"//U\", $content, $matches)){\n\t\t\tforeach($matches[0] AS $key => $value){\n\t\t\t\t$img_html = $value;\n\t\t\t\t\n\t\t\t\tif (preg_match(\"/src=\\\"([\\s\\S]+)\\\"/U\", $img_html, $match_src)){\n\t\t\t\t\t$src = $match_src[1];\n\t\t\t\t\tif (substr($src, 0, 1) == \"/\"){\n\t\t\t\t\t\t$src = substr($src, 1);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t$replace_with = \"image.php?picture=\" . $src;\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match(\"/width: ([0-9]+)(px|)/\", $img_html, $match_width)){\n\t\t\t\t\t\t$size[\"width\"] = $match_width[1];\n\t\t\t\t\t\t$replace_with .= \"&width=\" . $match_width[1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match(\"/height: ([0-9]+)(px|)/\", $img_html, $match_height)){\n\t\t\t\t\t\t$size[\"height\"] = $match_height[1];\n\t\t\t\t\t\t$replace_with .= \"&height=\" . $match_width[1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match_all(\"/(width|height)=\\\"([0-9]+)(px|)\\\"/\", $img_html, $match_sizes)){\n\t\t\t\t\t\t$size = array();\n\t\t\t\t\t\tforeach($match_sizes[1] AS $key => $sizetype){\n\t\t\t\t\t\t\tif (!$size[$sizetype]){\n\t\t\t\t\t\t\t\t$size[$sizetype] = $match_sizes[2][$key];\n\t\t\t\t\t\t\t\t$replace_with .= \"&\" . $sizetype . \"=\" . $match_sizes[2][$key];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ($size){\n\t\t\t\t\t\t$img_html = str_replace($src, $replace_with, $img_html);\n\t\t\t\t\t\t$content = str_replace($value, $img_html, $content);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $content;\n\t}\n\t\n\tstatic function UnixSafe($string){\n\t\t$string = str_replace(\"\\\\\", \"\\\\\\\\\", $string);\n\t\t$string = str_replace(\" \", \"\\\\ \", $string);\n\t\t$string = str_replace(\"\\$\", \"\\\\\\$\", $string);\n\t\t$string = str_replace(\"(\", \"\\\\(\", $string);\n\t\t$string = str_replace(\")\", \"\\\\)\", $string);\n\t\t$string = str_replace(\";\", \"\\\\;\", $string);\n\t\t$string = str_replace(\",\", \"\\\\,\", $string);\n\t\t$string = str_replace(\"'\", \"\\\\'\", $string);\n\t\t$string = str_replace(\">\", \"\\\\>\", $string);\n\t\t$string = str_replace(\"<\", \"\\\\<\", $string);\n\t\t$string = str_replace(\"\\\"\", \"\\\\\\\"\", $string);\n\t\t$string = str_replace(\"&\", \"\\\\&\", $string);\n\t\t\n\t\t//Replace the end & - if any.\n\t\t//$string = preg_replace(\"/&\\s*$/\", \"\\\\&\", $string);\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function RegexSafe($string){\n\t\treturn strtr($string, array(\n\t\t\t\"/\" => \"\\\\/\",\n\t\t\t\".\" => \"\\\\.\",\n\t\t\t\"(\" => \"\\\\(\",\n\t\t\t\")\" => \"\\\\)\",\n\t\t\t\"[\" => \"\\\\[\",\n\t\t\t\"]\" => \"\\\\]\",\n\t\t\t\"^\" => \"\\\\^\",\n\t\t\t\"\\$\" => \"\\\\\\$\",\n\t\t\t\"+\" => \"\\\\+\"\n\t\t));\n\t}\n\t\n\tstatic function HeaderSafe($string){\n\t\treturn strtr($string, array(\n\t\t\t\"\\r\" => \"\",\n\t\t\t\"\\n\" => \" \"\n\t\t));\n\t}\n\t\n\tstatic function csvsafe($string){\n\t\t$string = htmlspecialchars($string);\n\t\t$string = str_replace(\"\\\"\", \"\", $string);\n\t\t$string = str_replace(\""\", \"\", $string);\n\t\t$string = str_replace(\"&\", \"&\", $string);\n\t\t$string = str_replace(\"\\r\", \"\", $string);\n\t\t$string = str_replace(\"\\n\", \"\", $string);\n\t\t$string = str_replace(\"<\", \"<\", $string);\n\t\t$string = str_replace(\">\", \">\", $string);\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function htmlspecialchars_textarea($text){\n\t\treturn preg_replace(\"/<\\/textarea>/i\", \"</textarea>\", $text);\n\t}\n\t\n\tstatic function jsparse($string, $paras = array()){\n\t\t$string = strtr($string, array(\n\t\t\t\"'\" => \"\\\\'\",\n\t\t\t\"\\\"\" => \""\",\n\t\t\t\"\\r\" => \"\",\n\t\t\t\"\\n\" => \"\\\\n\"\n\t\t));\n\t\t\n\t\tif ($paras[\"parse_quotes\"]){\n\t\t\t$string = str_replace(\"\\\"\", \"\\\\\\\"\", $string);\n\t\t}\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function tf_str($value, $yesstr, $nostr){\n\t\tif ($value){\n\t\t\treturn $yesstr;\n\t\t}\n\t\t\n\t\treturn $nostr;\n\t}\n\t\n\tstatic function shorten($text, $maxlength = nil){\n\t\tif (!$maxlength or strlen($text) <= $maxlength){\n\t\t\treturn $text;\n\t\t}\n\t\t\n\t\treturn trim(substr($text, 0, $maxlength)) . \"...\";\n\t}\n\t\n\tstatic function is_email($str){\n\t\tif (preg_match(\"/^(.+)@(.+)\\.(.+)/\", $str)){\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n}\n\n/**\n\t* Parses the quotes of a string.\n\t* \n\t* FIXME: DONT USE THIS FUNCTION! It will be removed soon... Look in the SQL-functions instead.\n*/\nfunction parse_quotes($string){\n\t$string = str_replace(\"'\", \"\\\\'\", $string);\n\t\n\tif (substr($string, -1, 1) == \"\\\\\" && substr($string, -2, 2) !== \"\\\\\\\\\"){\n\t\t$string = substr($string, 0, -1) . \"\\\\\\\\\";\n\t}\n\t\n\treturn $string;\n}\n\n/** Parse a string so it fits into the command-line of Linux. */\nfunction knj_string_unix_safe($string){\n\treturn knj_strings::UnixSafe($string);\n}\n\n/** Parse a string so it will be a valid filename. */\nfunction knj_string_filename($string, $os = null){\n\tif (!$os){\n\t\trequire_once(\"knj/os.php\");\n\t\t$os = knj_os::getOS();\n\t\t$os = $os[\"os\"];\n\t}\n\t\n\tif ($os == \"windows\"){\n\t\t//parse windows-filename here.\n\t}elseif($os == \"linux\"){\n\t\t$string = strtr($string, array(\n\t\t\t\"\u00e5\" => \"aa\",\n\t\t\t\"\u00f8\" => \"oe\",\n\t\t\t\"\u00e6\" => \"ae\",\n\t\t\tutf8_decode(\"\u00e5\") => \"aa\",\n\t\t\tutf8_decode(\"\u00e6\") => \"ae\",\n\t\t\tutf8_decode(\"\u00f8\") => \"oe\",\n\t\t\t\"|\" => \"\",\n\t\t\t\"&\" => \"\",\n\t\t\t\"/\" => \"\",\n\t\t\t\"\\\\\" => \"\"\n\t\t));\n\t}else{\n\t\tthrow new Exception(\"Unsupported OS.\");\n\t}\n\t\n\treturn $string;\n}\n\n/** Parse a string to it is safe in a regex-command. */\nfunction knj_string_regex($string){\n\treturn knj_strings::RegexSafe($string);\n}", "epay.php": "args = $args;\n\t\t\n\t\tif (!$this->args[\"username\"]){\n\t\t\tthrow new exception(\"No username was given.\");\n\t\t}\n\t\t\n\t\tif (!$this->args[\"password\"]){\n\t\t\tthrow new exception(\"No password was given.\");\n\t\t}\n\t\t\n\t\t$this->soap_client = new SoapClient(\"https://ssl.ditonlinebetalingssystem.dk/remote/payment.asmx?WSDL\", array(\n\t\t\t\"verify_peer\" => false,\n\t\t\t\"allow_self_signed\" => true\n\t\t));\n\t}\n\t\n\tfunction transactions($args = array()){\n\t\t$res = $this->soap_client->__soapCall(\"gettransactionlist\", array(\"parameters\" => array_merge($args, array(\n\t\t\t\"merchantnumber\" => $this->args[\"merchant_no\"]\n\t\t))));\n\t\t$ret = array();\n\t\t\n\t\tif (is_array($res->transactionInformationAry->TransactionInformationType)){\n\t\t\tforeach($res->transactionInformationAry->TransactionInformationType as $trans_obj){\n\t\t\t\t$ret[] = new epay_payment(array(\n\t\t\t\t\t\"epay\" => $this,\n\t\t\t\t\t\"obj\" => $trans_obj,\n\t\t\t\t\t\"soap_client\" => $this->soap_client\n\t\t\t\t));\n\t\t\t}\n\t\t}elseif($res->transactionInformationAry->TransactionInformationType){\n\t\t\t$ret[] = new epay_payment(array(\n\t\t\t\t\"epay\" => $this,\n\t\t\t\t\"obj\" => $res->transactionInformationAry->TransactionInformationType,\n\t\t\t\t\"soap_client\" => $this->soap_client\n\t\t\t));\n\t\t}\n\t\t\n\t\treturn $ret;\n\t}\n\t\n\tfunction transaction($args = array()){\n\t\t$res = $this->soap_client->__soapCall(\"gettransaction\", array(\"parameters\" => array_merge($args, array(\n\t\t\t\"merchantnumber\" => $this->args[\"merchant_no\"],\n\t\t\t\"epayresponse\" => true\n\t\t))));\n\t\t\n\t\treturn new epay_payment(array(\n\t\t\t\"epay\" => $this,\n\t\t\t\"obj\" => $res->transactionInformation,\n\t\t\t\"soap_client\" => $this->soap_client\n\t\t));\n\t}\n}\n\nclass epay_payment{\n\tfunction __construct($args){\n\t\t$this->args = $args;\n\t\t$this->soap_client = $args[\"soap_client\"];\n\t\t\n\t\t$this->data = array(\n\t\t\t\"amount\" => floatval($args[\"obj\"]->authamount),\n\t\t\t\"orderid\" => intval($args[\"obj\"]->orderid),\n\t\t\t\"status\" => $args[\"obj\"]->status,\n\t\t\t\"transactionid\" => $args[\"obj\"]->transactionid\n\t\t);\n\t}\n\t\n\tfunction get($key){\n\t\tif ($key == \"id\"){\n\t\t\t$key = \"transactionid\";\n\t\t}\n\t\t\n\t\tif (!array_key_exists($key, $this->data)){\n\t\t\tthrow new exception(\"No such key: \" . $key);\n\t\t}\n\t\t\n\t\treturn $this->data[$key];\n\t}\n\t\n\tfunction args(){\n\t\treturn $this->args;\n\t}\n\t\n\tfunction accept(){\n\t\tif ($this->data[\"status\"] == \"PAYMENT_CAPTURED\"){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t$res = $this->soap_client->__soapCall(\"capture\", array(\"parameters\" => array(\n\t\t\t\"merchantnumber\" => $this->args[\"epay\"]->args[\"merchant_no\"],\n\t\t\t\"transactionid\" => $this->data[\"transactionid\"],\n\t\t\t\"amount\" => $this->data[\"amount\"],\n\t\t\t\"epayresponse\" => true,\n\t\t\t\"pbsResponse\" => true\n\t\t)));\n\t\t\n\t\tif (!$res->captureResult){\n\t\t\tthrow new exception(\"Could not accept payment.\\n\\n\" . print_r($res, true));\n\t\t}\n\t}\n\t\n\tfunction delete(){\n\t\t$res = $this->soap_client->__soapCall(\"delete\", array(\"parameters\" => array(\n\t\t\t\"merchantnumber\" => $this->args[\"epay\"]->args[\"merchant_no\"],\n\t\t\t\"transactionid\" => $this->data[\"transactionid\"],\n\t\t\t\"epayresponse\" => true\n\t\t)));\n\t\t\n\t\tif (!$res->deleteResult){\n\t\t\tthrow new exception(\"Could not delete payment.\\n\\n\" . print_r($res, true));\n\t\t}\n\t}\n\t\n\tfunction state(){\n\t\tthrow new exception(\"stub!\");\n\t}\n}"}, "files_after": {"wfpayment.php": "args = $args;\n\t\t\n\t\tif (!$this->args[\"username\"]){\n\t\t\tthrow new exception(\"No username was given.\");\n\t\t}\n\t\t\n\t\tif (!$this->args[\"password\"]){\n\t\t\tthrow new exception(\"No password was given.\");\n\t\t}\n\t\t\n\t\trequire_once \"knj/http.php\";\n\t\t$this->http = new knj_httpbrowser();\n\t\t$this->http->connect(\"betaling.wannafind.dk\", 443);\n\t\t\n\t\t$html = $this->http->getaddr(\"index.php\");\n\t\t\n\t\t$html = $this->http->post(\"pg.loginauth.php\", array(\n\t\t\t\"username\" => $this->args[\"username\"],\n\t\t\t\"password\" => $this->args[\"password\"]\n\t\t));\n\t\t\n\t\tif (strpos($html, \"Brugernavn eller password, blev ikke godkendt.\") !== false){\n\t\t\tthrow new exception(\"Could not log in.\");\n\t\t}\n\t}\n\t\n\tfunction http(){\n\t\treturn $this->http;\n\t}\n\t\n\tfunction listPayments($args = array()){\n\t\tif ($args[\"awaiting\"]){\n\t\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactions.php\");\n\t\t}else{\n\t\t\t$sargs = array(\n\t\t\t\t\"searchtype\" => \"\",\n\t\t\t\t\"fromday\" => \"01\",\n\t\t\t\t\"frommonth\" => \"01\",\n\t\t\t\t\"fromyear\" => date(\"Y\"),\n\t\t\t\t\"today\" => \"31\",\n\t\t\t\t\"tomonth\" => \"12\",\n\t\t\t\t\"toyear\" => date(\"Y\"),\n\t\t\t\t\"transacknum\" => \"\"\n\t\t\t);\n\t\t\t\n\t\t\tif ($args[\"order_id\"]){\n\t\t\t\t$sargs[\"orderid\"] = $args[\"order_id\"];\n\t\t\t}\n\t\t\t\n\t\t\t$html = $this->http->post(\"pg.frontend/pg.search.php?search=doit\", $sargs);\n\t\t}\n\t\t\n\t\tif (!preg_match_all(\"/]+)>\\s*([\\s\\S]+)<\\/tr>/U\", $html, $matches_tr)){\n\t\t\treturn array();\n\t\t}\n\t\t\n\t\tif (count($matches_tr[2]) == 1 or strlen(trim($matches_tr[2][0])) <= 0){\n\t\t\treturn array();\n\t\t}\n\t\t\n\t\t$payments = array();\n\t\tforeach($matches_tr[0] AS $key => $value){\n\t\t\tif (!preg_match_all(\"/]+)>(.*)<\\/td>/U\", $value, $matches_td)){\n\t\t\t\tthrow new exception(\"Could not match TDs.\");\n\t\t\t}\n\t\t\t\n\t\t\tif (!preg_match(\"/id=(\\d+)/\", $matches_td[2][0], $match_id)){\n\t\t\t\tthrow new exception(\"Could not match ID.\");\n\t\t\t}\n\t\t\t\n\t\t\t$id = $match_id[1];\n\t\t\t\n\t\t\t$amount = str_replace(\" DKK\", \"\", $matches_td[2][3]);\n\t\t\t$amount = strtr($amount, array(\n\t\t\t\t\".\" => \"\",\n\t\t\t\t\",\" => \".\"\n\t\t\t));\n\t\t\t\n\t\t\t$card_type = $matches_td[2][6];\n\t\t\t\n\t\t\tif (strpos($card_type, \"dk.png\") !== false){\n\t\t\t\t$card_type = \"dk\";\n\t\t\t}elseif(strpos($card_type, \"visa-elec.png\") !== false){\n\t\t\t\t$card_type = \"visa_electron\";\n\t\t\t}elseif(strpos($card_type, \"mc.png\") !== false){\n\t\t\t\t$card_type = \"mastercard\";\n\t\t\t}elseif(strpos($card_type, \"visa.png\") !== false){\n\t\t\t\t$card_type = \"visa\";\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Unknown card-type image: \" . $card_type);\n\t\t\t}\n\t\t\t\n\t\t\t$date = strtr($matches_td[2][2], array(\n\t\t\t\t\"januar\" => 1,\n\t\t\t\t\"februar\" => 2,\n\t\t\t\t\"marts\" => 3,\n\t\t\t\t\"april\" => 4,\n\t\t\t\t\"maj\" => 5,\n\t\t\t\t\"juni\" => 6,\n\t\t\t\t\"juli\" => 7,\n\t\t\t\t\"august\" => 8,\n\t\t\t\t\"september\" => 9,\n\t\t\t\t\"oktober\" => 10,\n\t\t\t\t\"november\" => 11,\n\t\t\t\t\"december\" => 12\n\t\t\t));\n\t\t\t\n\t\t\tif (preg_match(\"/(\\d+) (\\d+) (\\d+) (\\d+):(\\d+):(\\d+)/\", $date, $match)){\n\t\t\t\t$unixt = mktime($match[4], $match[5], $match[6], $match[2], $match[1], $match[3]);\n\t\t\t}elseif(preg_match(\"/(\\d+) ([a-z]{3}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2})/\", $date, $match)){\n\t\t\t\t$month = $match[2];\n\t\t\t\tif ($month == \"jan\"){\n\t\t\t\t\t$month_no = 1;\n\t\t\t\t}elseif($month == \"feb\"){\n\t\t\t\t\t$month_no = 2;\n\t\t\t\t}elseif($month == \"mar\"){\n\t\t\t\t\t$month_no = 3;\n\t\t\t\t}elseif($month == \"apr\"){\n\t\t\t\t\t$month_no = 4;\n\t\t\t\t}elseif($month == \"maj\"){\n\t\t\t\t\t$month_no = 5;\n\t\t\t\t}elseif($month == \"jun\"){\n\t\t\t\t\t$month_no = 6;\n\t\t\t\t}elseif($month == \"jul\"){\n\t\t\t\t\t$month_no = 7;\n\t\t\t\t}elseif($month == \"aug\"){\n\t\t\t\t\t$month_no = 8;\n\t\t\t\t}elseif($month == \"sep\"){\n\t\t\t\t\t$month_no = 9;\n\t\t\t\t}elseif($month == \"okt\"){\n\t\t\t\t\t$month_no = 10;\n\t\t\t\t}elseif($month == \"nov\"){\n\t\t\t\t\t$month_no = 11;\n\t\t\t\t}elseif($month == \"dec\"){\n\t\t\t\t\t$month_no = 12;\n\t\t\t\t}else{\n\t\t\t\t\tthrow new exception(\"Unknown month string: \" . $month);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$unixt = mktime($match[4], $match[5], $match[6], $month_no, $match[1], $match[3]);\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Could not parse date: \" . $date);\n\t\t\t}\n\t\t\t\n\t\t\t$state = $matches_td[2][7];\n\t\t\tif (strpos($state, \"Gennemf\u00f8rt\") !== false){\n\t\t\t\t$state = \"done\";\n\t\t\t}elseif(strpos($state, \"Gennemf\u00f8r\") !== false){\n\t\t\t\t$state = \"waiting\";\n\t\t\t}elseif(strpos($state, \"Annulleret\") !== false){\n\t\t\t\t$state = \"canceled\";\n\t\t\t}elseif(strpos($state, \"Refunderet\") !== false){\n\t\t\t\t$state = \"returned\";\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Unknown state: \" . $state);\n\t\t\t}\n\t\t\t\n\t\t\tif ($this->payments[$id]){\n\t\t\t\t$payment = $this->payments[$id];\n\t\t\t\t$payment->set(\"state\", $state);\n\t\t\t}else{\n\t\t\t\t$payment = new wfpayment_payment($this, array(\n\t\t\t\t\t\"id\" => $id,\n\t\t\t\t\t\"order_id\" => substr($matches_td[2][1], 4),\n\t\t\t\t\t\"customer_id\" => $matches_td[2][1],\n\t\t\t\t\t\"customer_string\" => $matches_td[2][1],\n\t\t\t\t\t\"date\" => $unixt,\n\t\t\t\t\t\"amount\" => $amount,\n\t\t\t\t\t\"card_type\" => $card_type,\n\t\t\t\t\t\"state\" => $state\n\t\t\t\t));\n\t\t\t}\n\t\t\t\n\t\t\t$payments[] = $payment;\n\t\t}\n\t\t\n\t\treturn $payments;\n\t}\n}\n\nclass wfpayment_payment{\n\tfunction __construct($wfpayment, $args){\n\t\t$this->wfpayment = $wfpayment;\n\t\t$this->http = $this->wfpayment->http();\n\t\t$this->args = $args;\n\t}\n\t\n\tfunction set($key, $value){\n\t\t$this->args[$key] = $value;\n\t}\n\t\n\tfunction get($key){\n\t\tif (!array_key_exists($key, $this->args)){\n\t\t\tthrow new exception(\"No such key: \" . $key);\n\t\t}\n\t\t\n\t\treturn $this->args[$key];\n\t}\n\t\n\tfunction args(){\n\t\treturn $this->args;\n\t}\n\t\n\tfunction accept(){\n\t\tif ($this->state() == \"done\"){\n\t\t\tthrow new exception(\"This payment is already accepted.\");\n\t\t}\n\t\t\n\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactions.php?capture=singlecapture&transid=\" . $this->get(\"id\") . \"&page=1&orderby=&direction=\");\n\t\t\n\t\tif ($this->state() != \"done\"){\n\t\t\tthrow new exception(\"Could not accept the payment. State: \" . $this->state());\n\t\t}\n\t}\n\t\n\tfunction cancel(){\n\t\tif ($this->state() != \"waiting\"){\n\t\t\tthrow new exception(\"This is not waiting and cannot be canceled.\");\n\t\t}\n\t\t\n\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactionview.php?action=cancel&id=\" . $this->get(\"id\") . \"&page=1\");\n\t\t\n\t\tif ($this->state() != \"canceled\"){\n\t\t\tthrow new exception(\"Could not cancel the payment.\");\n\t\t}\n\t}\n\t\n\tfunction state(){\n\t\t$payments = $this->wfpayment->listPayments(array(\"order_id\" => $this->get(\"order_id\")));\n\t\tif (!$payments or !$payments[0]){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn $payments[0]->get(\"state\");\n\t}\n}", "strings.php": " $value){\n\t\t\t\t$string[$key] = knj_strings::utf8force($value);\n\t\t\t}\n\t\t\t\n\t\t\treturn $string;\n\t\t}else{\n\t\t\t$values = array();\n\t\t\t$special = array(\"\u00f8\", \"\u00e6\", \"\u00e5\", \"\u00d8\", \"\u00c6\", \"\u00c5\");\n\t\t\tforeach($special AS $value){\n\t\t\t\t$values[utf8_decode($value)] = $value;\n\t\t\t}\n\t\t\t\n\t\t\t$string = str_replace(\"\u00c3\u00a6\", \"\u00e6\", $string);\n\t\t\t\n\t\t\treturn strtr($string, $values);\n\t\t}\n\t}\n\t\n\t/** Parses a string into an array of strings, which should all be searched for. */\n\tstatic function searchstring($string){\n\t\t$array = array();\n\t\t\n\t\tif (preg_match_all(\"/\\\"(.*)\\\"/U\", $string, $matches)){\n\t\t\tforeach($matches[1] AS $key => $value){\n\t\t\t\t$array[] = $value;\n\t\t\t\t$string = str_replace($matches[0][$key], \"\", $string);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (strlen($string) > 0){\n\t\t\tforeach(preg_split(\"/\\s/\", $string) AS $value){\n\t\t\t\tif (strlen(trim($value)) > 0){\n\t\t\t\t\t$array[] = $value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $array;\n\t}\n\t\n\tstatic function parseImageHTML($content){\n\t\tif (preg_match_all(\"//U\", $content, $matches)){\n\t\t\tforeach($matches[0] AS $key => $value){\n\t\t\t\t$img_html = $value;\n\t\t\t\t\n\t\t\t\tif (preg_match(\"/src=\\\"([\\s\\S]+)\\\"/U\", $img_html, $match_src)){\n\t\t\t\t\t$src = $match_src[1];\n\t\t\t\t\tif (substr($src, 0, 1) == \"/\"){\n\t\t\t\t\t\t$src = substr($src, 1);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t$replace_with = \"image.php?picture=\" . $src;\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match(\"/width: ([0-9]+)(px|)/\", $img_html, $match_width)){\n\t\t\t\t\t\t$size[\"width\"] = $match_width[1];\n\t\t\t\t\t\t$replace_with .= \"&width=\" . $match_width[1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match(\"/height: ([0-9]+)(px|)/\", $img_html, $match_height)){\n\t\t\t\t\t\t$size[\"height\"] = $match_height[1];\n\t\t\t\t\t\t$replace_with .= \"&height=\" . $match_width[1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match_all(\"/(width|height)=\\\"([0-9]+)(px|)\\\"/\", $img_html, $match_sizes)){\n\t\t\t\t\t\t$size = array();\n\t\t\t\t\t\tforeach($match_sizes[1] AS $key => $sizetype){\n\t\t\t\t\t\t\tif (!$size[$sizetype]){\n\t\t\t\t\t\t\t\t$size[$sizetype] = $match_sizes[2][$key];\n\t\t\t\t\t\t\t\t$replace_with .= \"&\" . $sizetype . \"=\" . $match_sizes[2][$key];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ($size){\n\t\t\t\t\t\t$img_html = str_replace($src, $replace_with, $img_html);\n\t\t\t\t\t\t$content = str_replace($value, $img_html, $content);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $content;\n\t}\n\t\n\tstatic function UnixSafe($string){\n\t\t$string = str_replace(\"\\\\\", \"\\\\\\\\\", $string);\n\t\t$string = str_replace(\" \", \"\\\\ \", $string);\n\t\t$string = str_replace(\"\\$\", \"\\\\\\$\", $string);\n\t\t$string = str_replace(\"(\", \"\\\\(\", $string);\n\t\t$string = str_replace(\")\", \"\\\\)\", $string);\n\t\t$string = str_replace(\";\", \"\\\\;\", $string);\n\t\t$string = str_replace(\",\", \"\\\\,\", $string);\n\t\t$string = str_replace(\"'\", \"\\\\'\", $string);\n\t\t$string = str_replace(\">\", \"\\\\>\", $string);\n\t\t$string = str_replace(\"<\", \"\\\\<\", $string);\n\t\t$string = str_replace(\"\\\"\", \"\\\\\\\"\", $string);\n\t\t$string = str_replace(\"&\", \"\\\\&\", $string);\n\t\t\n\t\t//Replace the end & - if any.\n\t\t//$string = preg_replace(\"/&\\s*$/\", \"\\\\&\", $string);\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function RegexSafe($string){\n\t\treturn strtr($string, array(\n\t\t\t\"/\" => \"\\\\/\",\n\t\t\t\".\" => \"\\\\.\",\n\t\t\t\"(\" => \"\\\\(\",\n\t\t\t\")\" => \"\\\\)\",\n\t\t\t\"[\" => \"\\\\[\",\n\t\t\t\"]\" => \"\\\\]\",\n\t\t\t\"^\" => \"\\\\^\",\n\t\t\t\"\\$\" => \"\\\\\\$\",\n\t\t\t\"+\" => \"\\\\+\"\n\t\t));\n\t}\n\t\n\tstatic function HeaderSafe($string){\n\t\treturn strtr($string, array(\n\t\t\t\"\\r\" => \"\",\n\t\t\t\"\\n\" => \" \"\n\t\t));\n\t}\n\t\n\tstatic function csvsafe($string){\n\t\t$string = htmlspecialchars($string);\n\t\t$string = str_replace(\"\\\"\", \"\", $string);\n\t\t$string = str_replace(\""\", \"\", $string);\n\t\t$string = str_replace(\"&\", \"&\", $string);\n\t\t$string = str_replace(\"\\r\", \"\", $string);\n\t\t$string = str_replace(\"\\n\", \"\", $string);\n\t\t$string = str_replace(\"<\", \"<\", $string);\n\t\t$string = str_replace(\">\", \">\", $string);\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function htmlspecialchars_textarea($text){\n\t\treturn preg_replace(\"/<\\/textarea>/i\", \"</textarea>\", $text);\n\t}\n\t\n\tstatic function jsparse($string, $paras = array()){\n\t\t$string = strtr($string, array(\n\t\t\t\"'\" => \"\\\\'\",\n\t\t\t\"\\\"\" => \""\",\n\t\t\t\"\\r\" => \"\",\n\t\t\t\"\\n\" => \"\\\\n\"\n\t\t));\n\t\t\n\t\tif ($paras[\"parse_quotes\"]){\n\t\t\t$string = str_replace(\"\\\"\", \"\\\\\\\"\", $string);\n\t\t}\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function tf_str($value, $yesstr, $nostr){\n\t\tif ($value){\n\t\t\treturn $yesstr;\n\t\t}\n\t\t\n\t\treturn $nostr;\n\t}\n\t\n\tstatic function shorten($text, $maxlength = nil){\n\t\tif (!$maxlength or strlen($text) <= $maxlength){\n\t\t\treturn $text;\n\t\t}\n\t\t\n\t\treturn trim(substr($text, 0, $maxlength)) . \"...\";\n\t}\n\t\n\tstatic function is_email($str){\n\t\tif (preg_match(\"/^(.+)@(.+)\\.(.+)/\", $str)){\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n}\n\n/**\n\t* Parses the quotes of a string.\n\t* \n\t* FIXME: DONT USE THIS FUNCTION! It will be removed soon... Look in the SQL-functions instead.\n*/\nfunction parse_quotes($string){\n\t$string = str_replace(\"'\", \"\\\\'\", $string);\n\t\n\tif (substr($string, -1, 1) == \"\\\\\" && substr($string, -2, 2) !== \"\\\\\\\\\"){\n\t\t$string = substr($string, 0, -1) . \"\\\\\\\\\";\n\t}\n\t\n\treturn $string;\n}\n\n/** Parse a string so it fits into the command-line of Linux. */\nfunction knj_string_unix_safe($string){\n\treturn knj_strings::UnixSafe($string);\n}\n\n/** Parse a string so it will be a valid filename. */\nfunction knj_string_filename($string, $os = null){\n\tif (!$os){\n\t\trequire_once(\"knj/os.php\");\n\t\t$os = knj_os::getOS();\n\t\t$os = $os[\"os\"];\n\t}\n\t\n\tif ($os == \"windows\"){\n\t\t//parse windows-filename here.\n\t}elseif($os == \"linux\"){\n\t\t$string = strtr($string, array(\n\t\t\t\"\u00e5\" => \"aa\",\n\t\t\t\"\u00f8\" => \"oe\",\n\t\t\t\"\u00e6\" => \"ae\",\n\t\t\tutf8_decode(\"\u00e5\") => \"aa\",\n\t\t\tutf8_decode(\"\u00e6\") => \"ae\",\n\t\t\tutf8_decode(\"\u00f8\") => \"oe\",\n\t\t\t\"|\" => \"\",\n\t\t\t\"&\" => \"\",\n\t\t\t\"/\" => \"\",\n\t\t\t\"\\\\\" => \"\"\n\t\t));\n\t}else{\n\t\tthrow new Exception(\"Unsupported OS.\");\n\t}\n\t\n\treturn $string;\n}\n\n/** Parse a string to it is safe in a regex-command. */\nfunction knj_string_regex($string){\n\treturn knj_strings::RegexSafe($string);\n}", "epay.php": "args = $args;\n\t\t\n\t\tif (!$this->args[\"username\"]){\n\t\t\tthrow new exception(\"No username was given.\");\n\t\t}\n\t\t\n\t\tif (!$this->args[\"password\"]){\n\t\t\tthrow new exception(\"No password was given.\");\n\t\t}\n\t\t\n\t\t$this->soap_client = new SoapClient(\"https://ssl.ditonlinebetalingssystem.dk/remote/payment.asmx?WSDL\", array(\n\t\t\t\"verify_peer\" => false,\n\t\t\t\"allow_self_signed\" => true\n\t\t));\n\t}\n\t\n\tfunction transactions($args = array()){\n\t\t$res = $this->soap_client->__soapCall(\"gettransactionlist\", array(\"parameters\" => array_merge($args, array(\n\t\t\t\"merchantnumber\" => $this->args[\"merchant_no\"]\n\t\t))));\n\t\t$ret = array();\n\t\t\n\t\tif (is_array($res->transactionInformationAry->TransactionInformationType)){\n\t\t\tforeach($res->transactionInformationAry->TransactionInformationType as $trans_obj){\n\t\t\t\t$ret[] = new epay_payment(array(\n\t\t\t\t\t\"epay\" => $this,\n\t\t\t\t\t\"obj\" => $trans_obj,\n\t\t\t\t\t\"soap_client\" => $this->soap_client\n\t\t\t\t));\n\t\t\t}\n\t\t}elseif($res->transactionInformationAry->TransactionInformationType){\n\t\t\t$ret[] = new epay_payment(array(\n\t\t\t\t\"epay\" => $this,\n\t\t\t\t\"obj\" => $res->transactionInformationAry->TransactionInformationType,\n\t\t\t\t\"soap_client\" => $this->soap_client\n\t\t\t));\n\t\t}\n\t\t\n\t\treturn $ret;\n\t}\n\t\n\tfunction transaction($args = array()){\n\t\t$res = $this->soap_client->__soapCall(\"gettransaction\", array(\"parameters\" => array_merge($args, array(\n\t\t\t\"merchantnumber\" => $this->args[\"merchant_no\"],\n\t\t\t\"epayresponse\" => true\n\t\t))));\n\t\t\n\t\treturn new epay_payment(array(\n\t\t\t\"epay\" => $this,\n\t\t\t\"obj\" => $res->transactionInformation,\n\t\t\t\"soap_client\" => $this->soap_client\n\t\t));\n\t}\n}\n\nclass epay_payment{\n\tfunction __construct($args){\n\t\t$this->args = $args;\n\t\t$this->soap_client = $args[\"soap_client\"];\n\t\t\n\t\tif ($args[\"obj\"]->capturedamount){\n\t\t\t$amount = floatval($args[\"obj\"]->capturedamount);\n\t\t}else{\n\t\t\t$amount = floatval($args[\"obj\"]->authamount);\n\t\t}\n\t\t\n\t\t$this->data = array(\n\t\t\t\"amount\" => $amount,\n\t\t\t\"orderid\" => intval($args[\"obj\"]->orderid),\n\t\t\t\"status\" => $args[\"obj\"]->status,\n\t\t\t\"transactionid\" => $args[\"obj\"]->transactionid\n\t\t);\n\t}\n\t\n\tfunction get($key){\n\t\tif ($key == \"id\"){\n\t\t\t$key = \"transactionid\";\n\t\t}\n\t\t\n\t\tif (!array_key_exists($key, $this->data)){\n\t\t\tthrow new exception(\"No such key: \" . $key);\n\t\t}\n\t\t\n\t\treturn $this->data[$key];\n\t}\n\t\n\tfunction args(){\n\t\treturn $this->args;\n\t}\n\t\n\tfunction accept(){\n\t\tif ($this->data[\"status\"] == \"PAYMENT_CAPTURED\"){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t$res = $this->soap_client->__soapCall(\"capture\", array(\"parameters\" => array(\n\t\t\t\"merchantnumber\" => $this->args[\"epay\"]->args[\"merchant_no\"],\n\t\t\t\"transactionid\" => $this->data[\"transactionid\"],\n\t\t\t\"amount\" => $this->data[\"amount\"],\n\t\t\t\"epayresponse\" => true,\n\t\t\t\"pbsResponse\" => true\n\t\t)));\n\t\t\n\t\tif (!$res->captureResult){\n\t\t\tthrow new exception(\"Could not accept payment.\\n\\n\" . print_r($res, true));\n\t\t}\n\t}\n\t\n\tfunction delete(){\n\t\t$res = $this->soap_client->__soapCall(\"delete\", array(\"parameters\" => array(\n\t\t\t\"merchantnumber\" => $this->args[\"epay\"]->args[\"merchant_no\"],\n\t\t\t\"transactionid\" => $this->data[\"transactionid\"],\n\t\t\t\"epayresponse\" => true\n\t\t)));\n\t\t\n\t\tif (!$res->deleteResult){\n\t\t\tthrow new exception(\"Could not delete payment.\\n\\n\" . print_r($res, true));\n\t\t}\n\t}\n\t\n\tfunction state(){\n\t\tthrow new exception(\"stub!\");\n\t}\n}"}} -{"repo": "collective/collective.setuphandlertools", "pr_number": 1, "title": "Depend on Products.CMFPlone instead of Plone to not fetch unnecessary\u2026", "state": "closed", "merged_at": "2018-02-08T13:11:26Z", "additions": 8, "deletions": 1, "files_changed": ["setup.py"], "files_before": {"setup.py": "from setuptools import setup, find_packages\nimport os\n\nversion = '1.0b4'\n\nsetup(name='collective.setuphandlertools',\n version=version,\n description=\"Tools for setting up a Plone site.\",\n long_description=open(\"README.txt\").read() + \"\\n\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more strings from http://pypi.python.org/pypi?:action=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n ],\n keywords='plone zope setup',\n author='Johannes Raggam',\n author_email='raggam-nl@adm.at',\n url='http://github.com/collective/collective.setuphandlertools',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n 'Plone',\n 'Products.ATContentTypes',\n 'Products.CMFCore',\n 'Products.PortalTransforms',\n ],\n )\n"}, "files_after": {"setup.py": "from setuptools import setup, find_packages\nimport os\n\nversion = '1.0b4'\n\nsetup(name='collective.setuphandlertools',\n version=version,\n description=\"Tools for setting up a Plone site.\",\n long_description=open(\"README.txt\").read() + \"\\n\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more strings from http://pypi.python.org/pypi?:action=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n ],\n keywords='plone zope setup',\n author='Johannes Raggam',\n author_email='raggam-nl@adm.at',\n url='http://github.com/collective/collective.setuphandlertools',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n 'Products.CMFPlone',\n 'Products.ATContentTypes',\n 'Products.CMFCore',\n 'Products.PortalTransforms',\n ],\n )\n"}} -{"repo": "balinterdi/balinterdi.github.com", "pr_number": 13, "title": "Sales web changes", "state": "closed", "merged_at": "2016-03-07T13:05:36Z", "additions": 13, "deletions": 1, "files_changed": ["source/_layouts/rarwe_book.html"], "files_before": {"source/_layouts/rarwe_book.html": "\n\n\n\n \n \n \n \n\n \n \n \n \n \n \n\n \n \n\n Cut your learning curve and build ambitious apps with Ember.js.\n\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n\n\n\n
\n\n \n
\n
\n\n \n\n
\n
\n
\n \"Rock\n
\n
\n
\n
\n

Build ambitious apps with confidence

\n

Ember.js is a kick-ass framework for building\n web applications. It's the only tool you need\n (on the client-side) to craft your idea into a working\n wonder. However, its strong opinions and heavy reliance of\n \u201cconvention over configuration\u201d can give developers who\n are new to the framework a hard time figuring out how\n Ember wants them to do things.

\n\n

This book helps to overcome that initial\n frustration, and help you grok Ember a lot\n faster, by pinpointing the core concepts and\n explaining them in detail. Once you understand them you\n are on your way to taming and mastering Ember.js.\n So don't fear the learning curve.

\n\n
\n
\n
\n

This is a really great book. I think it will be very helpful to many people. I\u2019m definitely going to recommend it to beginners.

\n
\n
\n
\n \"Taras\n
\n
\n — Taras Mankowski\n EmberSherpa\n
\n
\n
\n
\n

The book guides you through the steps of building a real application so that you can see how the concepts are applied in practice. You'll learn about the building blocks of Ember one by one, in a way that crushes the steep learning curve. Knowledge is dripped in slowly, chapter by chapter, to prevent you from drowning in a sea of novel information. By improving an existing and working application, you will learn more quickly and new knowledge will sink in deeper.

\n

Already convinced? Skip to the packages.

\n
\n\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n \"Sample\n
\n
\n
\n
\n

Want to read a sample chapter first?

\n \n
\n\n
\n \n \n
\n \n \n
\n
\n

There was an error submitting your subscription. Please try again.

\n
\n
\n
\n \n \n
\n
\n \n \n
\n \n We won't send you spam. Unsubscribe at any time.\n
\n
\n
\n
\n\n
\n
\n
\n
\n \n \n \n\n \n
\n
\n
\n
\n \n
\n
\n

Once upon a time...

\n
\n
\n
\n\n
\n

\n It all started in September 2013. Having just returned from the first European\n Ember.js conference, my enthusiasm went through the roof. I wanted to spread the\n word, for people to realize how beautiful Ember is, for them to know\n that Ember.js is not that hard to learn. It's just a matter of having the core\n concepts internalized.\n

\n

\n So without proper equipment (and after a few episodes, with a ~$80 mic) I started producing screencasts, a series in\n which a simple application is developed step-by-step. I sent the first few to my\n subscribers and kept producing them. And people seemed to have liked them.\n

\n\n
\n
\n
\n
\n
\n

Great episode! Pace and depth was perfect. Thanks for such a great webcast series!

\n
\n
\n
\n \"Curtis\n
\n
\n — Curtis Wallen\n
\n
\n
\n
\n\n
\n
\n
\n

I really appreciate the effort you want to put up. Just wanted to thank you for this and let you know that your video series rock!

\n
\n
\n
\n \"Antonio\n
\n
\n — Antonio Antillon\n
\n
\n
\n
\n
\n
\n\n

\n Once the screencast series was finished, I switched to blog posts and lengthier\n articles, and in 2014 I committed to posting something of\n value each week. Then, after a long labor of (mostly) love,\n I published the 1st edition of the book in Feburary\n 2015, that used the then stable Ember version, 1.10.\n

\n

\n I was not done, though. As Ember made progress in a\n neck breaking pace, I kept the book up-to-date with the\n actual stable version of the framework, and adding material\n that covered the new features.\n

\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n \n
\n
\n

Buy once, get all updates for free

\n
\n
\n
\n\n
\n

The first edition of this book followed Ember's journey to\n its 2.0 release. As Ember gracefully shedded old syntaxes, the\n book's content was updated not to use those syntaxes, either.\n When a new feature appeared, I added a section about it, trying\n to find a practical example for it in the application.

\n\n

Since Ember follows a 6-week release cycle, that meant\n frequent book updates, precisely 8 \"minor book releases\" in a\n little less than 7 months. These updates came free for all of my\n customers, no matter which package they chose. I aim to follow a\n similar path and update policy with Ember 2.x. The framework\n makes progress really fast but I'll keep in sync with the latest\n stable version of Ember and keep the content fresh. And\n free until at least the next major version.

\n
\n
\n\n
\n
\n
\n
\n
\n

I really like it! It is super difficult to find the right balance between pacing and detail\nand put it all together in an understandable form but you pulled it off.

\n
\n
\n
\n \"Cory\n
\n
\n — Cory Forsyth\n 201 Created\n
\n
\n
\n
\n\n
\n
\n
\n

Just wanted to say thanks for the ongoing updates of the book. Even after finishing the book, it\u2019s becoming a great reference for the changes Ember is going through (even more so than the official docs).

\n
\n
\n
\n \"Gabriel\n
\n
\n — Gabriel Rotbart\n
\n
\n
\n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n
\n

Table of Contents

\n
\n
\n
\n
\n\n
\n
\n
\n \n
\n
    \n
  • Preface\n\n
      \n
    • My love affair with Ember.js
    • \n
    • Acknowledgements
    • \n
  • \n
  • Introduction to Ember.js\n\n
      \n
    • Why Ember.js
    • \n
    • Backstage - Dial M for Model
    • \n
    • About this book
    • \n
    • Is this book for you?
    • \n
    • Ambitious goal for an ambitious framework
    • \n
    • The application we are going to build
    • \n
    • Errata
    • \n
  • \n
  • Ember CLI\n\n
      \n
    • Setting up Ember CLI
    • \n
    • Creating our application
    • \n
  • \n
  • Templates and data bindings\n\n
      \n
    • The first template
    • \n
    • Showing a list of songs in the application template
    • \n
    • Backstage - Handlebar's fail-softness
    • \n
    • Backstage - ES2015 modules
    • \n
    • Backstage - Class and instance properties
    • \n
    • Adding libraries to the build
    • \n
    • Importing needed assets manually
    • \n
    • Using an Ember add-on
    • \n
    • Auto-updating templates
    • \n
  • \n
  • Routing\n\n
      \n
    • What do we want to achieve?
    • \n
    • New styles
    • \n
    • Routes set up data
    • \n
    • Backstage - A word about generated test files
    • \n
    • Moving around with link-to
    • \n
    • Using the model property
    • \n
    • Showing a list of bands
    • \n
    • Showing a list of songs
    • \n
  • \n
  • Nested routes\n\n
      \n
    • Defining the nested routes
    • \n
    • Full route names
    • \n
    • Backstage - Resource routes
    • \n
    • Stepping through a router transition
    • \n
    • Backstage - Computed properties
    • \n
    • Nested templates
    • \n
    • {{outlet}} is the default template for routes
    • \n
  • \n
  • Actions\n\n
      \n
    • Extracting model classes
    • \n
    • The class-level mutable attribute property
    • \n
    • Capturing the event
    • \n
    • Turning event into intent
    • \n
  • \n
  • Components\n\n
      \n
    • The idea behind components
    • \n
    • Component specification
    • \n
    • Defining the component's properties
    • \n
    • Using the component
    • \n
    • Displaying the rating with stars
    • \n
    • Backstage - The default component template
    • \n
    • Backstage - On the utility of explicit dependency definitions
    • \n
    • Speaking to the outside world through actions
    • \n
    • Closure actions
    • \n
  • \n
  • Controllers\n\n
      \n
    • Preventing the creation of bands without a name
    • \n
    • Smooth UI flows
    • \n
    • Going to the band page after it is created
    • \n
    • Nudging the user to create the first song
    • \n
    • Showing the text field when the call to action has been acted on
    • \n
    • Creating new bands and songs by pressing return
    • \n
    • Backstage - Where to handle actions?
    • \n
  • \n
  • Advanced routing\n\n
      \n
    • Route hooks
    • \n
    • Route actions
    • \n
    • Redirection
    • \n
    • Redirecting before the model is known
    • \n
    • Redirecting after the model is known
    • \n
    • Backstage - Skipping model resolution
    • \n
    • Leaving routes and arriving at them
    • \n
    • Setting descriptive page titles
    • \n
    • Warning about losing data
    • \n
  • \n
  • Talking to a backend - with Ember Data\n\n
      \n
    • The concept behind Ember Data
    • \n
    • The API
    • \n
    • Model classes
    • \n
    • Transforming the app to use Ember Data
    • \n
    • Loading bands
    • \n
    • Fetching a single band
    • \n
    • Loading songs for a band
    • \n
    • Creating a band
    • \n
    • Updating a band's description
    • \n
    • Updating song ratings
    • \n
    • Backstage - Promises
    • \n
  • \n
  • Testing\n\n
      \n
    • Clarifying the vocabulary
    • \n
    • Acceptance tests
    • \n
    • To mock or not to mock?
    • \n
    • Unit tests
    • \n
    • Integration tests
    • \n
    • Adding an acceptance test
    • \n
    • Analyzing an Ember acceptance test
    • \n
    • Making the first test pass
    • \n
    • Safeguarding critical user scenarios
    • \n
    • Creating a band
    • \n
    • Creating a song
    • \n
    • Backstage \u2013 Fake synchronous tests
    • \n
    • Writing your own test helpers
    • \n
    • Registering a synchronous helper
    • \n
    • Registering an async helper
    • \n
    • Refactoring stubs
    • \n
    • Integration tests in Ember
    • \n
    • Unit tests in Ember
    • \n
  • \n
  • Sorting and searching with query parameters\n\n
      \n
    • Query parameters
    • \n
    • Query parameters in Ember
    • \n
    • Sorting the list of songs
    • \n
    • Sorting an array of items
    • \n
    • Backstage - Computed property macros
    • \n
    • Changing the sorting criteria
    • \n
    • Filtering songs by a search term
    • \n
    • Adding a dash of query parameters
    • \n
    • Using links instead of buttons
    • \n
    • Taking a look at what we made
    • \n
  • \n
  • Loading and error routes\n\n
      \n
    • Loading routes
    • \n
    • Backstage - Rendering the loading template is an overridable default
    • \n
    • Error routes
    • \n
  • \n
  • Helpers\n\n
      \n
    • About helpers
    • \n
    • Capitalizing each word of a name
    • \n
    • Using it in templates, or elsewhere
    • \n
    • Use dashed names for helpers
    • \n
  • \n
  • Animations\n\n
      \n
    • Setting up liquid-fire
    • \n
    • liquid-fire architecture
    • \n
    • Transition map
    • \n
    • Transition functions
    • \n
    • Template helpers
    • \n
    • Putting it all together
    • \n
    • Debugging transitions
    • \n
    • Animate moving between routes
    • \n
    • Adding a custom animation
    • \n
    • Animate a value change
    • \n
  • \n
  • Making an Ember addon\n\n
      \n
    • What is an Ember addon?
    • \n
    • Developing the addon
    • \n
    • Integrating our addon into our app
    • \n
    • Adding a block form
    • \n
    • Customizing the star-rating component's look and behavior
    • \n
    • Publishing the addon
    • \n
    • Using a published addon from the app
    • \n
  • \n
  • ES2015 - Writing modern JavaScript\n\n
      \n
    • Modernizing the app
    • \n
    • Modules
    • \n
    • Template strings
    • \n
    • Short-hand method definitions
    • \n
    • Replacing var (let & const)
    • \n
    • Arrow functions
    • \n
    • Destructuring
    • \n
    • Other useful ES2015 features
    • \n
    • Backstage - ember-watson
    • \n
    • Computed property macros
    • \n
  • \n
  • Deployment\n\n
      \n
    • FrontPage
    • \n
    • Heroku
    • \n
    • ember-cli-deploy
    • \n
  • \n
  • Afterword\n\n
      \n
    • Your journey with Ember.js
    • \n
  • \n
\n\n
\n\n
\n
\n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n \"Balint\n
\n\n
\n

About me

\n

Hello there, I'm Balint Erdi.

\n

\n I have a long history of building web applications and have mostly been a back-end\n guy.\n

\n

\n On a grey, chilly February day in 2013 that I\u2019ll never forget (maybe it was\n January?) I got acquainted with Ember.js. Ember.js made that day bright and the\n ones that came after that. After learning the ropes I shifted gears and have been\n proselytizing for Ember since last summer.\n

\n

\n I gave a beginner\u2019s workshop at Eurucamp, and held presentations at Arrrrcamp, The Geek Gathering and EmberFest. I started an Ember.js mailing list, made an introductory\n screencast series and have been sending Ember content to my dear subscribers on a\n weekly basis. I have also written guest articles for Safari Books Online, Firebase\n and Toptal.\n

\n

\n I guess you could say I\u2019m pretty passionate about Ember.\n

\n

\n Oh, and I love rock & roll, obviously.\n

\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n \n
\n
\n

Bonus: Exclusive hack.hands() deal

\n
\n
\n
\n
\n

\n hack.hands()\n is your SOS button for live programming support, available 24/7. hack.hands() instantly connects developers with a network of expert programmers at the click of a button. Never get stuck, learn more and keep coding!\n If you buy any package, you will receive $25 to spend on their platform that you can use to get your Ember project unstuck.\n

\n
\n
\n\n
\n
\n
\n
\n
\n

Even though I have worked with Ember for the past 6 months, the book helped clarify a lot of things, especially new features and their deprecated counterparts. Such a great book, and looking forward to the second one!

\n
\n
\n
\n \"David\n
\n
\n — David Tang\n
\n
\n
\n
\n\n
\n
\n
\n

There is almost nowhere to go to get a good grounding in Ember. In months of searching this is the best resource that exists... so much so I'm going to try to get a few copies sorted out for my team at work. Thanks Balint!

\n
\n
\n
\n \"\n
\n
\n — Andy Davison\n
\n
\n
\n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n

Stairway to Heaven Package

\n
\n
\n
\n\n
\n
\n

\n The path to Ember.js bliss, this package contains all you need to take your Ember.js skills to the next level. It contains:

\n \"Stairway\n

\n
\n
\n
\n\n
\n
\n
\n
\n
\n

This was a truly great series of screencasts. Very, very well done. Simple enough while not being simplistic.

\n
\n
\n
\n \"Claude\n
\n
\n — Claude Pr\u00e9court\n
\n
\n
\n
\n\n
\n
\n
\n

Nice work with these Ember tutorials. You're doing a really nice thing for the community.

\n
\n
\n
\n \"Steven\n
\n
\n — Steven Kane\n
\n
\n
\n
\n
\n
\n
\n \n
\n
\n
\n
\n
\n
\n
\n \"The\n
\n

The book

\n 18 chapters\n

This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

\n
\n
\n\n
\n
\n
\n \"Code\"\n
\n

Access to the code

\n All of the source code\n

in the application so that you can check how the app looks & works at each step. Or tweak it to your liking.

\n
\n
\n\n
\n
\n
\n \"Screencast\"\n
\n

Screencasts

\n 4 screencasts\n

They run around 10 minutes each and cover the following,\n advanced topics: Pods in Ember CLI, Animations,\n Authentication & Authorization, and ES2015 &\n computed macros.

\n
\n
\n\n
\n
\n
\n \"Rock\n
\n

Rock & More

\n Includes\n

$25 credit on the hack.hands() platform

\n

60-day refund guarantee

\n
\n
\n
\n
\n\n
\n \n
\n\n
\n
\n\n \n
\n
\n
\n
\n
\n

Light my Fire Package

\n
\n
\n
\n\n
\n
\n

\n Take out the screencasts and you have this smaller package that will still ignite your Ember rocket. It contains:\n \"Light\n

\n
\n
\n
\n
\n\n
\n
\n
\n
\n
\n
\n
\n \"The\n
\n

The book

\n 18 chapters\n

This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

\n
\n
\n\n
\n
\n
\n \"Code\"\n
\n

Access to the code

\n All of the source code\n

in the application so that you can check how the app looks & works at each step. Or tweak it to your liking.

\n
\n
\n\n
\n
\n
\n \"Rock\n
\n

Rock & More

\n Includes\n

$25 credit on the hack.hands() platform

\n

60-day refund guarantee

\n
\n
\n
\n
\n\n
\n \n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n

Smoke on the Water Package

\n
\n
\n
\n\n
\n
\n

\n Basic but still solid, as the name suggests. This package inclues the book and the hack.hands() deal. It contains:\n

\n \"Smoke\n

\n
\n
\n
\n
\n\n
\n
\n
\n
\n
\n
\n
\n \"The\n
\n

The book

\n 18 chapters\n

This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

\n
\n
\n\n
\n
\n
\n \"Rock\n
\n

Rock & More

\n Includes\n

$25 credit on the hack.hands() platform

\n

60-day refund guarantee

\n
\n
\n\n
\n
\n\n
\n \n
\n\n
\n
\n
\n
\n
\n

I\u2019m REALLY enjoying the book and find it to be very thorough and informative. You\u2019ve done a great job of answering questions I had about various concepts that were not detailed clearly elsewhere.

\n
\n
\n
\n \"Bill\n
\n
\n — Bill White\n Data Visualizations at www.bildwhite.com\n
\n
\n
\n
\n\n
\n
\n
\n

It\u2019s been an invaluable resource in learning Ember and one I would recommend to any developer wanting to get started with the framework.

\n
\n
\n
\n \"Jonathan\n
\n
\n — Jonathan Rowley\n
\n
\n
\n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n \n
\n
\n

Hmm, I\u2019m not sure...

\n
\n
\n
\n\n
\n
    \n
  • \n

    Is the book ready for Ember 2?

    \n

    \n Yes, it is! The app in the book runs Ember (and Ember Data)\n 2 and does not use any deprecated stuff.\n

    \n
  • \n\n
  • \n

    Is this book for me?

    \n

    \n The book starts from the very basics (installing\n ember-cli, writing your first template, etc.) so if you\n completely get Ember, this book is probably not for you. If\n you are just starting out (or about to) or want to\n understand fundamental concepts in Ember, the book is\n definitely for you.\n

    \n
  • \n\n
  • \n

    What if I don't like the book?

    \n

    \n I offer a 60-day moneyback guarantee. No strings attached,\n just send your purchase receipt (or email address) to\n rarwe-book@balinterdi.com or answer to the welcome email\n that you received when you purchased.\n

    \n
  • \n\n
  • \n

    Everything is changing so fast; won't the content be outdated by next week?

    \n

    \n As Ember.js moves towards 3.0, I will keep updating the\n content of the book so that it stays void of deprecation\n warnings and does not promote practices that are no longer\n considered idiomatic. For the 1st edition of the book,\n I released an update once about every four weeks,\n more often than Ember stable versions came out.\n Expect the same for the this book edition.\n

    \n
  • \n\n
  • \n

    I heard Ember is so hard. Will this book help me understand it?

    \n

    \n I think there are a handful of key concepts in Ember.js\n that you need to understand to master it (probably the main\n one among these is routing). Once you understand these,\n Ember is not that hard. The intention of the book is\n to introduce concepts by way of building an actual\n application, so you see them applied in practice right away.\n That also helps the learning process. I also encourage you\n to work through the book as you read it, since that makes\n things sink in even deeper. You have access to the code\n repository if you have purchased the middle- or\n high-tier package. If I failed to explain Ember for you, please\n send me your purchase receipt to rarwe-book@balinterdi.com\n within 60 days of purchase and I\u2019ll issue a refund.\n

    \n
  • \n\n
  • \n

    Is the book DRM protected?

    \n

    \n No, it\u2019s not. If you would like to share it with\n colleagues (or a class), please contact me at rarwe-book@balinterdi.com.

    \n
  • \n\n
  • \n

    What if I buy the book-only package and later realize I want to switch to a higher package?

    \n

    No problem! Just send me your purchase receipt to rarwe-book@balinterdi.com, and I will upgrade you for the difference between the package prices.

    \n
  • \n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n \"60-day\n
\n\n \n
\n
\n

Choose a Package

\n
\n
\n
\n
\n\n
\n
\n
    \n
  • \n

    Smoke on the Water

    \n
    \n
    \n $39\n
    \n
    \n
      \n
    • The book with 18 chapters
    • \n
    • Free book updates until 3.0
    • \n
    • $25 credit for hack.hands()
    • \n
    • 60-days money back guarantee
    • \n
    • Rock & Roll!
    • \n
    • \n
    • \n
    \n
    \n Buy Now\n
    \n
  • \n
  • \n

    Light my Fire

    \n
    \n
    \n $59\n
    \n
    \n
      \n
    • The book with 18 chapters
    • \n
    • Free book updates until 3.0
    • \n
    • Access to the code
    • \n
    • $25 credit for hack.hands()
    • \n
    • 60-days money back guarantee
    • \n
    • Rock & Roll!
    • \n
    • \n
    \n
    \n Buy Now\n
    \n
  • \n
  • \n

    Stairway to Heaven

    \n
    \n
    \n $89\n
    \n
    \n
      \n
    • The book with 18 chapters
    • \n
    • Free book updates until 3.0
    • \n
    • Access to the code
    • \n
    • 4 Screencasts
    • \n
    • $25 credit for hack.hands()
    • \n
    • 60-days money back guarantee
    • \n
    • Rock & Roll!
    • \n
    \n
    \n Buy Now\n
    \n
  • \n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n\n
\n
\n

This book is a fabulous, approachable, foray into Emberjs that makes the learning curve much less scary. I just wish it had been available sooner for students in my previous classes.

\n
\n
\n
\n \"Matt\n
\n
\n — Matt Hale\n Assistant Professor at the University of Nebraska\n
\n
\n
\n
\n\n
\n
\n
\n

I\u2019ve gone through the first four chapters and I am already loving it.

\n
\n
\n
\n \"Sergio\n
\n
\n — Sergio Arbeo\n EmberMadrid\n
\n
\n
\n
\n
\n
\n
\n \n\n \n \n \n\n \n\n \n \n \n \n\n \n \n\n\n\n"}, "files_after": {"source/_layouts/rarwe_book.html": "\n\n\n\n \n \n \n \n\n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n Cut your learning curve and build ambitious apps with Ember.js.\n\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n\n\n\n
\n\n \n
\n
\n\n
\n
\n

The most up-to-date book to learn Ember.js

\n
\n Trusted by:\n \"Toptal\"\n \"Firebase\"\n \"Airpair\"\n \"Nathan\n
\n
\n
\n\n
\n
\n
\n \"Rock\n
\n
\n
\n
\n

Build ambitious apps with confidence

\n

Ember.js is a kick-ass framework for building\n web applications. It's the only tool you need\n (on the client-side) to craft your idea into a working\n wonder. However, its strong opinions and heavy reliance of\n \u201cconvention over configuration\u201d can give developers who\n are new to the framework a hard time figuring out how\n Ember wants them to do things.

\n\n

This book helps to overcome that initial\n frustration, and help you grok Ember a lot\n faster, by pinpointing the core concepts and\n explaining them in detail. Once you understand them you\n are on your way to taming and mastering Ember.js.\n So don't fear the learning curve.

\n\n
\n
\n
\n

This is a really great book. I think it will be very helpful to many people. I\u2019m definitely going to recommend it to beginners.

\n
\n
\n
\n \"Taras\n
\n
\n — Taras Mankowski\n EmberSherpa\n
\n
\n
\n
\n

The book guides you through the steps of building a real application so that you can see how the concepts are applied in practice. You'll learn about the building blocks of Ember one by one, in a way that crushes the steep learning curve. Knowledge is dripped in slowly, chapter by chapter, to prevent you from drowning in a sea of novel information. By improving an existing and working application, you will learn more quickly and new knowledge will sink in deeper.

\n

Already convinced? Skip to the packages.

\n
\n\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n \"Sample\n
\n
\n
\n
\n

Want to read a sample chapter first?

\n \n
\n\n
\n \n \n
\n \n \n
\n
\n

There was an error submitting your subscription. Please try again.

\n
\n
\n
\n \n \n
\n
\n \n \n
\n \n We won't send you spam. Unsubscribe at any time.\n
\n
\n
\n
\n\n
\n
\n
\n
\n \n \n \n\n \n
\n
\n
\n
\n \n
\n
\n

Once upon a time...

\n
\n
\n
\n\n
\n

\n It all started in September 2013. Having just returned from the first European\n Ember.js conference, my enthusiasm went through the roof. I wanted to spread the\n word, for people to realize how beautiful Ember is, for them to know\n that Ember.js is not that hard to learn. It's just a matter of having the core\n concepts internalized.\n

\n

\n So without proper equipment (and after a few episodes, with a ~$80 mic) I started producing screencasts, a series in\n which a simple application is developed step-by-step. I sent the first few to my\n subscribers and kept producing them. And people seemed to have liked them.\n

\n\n
\n
\n
\n
\n
\n

Great episode! Pace and depth was perfect. Thanks for such a great webcast series!

\n
\n
\n
\n \"Curtis\n
\n
\n — Curtis Wallen\n
\n
\n
\n
\n\n
\n
\n
\n

I really appreciate the effort you want to put up. Just wanted to thank you for this and let you know that your video series rock!

\n
\n
\n
\n \"Antonio\n
\n
\n — Antonio Antillon\n
\n
\n
\n
\n
\n
\n\n

\n Once the screencast series was finished, I switched to blog posts and lengthier\n articles, and in 2014 I committed to posting something of\n value each week. Then, after a long labor of (mostly) love,\n I published the 1st edition of the book in Feburary\n 2015, that used the then stable Ember version, 1.10.\n

\n

\n I was not done, though. As Ember made progress in a\n neck breaking pace, I kept the book up-to-date with the\n actual stable version of the framework, and adding material\n that covered the new features.\n

\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n \n
\n
\n

Buy once, get all updates for free

\n
\n
\n
\n\n
\n

The first edition of this book followed Ember's journey to\n its 2.0 release. As Ember gracefully shedded old syntaxes, the\n book's content was updated not to use those syntaxes, either.\n When a new feature appeared, I added a section about it, trying\n to find a practical example for it in the application.

\n\n

Since Ember follows a 6-week release cycle, that meant\n frequent book updates, precisely 8 \"minor book releases\" in a\n little less than 7 months. These updates came free for all of my\n customers, no matter which package they chose. I aim to follow a\n similar path and update policy with Ember 2.x. The framework\n makes progress really fast but I'll keep in sync with the latest\n stable version of Ember and keep the content fresh. And\n free until at least the next major version.

\n
\n
\n\n
\n
\n
\n
\n
\n

I really like it! It is super difficult to find the right balance between pacing and detail\nand put it all together in an understandable form but you pulled it off.

\n
\n
\n
\n \"Cory\n
\n
\n — Cory Forsyth\n 201 Created\n
\n
\n
\n
\n\n
\n
\n
\n

Just wanted to say thanks for the ongoing updates of the book. Even after finishing the book, it\u2019s becoming a great reference for the changes Ember is going through (even more so than the official docs).

\n
\n
\n
\n \"Gabriel\n
\n
\n — Gabriel Rotbart\n
\n
\n
\n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n
\n

Table of Contents

\n
\n
\n
\n
\n\n
\n
\n
\n \n
\n
    \n
  • Preface\n\n
      \n
    • My love affair with Ember.js
    • \n
    • Acknowledgements
    • \n
  • \n
  • Introduction to Ember.js\n\n
      \n
    • Why Ember.js
    • \n
    • Backstage - Dial M for Model
    • \n
    • About this book
    • \n
    • Is this book for you?
    • \n
    • Ambitious goal for an ambitious framework
    • \n
    • The application we are going to build
    • \n
    • Errata
    • \n
  • \n
  • Ember CLI\n\n
      \n
    • Setting up Ember CLI
    • \n
    • Creating our application
    • \n
  • \n
  • Templates and data bindings\n\n
      \n
    • The first template
    • \n
    • Showing a list of songs in the application template
    • \n
    • Backstage - Handlebar's fail-softness
    • \n
    • Backstage - ES2015 modules
    • \n
    • Backstage - Class and instance properties
    • \n
    • Adding libraries to the build
    • \n
    • Importing needed assets manually
    • \n
    • Using an Ember add-on
    • \n
    • Auto-updating templates
    • \n
  • \n
  • Routing\n\n
      \n
    • What do we want to achieve?
    • \n
    • New styles
    • \n
    • Routes set up data
    • \n
    • Backstage - A word about generated test files
    • \n
    • Moving around with link-to
    • \n
    • Using the model property
    • \n
    • Showing a list of bands
    • \n
    • Showing a list of songs
    • \n
  • \n
  • Nested routes\n\n
      \n
    • Defining the nested routes
    • \n
    • Full route names
    • \n
    • Backstage - Resource routes
    • \n
    • Stepping through a router transition
    • \n
    • Backstage - Computed properties
    • \n
    • Nested templates
    • \n
    • {{outlet}} is the default template for routes
    • \n
  • \n
  • Actions\n\n
      \n
    • Extracting model classes
    • \n
    • The class-level mutable attribute property
    • \n
    • Capturing the event
    • \n
    • Turning event into intent
    • \n
  • \n
  • Components\n\n
      \n
    • The idea behind components
    • \n
    • Component specification
    • \n
    • Defining the component's properties
    • \n
    • Using the component
    • \n
    • Displaying the rating with stars
    • \n
    • Backstage - The default component template
    • \n
    • Backstage - On the utility of explicit dependency definitions
    • \n
    • Speaking to the outside world through actions
    • \n
    • Closure actions
    • \n
  • \n
  • Controllers\n\n
      \n
    • Preventing the creation of bands without a name
    • \n
    • Smooth UI flows
    • \n
    • Going to the band page after it is created
    • \n
    • Nudging the user to create the first song
    • \n
    • Showing the text field when the call to action has been acted on
    • \n
    • Creating new bands and songs by pressing return
    • \n
    • Backstage - Where to handle actions?
    • \n
  • \n
  • Advanced routing\n\n
      \n
    • Route hooks
    • \n
    • Route actions
    • \n
    • Redirection
    • \n
    • Redirecting before the model is known
    • \n
    • Redirecting after the model is known
    • \n
    • Backstage - Skipping model resolution
    • \n
    • Leaving routes and arriving at them
    • \n
    • Setting descriptive page titles
    • \n
    • Warning about losing data
    • \n
  • \n
  • Talking to a backend - with Ember Data\n\n
      \n
    • The concept behind Ember Data
    • \n
    • The API
    • \n
    • Model classes
    • \n
    • Transforming the app to use Ember Data
    • \n
    • Loading bands
    • \n
    • Fetching a single band
    • \n
    • Loading songs for a band
    • \n
    • Creating a band
    • \n
    • Updating a band's description
    • \n
    • Updating song ratings
    • \n
    • Backstage - Promises
    • \n
  • \n
  • Testing\n\n
      \n
    • Clarifying the vocabulary
    • \n
    • Acceptance tests
    • \n
    • To mock or not to mock?
    • \n
    • Unit tests
    • \n
    • Integration tests
    • \n
    • Adding an acceptance test
    • \n
    • Analyzing an Ember acceptance test
    • \n
    • Making the first test pass
    • \n
    • Safeguarding critical user scenarios
    • \n
    • Creating a band
    • \n
    • Creating a song
    • \n
    • Backstage \u2013 Fake synchronous tests
    • \n
    • Writing your own test helpers
    • \n
    • Registering a synchronous helper
    • \n
    • Registering an async helper
    • \n
    • Refactoring stubs
    • \n
    • Integration tests in Ember
    • \n
    • Unit tests in Ember
    • \n
  • \n
  • Sorting and searching with query parameters\n\n
      \n
    • Query parameters
    • \n
    • Query parameters in Ember
    • \n
    • Sorting the list of songs
    • \n
    • Sorting an array of items
    • \n
    • Backstage - Computed property macros
    • \n
    • Changing the sorting criteria
    • \n
    • Filtering songs by a search term
    • \n
    • Adding a dash of query parameters
    • \n
    • Using links instead of buttons
    • \n
    • Taking a look at what we made
    • \n
  • \n
  • Loading and error routes\n\n
      \n
    • Loading routes
    • \n
    • Backstage - Rendering the loading template is an overridable default
    • \n
    • Error routes
    • \n
  • \n
  • Helpers\n\n
      \n
    • About helpers
    • \n
    • Capitalizing each word of a name
    • \n
    • Using it in templates, or elsewhere
    • \n
    • Use dashed names for helpers
    • \n
  • \n
  • Animations\n\n
      \n
    • Setting up liquid-fire
    • \n
    • liquid-fire architecture
    • \n
    • Transition map
    • \n
    • Transition functions
    • \n
    • Template helpers
    • \n
    • Putting it all together
    • \n
    • Debugging transitions
    • \n
    • Animate moving between routes
    • \n
    • Adding a custom animation
    • \n
    • Animate a value change
    • \n
  • \n
  • Making an Ember addon\n\n
      \n
    • What is an Ember addon?
    • \n
    • Developing the addon
    • \n
    • Integrating our addon into our app
    • \n
    • Adding a block form
    • \n
    • Customizing the star-rating component's look and behavior
    • \n
    • Publishing the addon
    • \n
    • Using a published addon from the app
    • \n
  • \n
  • ES2015 - Writing modern JavaScript\n\n
      \n
    • Modernizing the app
    • \n
    • Modules
    • \n
    • Template strings
    • \n
    • Short-hand method definitions
    • \n
    • Replacing var (let & const)
    • \n
    • Arrow functions
    • \n
    • Destructuring
    • \n
    • Other useful ES2015 features
    • \n
    • Backstage - ember-watson
    • \n
    • Computed property macros
    • \n
  • \n
  • Deployment\n\n
      \n
    • FrontPage
    • \n
    • Heroku
    • \n
    • ember-cli-deploy
    • \n
  • \n
  • Afterword\n\n
      \n
    • Your journey with Ember.js
    • \n
  • \n
\n\n
\n\n
\n
\n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n \"Balint\n
\n\n
\n

About me

\n

Hello there, I'm Balint Erdi.

\n

\n I have a long history of building web applications and have mostly been a back-end\n guy.\n

\n

\n On a grey, chilly February day in 2013 that I\u2019ll never forget (maybe it was\n January?) I got acquainted with Ember.js. Ember.js made that day bright and the\n ones that came after that. After learning the ropes I shifted gears and have been\n proselytizing for Ember since last summer.\n

\n

\n I gave a beginner\u2019s workshop at Eurucamp, and held presentations at Arrrrcamp, The Geek Gathering and EmberFest. I started an Ember.js mailing list, made an introductory\n screencast series and have been sending Ember content to my dear subscribers on a\n weekly basis. I have also written guest articles for Safari Books Online, Firebase\n and Toptal.\n

\n

\n I guess you could say I\u2019m pretty passionate about Ember.\n

\n

\n Oh, and I love rock & roll, obviously.\n

\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n \n
\n
\n

Bonus: Exclusive hack.hands() deal

\n
\n
\n
\n
\n

\n hack.hands()\n is your SOS button for live programming support, available 24/7. hack.hands() instantly connects developers with a network of expert programmers at the click of a button. Never get stuck, learn more and keep coding!\n If you buy any package, you will receive $25 to spend on their platform that you can use to get your Ember project unstuck.\n

\n
\n
\n\n
\n
\n
\n
\n
\n

Even though I have worked with Ember for the past 6 months, the book helped clarify a lot of things, especially new features and their deprecated counterparts. Such a great book, and looking forward to the second one!

\n
\n
\n
\n \"David\n
\n
\n — David Tang\n
\n
\n
\n
\n\n
\n
\n
\n

There is almost nowhere to go to get a good grounding in Ember. In months of searching this is the best resource that exists... so much so I'm going to try to get a few copies sorted out for my team at work. Thanks Balint!

\n
\n
\n
\n \"\n
\n
\n — Andy Davison\n
\n
\n
\n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n

Stairway to Heaven Package

\n
\n
\n
\n\n
\n
\n

\n The path to Ember.js bliss, this package contains all you need to take your Ember.js skills to the next level. It contains:

\n \"Stairway\n

\n
\n
\n
\n\n
\n
\n
\n
\n
\n

This was a truly great series of screencasts. Very, very well done. Simple enough while not being simplistic.

\n
\n
\n
\n \"Claude\n
\n
\n — Claude Pr\u00e9court\n
\n
\n
\n
\n\n
\n
\n
\n

Nice work with these Ember tutorials. You're doing a really nice thing for the community.

\n
\n
\n
\n \"Steven\n
\n
\n — Steven Kane\n
\n
\n
\n
\n
\n
\n
\n \n
\n
\n
\n
\n
\n
\n
\n \"The\n
\n

The book

\n 18 chapters\n

This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

\n
\n
\n\n
\n
\n
\n \"Code\"\n
\n

Access to the code

\n All of the source code\n

in the application so that you can check how the app looks & works at each step. Or tweak it to your liking.

\n
\n
\n\n
\n
\n
\n \"Screencast\"\n
\n

Screencasts

\n 4 screencasts\n

They run around 10 minutes each and cover the following,\n advanced topics: Pods in Ember CLI, Animations,\n Authentication & Authorization, and ES2015 &\n computed macros.

\n
\n
\n\n
\n
\n
\n \"Rock\n
\n

Rock & More

\n Includes\n

$25 credit on the hack.hands() platform

\n

60-day refund guarantee

\n
\n
\n
\n
\n\n
\n \n
\n\n
\n
\n\n \n
\n
\n
\n
\n
\n

Light my Fire Package

\n
\n
\n
\n\n
\n
\n

\n Take out the screencasts and you have this smaller package that will still ignite your Ember rocket. It contains:\n \"Light\n

\n
\n
\n
\n
\n\n
\n
\n
\n
\n
\n
\n
\n \"The\n
\n

The book

\n 18 chapters\n

This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

\n
\n
\n\n
\n
\n
\n \"Code\"\n
\n

Access to the code

\n All of the source code\n

in the application so that you can check how the app looks & works at each step. Or tweak it to your liking.

\n
\n
\n\n
\n
\n
\n \"Rock\n
\n

Rock & More

\n Includes\n

$25 credit on the hack.hands() platform

\n

60-day refund guarantee

\n
\n
\n
\n
\n\n
\n \n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n

Smoke on the Water Package

\n
\n
\n
\n\n
\n
\n

\n Basic but still solid, as the name suggests. This package inclues the book and the hack.hands() deal. It contains:\n

\n \"Smoke\n

\n
\n
\n
\n
\n\n
\n
\n
\n
\n
\n
\n
\n \"The\n
\n

The book

\n 18 chapters\n

This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

\n
\n
\n\n
\n
\n
\n \"Rock\n
\n

Rock & More

\n Includes\n

$25 credit on the hack.hands() platform

\n

60-day refund guarantee

\n
\n
\n\n
\n
\n\n
\n \n
\n\n
\n
\n
\n
\n
\n

I\u2019m REALLY enjoying the book and find it to be very thorough and informative. You\u2019ve done a great job of answering questions I had about various concepts that were not detailed clearly elsewhere.

\n
\n
\n
\n \"Bill\n
\n
\n — Bill White\n Data Visualizations at www.bildwhite.com\n
\n
\n
\n
\n\n
\n
\n
\n

It\u2019s been an invaluable resource in learning Ember and one I would recommend to any developer wanting to get started with the framework.

\n
\n
\n
\n \"Jonathan\n
\n
\n — Jonathan Rowley\n
\n
\n
\n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n \n
\n
\n

Hmm, I\u2019m not sure...

\n
\n
\n
\n\n
\n
    \n
  • \n

    Is the book ready for Ember 2?

    \n

    \n Yes, it is! The app in the book runs Ember (and Ember Data)\n 2 and does not use any deprecated stuff.\n

    \n
  • \n\n
  • \n

    Is this book for me?

    \n

    \n The book starts from the very basics (installing\n ember-cli, writing your first template, etc.) so if you\n completely get Ember, this book is probably not for you. If\n you are just starting out (or about to) or want to\n understand fundamental concepts in Ember, the book is\n definitely for you.\n

    \n
  • \n\n
  • \n

    What if I don't like the book?

    \n

    \n I offer a 60-day moneyback guarantee. No strings attached,\n just send your purchase receipt (or email address) to\n rarwe-book@balinterdi.com or answer to the welcome email\n that you received when you purchased.\n

    \n
  • \n\n
  • \n

    Everything is changing so fast; won't the content be outdated by next week?

    \n

    \n As Ember.js moves towards 3.0, I will keep updating the\n content of the book so that it stays void of deprecation\n warnings and does not promote practices that are no longer\n considered idiomatic. For the 1st edition of the book,\n I released an update once about every four weeks,\n more often than Ember stable versions came out.\n Expect the same for the this book edition.\n

    \n
  • \n\n
  • \n

    I heard Ember is so hard. Will this book help me understand it?

    \n

    \n I think there are a handful of key concepts in Ember.js\n that you need to understand to master it (probably the main\n one among these is routing). Once you understand these,\n Ember is not that hard. The intention of the book is\n to introduce concepts by way of building an actual\n application, so you see them applied in practice right away.\n That also helps the learning process. I also encourage you\n to work through the book as you read it, since that makes\n things sink in even deeper. You have access to the code\n repository if you have purchased the middle- or\n high-tier package. If I failed to explain Ember for you, please\n send me your purchase receipt to rarwe-book@balinterdi.com\n within 60 days of purchase and I\u2019ll issue a refund.\n

    \n
  • \n\n
  • \n

    Is the book DRM protected?

    \n

    \n No, it\u2019s not. If you would like to share it with\n colleagues (or a class), please contact me at rarwe-book@balinterdi.com.

    \n
  • \n\n
  • \n

    What if I buy the book-only package and later realize I want to switch to a higher package?

    \n

    No problem! Just send me your purchase receipt to rarwe-book@balinterdi.com, and I will upgrade you for the difference between the package prices.

    \n
  • \n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n
\n \"60-day\n
\n\n \n
\n
\n

Choose a Package

\n
\n
\n
\n
\n\n
\n
\n
    \n
  • \n

    Smoke on the Water

    \n
    \n
    \n $39\n
    \n
    \n
      \n
    • The book with 18 chapters
    • \n
    • Free book updates until 3.0
    • \n
    • $25 credit for hack.hands()
    • \n
    • 60-days money back guarantee
    • \n
    • Rock & Roll!
    • \n
    • \n
    • \n
    \n
    \n Buy Now\n
    \n
  • \n
  • \n

    Light my Fire

    \n
    \n
    \n $59\n
    \n
    \n
      \n
    • The book with 18 chapters
    • \n
    • Free book updates until 3.0
    • \n
    • Access to the code
    • \n
    • $25 credit for hack.hands()
    • \n
    • 60-days money back guarantee
    • \n
    • Rock & Roll!
    • \n
    • \n
    \n
    \n Buy Now\n
    \n
  • \n
  • \n

    Stairway to Heaven

    \n
    \n
    \n $89\n
    \n
    \n
      \n
    • The book with 18 chapters
    • \n
    • Free book updates until 3.0
    • \n
    • Access to the code
    • \n
    • 4 Screencasts
    • \n
    • $25 credit for hack.hands()
    • \n
    • 60-days money back guarantee
    • \n
    • Rock & Roll!
    • \n
    \n
    \n Buy Now\n
    \n
  • \n
\n
\n
\n
\n
\n \n\n \n
\n
\n
\n
\n\n
\n
\n

This book is a fabulous, approachable, foray into Emberjs that makes the learning curve much less scary. I just wish it had been available sooner for students in my previous classes.

\n
\n
\n
\n \"Matt\n
\n
\n — Matt Hale\n Assistant Professor at the University of Nebraska\n
\n
\n
\n
\n\n
\n
\n
\n

I\u2019ve gone through the first four chapters and I am already loving it.

\n
\n
\n
\n \"Sergio\n
\n
\n — Sergio Arbeo\n EmberMadrid\n
\n
\n
\n
\n
\n
\n
\n \n\n \n \n \n\n \n\n \n \n \n \n\n \n \n\n\n\n"}} -{"repo": "sebastianbergmann/phpcpd", "pr_number": 206, "title": "Fixing regressed bug-fix for Issue#147", "state": "closed", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["src/CLI/Application.php"], "files_before": {"src/CLI/Application.php": "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nnamespace SebastianBergmann\\PHPCPD;\n\nuse const PHP_EOL;\nuse function count;\nuse function printf;\nuse SebastianBergmann\\FileIterator\\Facade;\nuse SebastianBergmann\\PHPCPD\\Detector\\Detector;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\AbstractStrategy;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\DefaultStrategy;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\StrategyConfiguration;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\SuffixTreeStrategy;\nuse SebastianBergmann\\PHPCPD\\Log\\PMD;\nuse SebastianBergmann\\PHPCPD\\Log\\Text;\nuse SebastianBergmann\\Timer\\ResourceUsageFormatter;\nuse SebastianBergmann\\Timer\\Timer;\nuse SebastianBergmann\\Version;\n\nfinal class Application\n{\n private const VERSION = '7.0';\n\n public function run(array $argv): int\n {\n $this->printVersion();\n\n try {\n $arguments = (new ArgumentsBuilder)->build($argv);\n } catch (Exception $e) {\n print PHP_EOL . $e->getMessage() . PHP_EOL;\n\n return 1;\n }\n\n if ($arguments->version()) {\n return 0;\n }\n\n print PHP_EOL;\n\n if ($arguments->help()) {\n $this->help();\n\n return 0;\n }\n\n $files = (new Facade)->getFilesAsArray(\n $arguments->directories(),\n $arguments->suffixes(),\n '',\n $arguments->exclude()\n );\n\n if (empty($files)) {\n print 'No files found to scan' . PHP_EOL;\n\n return 1;\n }\n\n $config = new StrategyConfiguration($arguments);\n\n try {\n $strategy = $this->pickStrategy($arguments->algorithm(), $config);\n } catch (InvalidStrategyException $e) {\n print $e->getMessage() . PHP_EOL;\n\n return 1;\n }\n\n $timer = new Timer;\n $timer->start();\n\n $clones = (new Detector($strategy))->copyPasteDetection($files);\n\n (new Text)->printResult($clones, $arguments->verbose());\n\n if ($arguments->pmdCpdXmlLogfile()) {\n (new PMD($arguments->pmdCpdXmlLogfile()))->processClones($clones);\n }\n\n print (new ResourceUsageFormatter)->resourceUsage($timer->stop()) . PHP_EOL;\n\n return count($clones) > 0 ? 1 : 0;\n }\n\n private function printVersion(): void\n {\n printf(\n 'phpcpd %s by Sebastian Bergmann.' . PHP_EOL,\n (new Version(self::VERSION, dirname(__DIR__)))->getVersion()\n );\n }\n\n /**\n * @throws InvalidStrategyException\n */\n private function pickStrategy(?string $algorithm, StrategyConfiguration $config): AbstractStrategy\n {\n return match ($algorithm) {\n null, 'rabin-karp' => new DefaultStrategy($config),\n 'suffixtree' => new SuffixTreeStrategy($config),\n default => throw new InvalidStrategyException('Unsupported algorithm: ' . $algorithm),\n };\n }\n\n private function help(): void\n {\n print <<<'EOT'\nUsage:\n phpcpd [options] \n\nOptions for selecting files:\n\n --suffix Include files with names ending in in the analysis\n (default: .php; can be given multiple times)\n --exclude Exclude files with in their path from the analysis\n (can be given multiple times)\n\nOptions for analysing files:\n\n --fuzzy Fuzz variable names\n --min-lines Minimum number of identical lines (default: 5)\n --min-tokens Minimum number of identical tokens (default: 70)\n --algorithm Select which algorithm to use ('rabin-karp' (default) or 'suffixtree')\n --edit-distance Distance in number of edits between two clones (only for suffixtree; default: 5)\n --head-equality Minimum equality at start of clone (only for suffixtree; default 10)\n\nOptions for report generation:\n\n --log-pmd Write log in PMD-CPD XML format to \n\nEOT;\n }\n}\n"}, "files_after": {"src/CLI/Application.php": "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nnamespace SebastianBergmann\\PHPCPD;\n\nuse const PHP_EOL;\nuse function count;\nuse function printf;\nuse SebastianBergmann\\FileIterator\\Facade;\nuse SebastianBergmann\\PHPCPD\\Detector\\Detector;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\AbstractStrategy;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\DefaultStrategy;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\StrategyConfiguration;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\SuffixTreeStrategy;\nuse SebastianBergmann\\PHPCPD\\Log\\PMD;\nuse SebastianBergmann\\PHPCPD\\Log\\Text;\nuse SebastianBergmann\\Timer\\ResourceUsageFormatter;\nuse SebastianBergmann\\Timer\\Timer;\nuse SebastianBergmann\\Version;\n\nfinal class Application\n{\n private const VERSION = '7.0';\n\n public function run(array $argv): int\n {\n $this->printVersion();\n\n try {\n $arguments = (new ArgumentsBuilder)->build($argv);\n } catch (Exception $e) {\n print PHP_EOL . $e->getMessage() . PHP_EOL;\n\n return 1;\n }\n\n if ($arguments->version()) {\n return 0;\n }\n\n print PHP_EOL;\n\n if ($arguments->help()) {\n $this->help();\n\n return 0;\n }\n\n $files = (new Facade)->getFilesAsArray(\n $arguments->directories(),\n $arguments->suffixes(),\n '',\n $arguments->exclude()\n );\n\n if (empty($files)) {\n print 'No files found to scan' . PHP_EOL;\n\n return 0;\n }\n\n $config = new StrategyConfiguration($arguments);\n\n try {\n $strategy = $this->pickStrategy($arguments->algorithm(), $config);\n } catch (InvalidStrategyException $e) {\n print $e->getMessage() . PHP_EOL;\n\n return 1;\n }\n\n $timer = new Timer;\n $timer->start();\n\n $clones = (new Detector($strategy))->copyPasteDetection($files);\n\n (new Text)->printResult($clones, $arguments->verbose());\n\n if ($arguments->pmdCpdXmlLogfile()) {\n (new PMD($arguments->pmdCpdXmlLogfile()))->processClones($clones);\n }\n\n print (new ResourceUsageFormatter)->resourceUsage($timer->stop()) . PHP_EOL;\n\n return count($clones) > 0 ? 1 : 0;\n }\n\n private function printVersion(): void\n {\n printf(\n 'phpcpd %s by Sebastian Bergmann.' . PHP_EOL,\n (new Version(self::VERSION, dirname(__DIR__)))->getVersion()\n );\n }\n\n /**\n * @throws InvalidStrategyException\n */\n private function pickStrategy(?string $algorithm, StrategyConfiguration $config): AbstractStrategy\n {\n return match ($algorithm) {\n null, 'rabin-karp' => new DefaultStrategy($config),\n 'suffixtree' => new SuffixTreeStrategy($config),\n default => throw new InvalidStrategyException('Unsupported algorithm: ' . $algorithm),\n };\n }\n\n private function help(): void\n {\n print <<<'EOT'\nUsage:\n phpcpd [options] \n\nOptions for selecting files:\n\n --suffix Include files with names ending in in the analysis\n (default: .php; can be given multiple times)\n --exclude Exclude files with in their path from the analysis\n (can be given multiple times)\n\nOptions for analysing files:\n\n --fuzzy Fuzz variable names\n --min-lines Minimum number of identical lines (default: 5)\n --min-tokens Minimum number of identical tokens (default: 70)\n --algorithm Select which algorithm to use ('rabin-karp' (default) or 'suffixtree')\n --edit-distance Distance in number of edits between two clones (only for suffixtree; default: 5)\n --head-equality Minimum equality at start of clone (only for suffixtree; default 10)\n\nOptions for report generation:\n\n --log-pmd Write log in PMD-CPD XML format to \n\nEOT;\n }\n}\n"}} -{"repo": "jezdez/limechat-whisper", "pr_number": 1, "title": "fix display of #channame or www.link.com", "state": "closed", "merged_at": "2012-08-03T20:35:28Z", "additions": 1, "deletions": 1, "files_changed": ["Whisper.css"], "files_before": {"Whisper.css": "html.normal {\n color: #4b4b4b;\n background-color: white;\n font: 12px/1.3em 'Lucida Grande' sans-serif;\n margin: 0;\n padding: 0;\n}\n\nbody.normal .sender[type=myself]:hover:before {\n content: \"\u2022 \";\n color: #bebebe;\n}\n\nbody.normal a img {\n border: 0;\n}\n\nbody.normal img {\n display: block;\n padding-top: 5px;\n padding-bottom: 5px;\n padding-left: 8px;\n max-width: 95%;\n}\n\nbody.normal a:link, a:visited, a:hover, a:active {\n color: #184586;\n}\n\nbody.normal .text span {\n display: block;\n}\n\nbody.normal .line {\n padding: 0;\n margin: 0;\n background-color: #eee;\n line-height: 130%;\n}\n\nbody.normal .event {\n padding: 0.2em;\n margin: 0;\n color: #363636;\n background: #e5edf7;\n}\n\nbody.normal .event + .event {\n border-top: #fff 1px solid;\n}\n\nbody.normal .text span.message {\n border-bottom: #efefef 1px solid;\n}\n\nbody.normal .text + .event {\n margin-top: -1px;\n}\n\nbody.normal .sender {\n padding: 0.4em 0;\n float: left;\n text-align: right;\n font-weight: bold;\n width: 130px;\n overflow: hidden;\n}\n\nbody.normal .line .message {\n margin: 0 0 0 134px;\n padding: 0.4em;\n color: #303030;\n border-left: 1px solid #dcdcdc;\n background-color: #fff;\n}\n\nbody.normal .event .message {\n margin: 0;\n padding: 0.4em;\n border: 0;\n color: #a6b9c0;\n background: none;\n font: bold 11px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n}\n\nbody.normal .line .time {\n float: right;\n margin-right: 6px;\n margin-top: 5px;\n margin-left: 4px;\n color: #999;\n font: bold 11px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n}\n\nbody.normal .line .place {\n display: block;\n color: #999;\n margin: 0;\n font-size: 12px;\n}\n\nbody.normal .event .time {\n margin: 1px 3px;\n float: right;\n text-align: right;\n font-size: 11px;\n color: #a6b9c0;\n}\n\nbody.normal .line[highlight=true] span.message {\n background-color: #ffc;\n}\n\nbody.normal .member {\n text-decoration: none !important;\n color: inherit !important;\n}\n\nbody.normal .member:hover {\n text-decoration: underline;\n}\n\nbody.normal {\n \n}\n\nbody.console {\n \n}\n\nbody[type=channel] {\n \n}\n\nbody[type=talk] {\n \n}\n\nbody[type=console] {\n \n}\n\nbody.normal hr {\n margin: 0;\n padding: 2px;\n border: none;\n background-color: #d33b54;\n height: 2px;\n text-align: center;\n}\n\na {\n \n}\n\n/* lines */\n\n.line[alternate=even] {\n \n}\n\n.line[alternate=odd] {\n \n}\n\n.line[type=action] .sender:before {\n content: \"\";\n}\n\nbody.normal .line[type=action] .sender {\n font-style: italic;\n}\n\nbody.normal .line[type=action] .message {\n background: #eee;\n border-left: none;\n margin: 0 0 0 130px;\n}\n\nbody.normal .url {\n word-break: break-all;\n}\n\nbody.normal .address {\n text-decoration: underline;\n word-break: break-all;\n}\n\nbody.normal .highlight {\n color: #d33b54;\n font-weight: bold;\n}\n\n/* nickname for text messages */\n\nbody.normal .sender[type=myself] {\n color: #333;\n}\n\nbody.normal .sender[type=normal] {\n color: #333;\n}\n\nbody.normal .sender[type=normal][colornumber='0'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='1'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='2'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='3'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='4'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='5'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='6'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='7'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='8'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='9'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='10'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='11'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='12'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='13'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='14'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='15'] {\n \n}\n\n/* message body */\n\nbody.normal .message[type=system] {\n color: #303030;\n}\n\nbody.normal .message[type=error] {\n color: #d14025;\n font-weight: bold;\n}\n\nbody.normal .message[type=reply] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=error_reply] {\n color: #d33b54;\n}\n\nbody.normal .message[type=dcc_send_send] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=dcc_send_receive] {\n color: #153b7c;\n}\n\nbody.normal .message[type=privmsg] {\n \n}\n\nbody.normal .message[type=notice] {\n color: #888;\n}\n\nbody.normal .message[type=action] {\n color: #303030;\n font-style: italic;\n font-weight: bold;\n}\n\nbody.normal .message[type=join] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=part] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=kick] {\n color: #303030;\n}\n\nbody.normal .message[type=quit] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=kill] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=nick] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=mode] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=topic] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=invite] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=wallops] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=debug_send] {\n color: #aaa;\n}\n\nbody.normal .message[type=debug_receive] {\n color: #444;\n}"}, "files_after": {"Whisper.css": "html.normal {\n color: #4b4b4b;\n background-color: white;\n font: 12px/1.3em 'Lucida Grande' sans-serif;\n margin: 0;\n padding: 0;\n}\n\nbody.normal .sender[type=myself]:hover:before {\n content: \"\u2022 \";\n color: #bebebe;\n}\n\nbody.normal a img {\n border: 0;\n}\n\nbody.normal img {\n display: block;\n padding-top: 5px;\n padding-bottom: 5px;\n padding-left: 8px;\n max-width: 95%;\n}\n\nbody.normal a:link, a:visited, a:hover, a:active {\n color: #184586;\n}\n\nbody.normal .text > span {\n display: block;\n}\n\nbody.normal .line {\n padding: 0;\n margin: 0;\n background-color: #eee;\n line-height: 130%;\n}\n\nbody.normal .event {\n padding: 0.2em;\n margin: 0;\n color: #363636;\n background: #e5edf7;\n}\n\nbody.normal .event + .event {\n border-top: #fff 1px solid;\n}\n\nbody.normal .text span.message {\n border-bottom: #efefef 1px solid;\n}\n\nbody.normal .text + .event {\n margin-top: -1px;\n}\n\nbody.normal .sender {\n padding: 0.4em 0;\n float: left;\n text-align: right;\n font-weight: bold;\n width: 130px;\n overflow: hidden;\n}\n\nbody.normal .line .message {\n margin: 0 0 0 134px;\n padding: 0.4em;\n color: #303030;\n border-left: 1px solid #dcdcdc;\n background-color: #fff;\n}\n\nbody.normal .event .message {\n margin: 0;\n padding: 0.4em;\n border: 0;\n color: #a6b9c0;\n background: none;\n font: bold 11px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n}\n\nbody.normal .line .time {\n float: right;\n margin-right: 6px;\n margin-top: 5px;\n margin-left: 4px;\n color: #999;\n font: bold 11px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n}\n\nbody.normal .line .place {\n display: block;\n color: #999;\n margin: 0;\n font-size: 12px;\n}\n\nbody.normal .event .time {\n margin: 1px 3px;\n float: right;\n text-align: right;\n font-size: 11px;\n color: #a6b9c0;\n}\n\nbody.normal .line[highlight=true] span.message {\n background-color: #ffc;\n}\n\nbody.normal .member {\n text-decoration: none !important;\n color: inherit !important;\n}\n\nbody.normal .member:hover {\n text-decoration: underline;\n}\n\nbody.normal {\n \n}\n\nbody.console {\n \n}\n\nbody[type=channel] {\n \n}\n\nbody[type=talk] {\n \n}\n\nbody[type=console] {\n \n}\n\nbody.normal hr {\n margin: 0;\n padding: 2px;\n border: none;\n background-color: #d33b54;\n height: 2px;\n text-align: center;\n}\n\na {\n \n}\n\n/* lines */\n\n.line[alternate=even] {\n \n}\n\n.line[alternate=odd] {\n \n}\n\n.line[type=action] .sender:before {\n content: \"\";\n}\n\nbody.normal .line[type=action] .sender {\n font-style: italic;\n}\n\nbody.normal .line[type=action] .message {\n background: #eee;\n border-left: none;\n margin: 0 0 0 130px;\n}\n\nbody.normal .url {\n word-break: break-all;\n}\n\nbody.normal .address {\n text-decoration: underline;\n word-break: break-all;\n}\n\nbody.normal .highlight {\n color: #d33b54;\n font-weight: bold;\n}\n\n/* nickname for text messages */\n\nbody.normal .sender[type=myself] {\n color: #333;\n}\n\nbody.normal .sender[type=normal] {\n color: #333;\n}\n\nbody.normal .sender[type=normal][colornumber='0'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='1'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='2'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='3'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='4'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='5'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='6'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='7'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='8'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='9'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='10'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='11'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='12'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='13'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='14'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='15'] {\n \n}\n\n/* message body */\n\nbody.normal .message[type=system] {\n color: #303030;\n}\n\nbody.normal .message[type=error] {\n color: #d14025;\n font-weight: bold;\n}\n\nbody.normal .message[type=reply] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=error_reply] {\n color: #d33b54;\n}\n\nbody.normal .message[type=dcc_send_send] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=dcc_send_receive] {\n color: #153b7c;\n}\n\nbody.normal .message[type=privmsg] {\n \n}\n\nbody.normal .message[type=notice] {\n color: #888;\n}\n\nbody.normal .message[type=action] {\n color: #303030;\n font-style: italic;\n font-weight: bold;\n}\n\nbody.normal .message[type=join] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=part] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=kick] {\n color: #303030;\n}\n\nbody.normal .message[type=quit] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=kill] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=nick] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=mode] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=topic] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=invite] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=wallops] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=debug_send] {\n color: #aaa;\n}\n\nbody.normal .message[type=debug_receive] {\n color: #444;\n}"}} -{"repo": "paveltyk/technical-test", "pr_number": 1, "title": "improve CLI", "state": "closed", "merged_at": "2010-09-30T09:53:36Z", "additions": 7, "deletions": 1, "files_changed": ["lib/editor.rb"], "files_before": {"lib/editor.rb": "require 'image'\nrequire 'readline'\n\nclass Editor\n def initialize(output)\n @output = output\n end\n def start\n @output.puts 'Welcome to Image Editor!'\n listen\n end\n\n def listen\n loop do\n cmd = Readline::readline '> ', true\n execute(cmd)\n end\n end\n\n def execute(cmd)\n case cmd\n when /^i (\\d+)+ (\\d+)+$/i\n @image = Image.new($1.to_i, $2.to_i)\n when /^c/i\n @image.clear\n when /^l (\\d+) (\\d+) ([a-z])$/i\n @image.colorize($1.to_i, $2.to_i,$3)\n when /^v (\\d+) (\\d+) (\\d+) ([a-z])$/i\n @image.draw_vertical_segment($1.to_i, $2.to_i, $3.to_i, $4)\n when /^h (\\d+) (\\d+) (\\d+) ([a-z])$/i\n @image.draw_horizontal_segment($1.to_i, $2.to_i, $3.to_i, $4)\n when /^f (\\d+) (\\d+) ([a-z])$/i\n @image.fill($1.to_i, $2.to_i, $3)\n when /^s$/i\n @output.puts @image.to_s\n when /^x$/i\n exit\n else\n puts 'Unknown command'\n end\n end\n \nend"}, "files_after": {"lib/editor.rb": "require 'image'\nrequire 'readline'\n\n# trap SIGINT and restore the state of the terminal\nstty_save = `stty -g`.chomp\ntrap('INT') { system('stty', stty_save); exit }\n\nclass Editor\n def initialize(output)\n @output = output\n end\n def start\n @output.puts 'Welcome to Image Editor!'\n listen\n end\n\n def listen\n loop do\n cmd = Readline::readline '> ', true\n # exit if user press CTRL-D\n exit if cmd.nil?\n execute(cmd)\n end\n end\n\n def execute(cmd)\n case cmd\n when /^i (\\d+)+ (\\d+)+$/i\n @image = Image.new($1.to_i, $2.to_i)\n when /^c/i\n @image.clear\n when /^l (\\d+) (\\d+) ([a-z])$/i\n @image.colorize($1.to_i, $2.to_i,$3)\n when /^v (\\d+) (\\d+) (\\d+) ([a-z])$/i\n @image.draw_vertical_segment($1.to_i, $2.to_i, $3.to_i, $4)\n when /^h (\\d+) (\\d+) (\\d+) ([a-z])$/i\n @image.draw_horizontal_segment($1.to_i, $2.to_i, $3.to_i, $4)\n when /^f (\\d+) (\\d+) ([a-z])$/i\n @image.fill($1.to_i, $2.to_i, $3)\n when /^s$/i\n @output.puts @image.to_s\n when /^x$/i\n exit\n else\n puts 'Unknown command'\n end\n end\n \nend\n"}} -{"repo": "nhowell/subdomain-fu", "pr_number": 1, "title": "Path url_for to work on on Rails 4.2", "state": "closed", "merged_at": null, "additions": 14, "deletions": 2, "files_changed": ["lib/subdomain_fu/url_rewriter.rb"], "files_before": {"lib/subdomain_fu/url_rewriter.rb": "require 'action_dispatch/routing/route_set'\n\nmodule ActionDispatch\n module Routing\n class RouteSet #:nodoc:\n def url_for_with_subdomains(options, path_segments=nil)\n if SubdomainFu.needs_rewrite?(options[:subdomain], (options[:host] || @request.host_with_port)) || options[:only_path] == false\n options[:only_path] = false if SubdomainFu.override_only_path?\n options[:host] = SubdomainFu.rewrite_host_for_subdomains(options.delete(:subdomain), options[:host] || @request.host_with_port)\n # puts \"options[:host]: #{options[:host].inspect}\"\n else\n options.delete(:subdomain)\n end\n url_for_without_subdomains(options)\n end\n alias_method_chain :url_for, :subdomains\n end\n end\nend\n"}, "files_after": {"lib/subdomain_fu/url_rewriter.rb": "require 'action_dispatch/routing/route_set'\n\nmodule ActionDispatch\n module Routing\n class RouteSet #:nodoc:\n # Known Issue: Monkey-patching `url_for` is error-prone.\n # For example, in rails 4.2, the method signature changed from\n #\n # def url_for(options)\n #\n # to\n #\n # def url_for(options, route_name = nil, url_strategy = UNKNOWN)\n #\n # Is there an alternative design using composition or class\n # inheritance?\n\n def url_for_with_subdomains(options, *args)\n if SubdomainFu.needs_rewrite?(options[:subdomain], (options[:host] || @request.host_with_port)) || options[:only_path] == false\n options[:only_path] = false if SubdomainFu.override_only_path?\n options[:host] = SubdomainFu.rewrite_host_for_subdomains(options.delete(:subdomain), options[:host] || @request.host_with_port)\n # puts \"options[:host]: #{options[:host].inspect}\"\n else\n options.delete(:subdomain)\n end\n url_for_without_subdomains(options, *args)\n end\n alias_method_chain :url_for, :subdomains\n end\n end\nend\n"}} -{"repo": "jcsalterego/nagios-rb", "pr_number": 1, "title": "unbreak adding further options", "state": "closed", "merged_at": "2012-02-16T16:25:17Z", "additions": 1, "deletions": 1, "files_changed": ["lib/nagios/config.rb"], "files_before": {"lib/nagios/config.rb": "require 'optparse'\n\nmodule Nagios\n class Config\n\n attr_accessor :options\n\n def initialize\n @settings = {}\n @options = OptionParser.new do |options|\n options.on(\"-wWARNING\",\n \"--warning=WARNING\",\n \"Warning Threshold\") do |x|\n @settings[:warning] = int_if_possible(x)\n end\n options.on(\"-cCRITICAL\",\n \"--critical=CRITICAL\",\n \"Critical Threshold\") do |x|\n @settings[:critical] = int_if_possible(x)\n end\n end\n end\n\n def [](setting)\n @settings[setting]\n end\n\n def []=(field, value)\n @settings[field] = vaule\n end\n\n def parse!\n @options.parse!\n end\n\n private\n def int_if_possible(x)\n (x.to_i > 0 || x == '0') ? x.to_i : x\n end\n end\nend\n"}, "files_after": {"lib/nagios/config.rb": "require 'optparse'\n\nmodule Nagios\n class Config\n\n attr_accessor :options\n\n def initialize\n @settings = {}\n @options = OptionParser.new do |options|\n options.on(\"-wWARNING\",\n \"--warning=WARNING\",\n \"Warning Threshold\") do |x|\n @settings[:warning] = int_if_possible(x)\n end\n options.on(\"-cCRITICAL\",\n \"--critical=CRITICAL\",\n \"Critical Threshold\") do |x|\n @settings[:critical] = int_if_possible(x)\n end\n end\n end\n\n def [](setting)\n @settings[setting]\n end\n\n def []=(field, value)\n @settings[field] = value\n end\n\n def parse!\n @options.parse!\n end\n\n private\n def int_if_possible(x)\n (x.to_i > 0 || x == '0') ? x.to_i : x\n end\n end\nend\n"}} -{"repo": "aconbere/evented", "pr_number": 1, "title": "Correct the URL for the github repo.", "state": "open", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["lib/evented.js"], "files_before": {"lib/evented.js": "/*\n * YO check out the repository for updates\n * http://github.com/aconbere/event-emitter\n *\n */\nvar Evented = function () {\n this.listeners = {};\n this.listenersOnce = {};\n};\n\nEvented.prototype.withListeners = function (ev, callback) {\n if (!this.listeners[ev]) {\n this.listeners[ev] = [];\n }\n\n if (!this.listenersOnce[ev]) {\n this.listenersOnce[ev] = [];\n }\n\n if (callback) {\n callback(this.listeners[ev], this.listenersOnce[ev]);\n }\n};\n\nEvented.prototype.trigger = function (ev, data) {\n data = data || [];\n\n var that = this;\n this.withListeners(ev, function (listeners, listenersOnce) {\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].apply(null, data);\n }\n\n for (var i = 0; i < listenersOnce.length; i++) {\n listenersOnce[i].apply(null, data);\n }\n // reset any of the once listeners for this event\n that.listenersOnce[ev] = [];\n });\n};\n\n\nEvented.prototype.bind = function (ev, callback) {\n this.withListeners(ev, function (listeners, _listenersOnce) {\n listeners.push(callback);\n });\n};\n\nEvented.prototype.bindOnce = function (ev, callback) {\n this.withListeners(ev, function (_listeners, listenersOnce) {\n listenersOnce.push(callback);\n });\n};\n\nEvented.prototype.unbindAll = function () {\n this.listeners = {};\n};\n\nif (typeof window === \"undefined\") {\n exports.Evented = Evented;\n}\n"}, "files_after": {"lib/evented.js": "/*\n * YO check out the repository for updates\n * http://github.com/aconbere/evented\n *\n */\nvar Evented = function () {\n this.listeners = {};\n this.listenersOnce = {};\n};\n\nEvented.prototype.withListeners = function (ev, callback) {\n if (!this.listeners[ev]) {\n this.listeners[ev] = [];\n }\n\n if (!this.listenersOnce[ev]) {\n this.listenersOnce[ev] = [];\n }\n\n if (callback) {\n callback(this.listeners[ev], this.listenersOnce[ev]);\n }\n};\n\nEvented.prototype.trigger = function (ev, data) {\n data = data || [];\n\n var that = this;\n this.withListeners(ev, function (listeners, listenersOnce) {\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].apply(null, data);\n }\n\n for (var i = 0; i < listenersOnce.length; i++) {\n listenersOnce[i].apply(null, data);\n }\n // reset any of the once listeners for this event\n that.listenersOnce[ev] = [];\n });\n};\n\n\nEvented.prototype.bind = function (ev, callback) {\n this.withListeners(ev, function (listeners, _listenersOnce) {\n listeners.push(callback);\n });\n};\n\nEvented.prototype.bindOnce = function (ev, callback) {\n this.withListeners(ev, function (_listeners, listenersOnce) {\n listenersOnce.push(callback);\n });\n};\n\nEvented.prototype.unbindAll = function () {\n this.listeners = {};\n};\n\nif (typeof window === \"undefined\") {\n exports.Evented = Evented;\n}\n"}} -{"repo": "jtauber/web-graphics", "pr_number": 1, "title": "Fixed 'open' to write binary data in Windows too", "state": "closed", "merged_at": "2013-08-23T12:31:06Z", "additions": 1, "deletions": 1, "files_changed": ["web_graphics.py"], "files_before": {"web_graphics.py": "import zlib\nimport struct\nimport array\nimport random\nimport colorsys\n\n\ndef output_chunk(out, chunk_type, data):\n out.write(struct.pack(\"!I\", len(data)))\n out.write(chunk_type)\n out.write(data)\n checksum = zlib.crc32(data, zlib.crc32(chunk_type))\n out.write(struct.pack(\"!i\", checksum))\n\n\ndef get_data(width, height, rgb_func):\n fw = float(width)\n fh = float(height)\n compressor = zlib.compressobj()\n data = array.array(\"B\")\n for y in range(height):\n data.append(0)\n fy = float(y)\n for x in range(width):\n fx = float(x)\n data.extend([min(255, max(0, int(v * 255))) for v in rgb_func(fx / fw, fy / fh)])\n compressed = compressor.compress(data.tostring())\n flushed = compressor.flush()\n return compressed + flushed\n\n\ndef write_png(filename, width, height, rgb_func):\n out = open(filename, \"w\")\n out.write(struct.pack(\"8B\", 137, 80, 78, 71, 13, 10, 26, 10))\n output_chunk(out, \"IHDR\", struct.pack(\"!2I5B\", width, height, 8, 2, 0, 0, 0))\n output_chunk(out, \"IDAT\", get_data(width, height, rgb_func))\n output_chunk(out, \"IEND\", \"\")\n out.close()\n\n\ndef linear_gradient(start_value, stop_value, start_offset=0.0, stop_offset=1.0):\n return lambda offset: (start_value + ((offset - start_offset) / (stop_offset - start_offset) * (stop_value - start_value))) / 255.0\n\n\ndef LINEAR_Y(x, y):\n return y\n\n\ndef LINEAR_X(x, y):\n return x\n\n\ndef RADIAL(center_x, center_y):\n return lambda x, y: (x - center_x) ** 2 + (y - center_y) ** 2\n\n\ndef NO_NOISE(r, g, b):\n return r, g, b\n\n\ndef GAUSSIAN(sigma):\n def add_noise(r, g, b):\n d = random.gauss(0, sigma)\n return r + d, g + d, b + d\n return add_noise\n\n\ndef HSV(h, s, v):\n r, g, b = colorsys.hsv_to_rgb(h, s, v)\n return 255 * r, 255 * g, 255 * b\n\n\ndef hexstring_to_rgb(s):\n r = int(s[1:3], 16)\n g = int(s[3:5], 16)\n b = int(s[5:7], 16)\n return r, g, b\n\n\ndef gradient(value_func, noise_func, DATA):\n def gradient_function(x, y):\n initial_offset = 0.0\n v = value_func(x, y)\n for offset, start, end in DATA:\n if isinstance(start, str) and start.startswith(\"#\"):\n start = hexstring_to_rgb(start)\n if isinstance(end, str) and end.startswith(\"#\"):\n end = hexstring_to_rgb(end)\n if v < offset:\n r = linear_gradient(start[0], end[0], initial_offset, offset)(v)\n g = linear_gradient(start[1], end[1], initial_offset, offset)(v)\n b = linear_gradient(start[2], end[2], initial_offset, offset)(v)\n return noise_func(r, g, b)\n initial_offset = offset\n return noise_func(end[0] / 255.0, end[1] / 255.0, end[2] / 255.0)\n return gradient_function\n"}, "files_after": {"web_graphics.py": "import zlib\nimport struct\nimport array\nimport random\nimport colorsys\n\n\ndef output_chunk(out, chunk_type, data):\n out.write(struct.pack(\"!I\", len(data)))\n out.write(chunk_type)\n out.write(data)\n checksum = zlib.crc32(data, zlib.crc32(chunk_type))\n out.write(struct.pack(\"!i\", checksum))\n\n\ndef get_data(width, height, rgb_func):\n fw = float(width)\n fh = float(height)\n compressor = zlib.compressobj()\n data = array.array(\"B\")\n for y in range(height):\n data.append(0)\n fy = float(y)\n for x in range(width):\n fx = float(x)\n data.extend([min(255, max(0, int(v * 255))) for v in rgb_func(fx / fw, fy / fh)])\n compressed = compressor.compress(data.tostring())\n flushed = compressor.flush()\n return compressed + flushed\n\n\ndef write_png(filename, width, height, rgb_func):\n out = open(filename, \"wb\")\n out.write(struct.pack(\"8B\", 137, 80, 78, 71, 13, 10, 26, 10))\n output_chunk(out, \"IHDR\", struct.pack(\"!2I5B\", width, height, 8, 2, 0, 0, 0))\n output_chunk(out, \"IDAT\", get_data(width, height, rgb_func))\n output_chunk(out, \"IEND\", \"\")\n out.close()\n\n\ndef linear_gradient(start_value, stop_value, start_offset=0.0, stop_offset=1.0):\n return lambda offset: (start_value + ((offset - start_offset) / (stop_offset - start_offset) * (stop_value - start_value))) / 255.0\n\n\ndef LINEAR_Y(x, y):\n return y\n\n\ndef LINEAR_X(x, y):\n return x\n\n\ndef RADIAL(center_x, center_y):\n return lambda x, y: (x - center_x) ** 2 + (y - center_y) ** 2\n\n\ndef NO_NOISE(r, g, b):\n return r, g, b\n\n\ndef GAUSSIAN(sigma):\n def add_noise(r, g, b):\n d = random.gauss(0, sigma)\n return r + d, g + d, b + d\n return add_noise\n\n\ndef HSV(h, s, v):\n r, g, b = colorsys.hsv_to_rgb(h, s, v)\n return 255 * r, 255 * g, 255 * b\n\n\ndef hexstring_to_rgb(s):\n r = int(s[1:3], 16)\n g = int(s[3:5], 16)\n b = int(s[5:7], 16)\n return r, g, b\n\n\ndef gradient(value_func, noise_func, DATA):\n def gradient_function(x, y):\n initial_offset = 0.0\n v = value_func(x, y)\n for offset, start, end in DATA:\n if isinstance(start, str) and start.startswith(\"#\"):\n start = hexstring_to_rgb(start)\n if isinstance(end, str) and end.startswith(\"#\"):\n end = hexstring_to_rgb(end)\n if v < offset:\n r = linear_gradient(start[0], end[0], initial_offset, offset)(v)\n g = linear_gradient(start[1], end[1], initial_offset, offset)(v)\n b = linear_gradient(start[2], end[2], initial_offset, offset)(v)\n return noise_func(r, g, b)\n initial_offset = offset\n return noise_func(end[0] / 255.0, end[1] / 255.0, end[2] / 255.0)\n return gradient_function\n"}} -{"repo": "chnm/thatcamp-registrations", "pr_number": 28, "title": "Simplifies user creation.", "state": "closed", "merged_at": "2012-02-09T21:10:49Z", "additions": 5, "deletions": 18, "files_changed": ["thatcamp-registrations-functions.php"], "files_before": {"thatcamp-registrations-functions.php": "prefix . \"thatcamp_registrations\";\n \n $_POST = stripslashes_deep($_POST); \n \n // The user_id is set to the posted user ID, or null.\n $user_id = isset($_POST['user_id']) ? $_POST['user_id'] : null;\n \n $applicant_info = array();\n \n // Array of applicant info fields. May set up an option in plugin so admins can modify this list.\n $applicant_fields = array(\n 'first_name',\n 'last_name',\n 'user_email',\n 'user_url',\n 'description',\n 'previous_thatcamps',\n 'user_title',\n 'user_organization',\n 'user_twitter',\n 'tshirt_size',\n 'dietary_preferences'\n );\n \n foreach ( $applicant_fields as $field) {\n $applicant_info[$field] = isset($_POST[$field]) ? $_POST[$field] : null;\n }\n \n $date = isset($_POST['date']) ? $_POST['date'] : null;\n $applicationText = isset($_POST['application_text']) ? $_POST['application_text'] : null;\n\n // Let's serialize the applicant_info before putting it in the database.\n $applicant_info = maybe_serialize($applicant_info);\n $applicant_email = isset($_POST['user_email']) ? $_POST['user_email'] : null;\n \n if ( $registration = thatcamp_registrations_get_registration_by_user_id($user_id) \n || $registration = thatcamp_registrations_get_registration_by_applicant_email($applicant_email) ) {\n return 'You have already submitted an application.';\n } else {\n $wpdb->insert(\n $table,\n array(\n 'applicant_info' => $applicant_info,\n 'applicant_email' => $applicant_email,\n 'application_text' => $applicationText,\n 'status' => $status,\n 'date' => $date,\n 'user_id' => $user_id\n )\n );\n thatcamp_registrations_send_applicant_email($applicant_email);\n }\n}\n\n/**\n * Returns registration records based on type\n * \n * @param array The parameters on which to retrieve registrations\n **/\nfunction thatcamp_registrations_get_registrations($params = array()) {\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n \n $sql = \"SELECT * FROM \" . $registrations_table;\n \n if( isset($params['id']) && $id = $params['id']) {\n $sql .= \" WHERE id=\".$params['id'];\n if( isset($params['status']) && $status = $params['status']) {\n $sql .= \" AND status = CONVERT( _utf8 '$status' USING latin1 )\";\n }\n } elseif ( isset($params['status']) && $status = $params['status']) {\n $sql .= \" WHERE status = CONVERT( _utf8 '$status' USING latin1 )\";\n }\n \n // echo $sql; exit;\n $results = $wpdb->get_results($sql, OBJECT);\n return $results;\n}\n\n/**\n * Processes an array of registrations based on ID. Used mainly in the admin.\n * \n * @param array The IDs of the registration records.\n * @param string The status for the registration records.\n **/\nfunction thatcamp_registrations_process_registrations($ids = array(), $status) {\n global $wpdb;\n $table = $wpdb->prefix . \"thatcamp_registrations\";\n \n $idArray = array();\n foreach ($ids as $id) {\n $idArray['id'] = $id;\n }\n \n if ($status && !empty($idArray)) { \n $wpdb->update(\n $table,\n array('status' => $status),\n $idArray\n );\n if ($status == 'approved' && thatcamp_registrations_create_user_accounts()) {\n foreach ($ids as $id) {\n thatcamp_registrations_process_user($id);\n }\n }\n }\n \n return;\n}\n\n/**\n * Process a single registration based on ID. Uses mainly in the admin.\n * \n * @param int The ID of the registration record.\n * @param string The status for the registration record.\n **/\nfunction thatcamp_registrations_process_registration($id, $status) {\n if (isset($id) && isset($status)) {\n thatcamp_registrations_process_registrations(array($id), $status);\n }\n return;\n}\n\n/**\n * Processes a WP user when adding/updating a registration record. Only \n * should be used if we're creating users with approved registrations.\n *\n * @param integer|null The User ID\n * @param array The array of user information.\n * @param $registrationId\n * @return integer The User ID\n **/\nfunction thatcamp_registrations_process_user($registrationId = null, $role = 'author') {\n global $wpdb;\n \n /**\n * If the Registration ID is set, it means we already have a registration \n * record! Booyah. We'll use the user_id and application_info columns from \n * that record to process the user.\n */\n \n if ($registration = thatcamp_registrations_get_registration_by_id($registrationId)) { \n \n $userInfo = maybe_unserialize($registration->applicant_info);\n $userId = $registration->user_id ? $registration->user_id : email_exists($registration->applicant_email);\n \n // If we have a valid a User ID, we're dealing with an existing user.\n if ($userId) {\n add_existing_user_to_blog(array('user_id' => $userId, 'role' => $role));\n wp_new_user_notification($userId);\n }\n // We're probably dealing with a new user. Let's create one and associate it to our blog.\n else { \n $randomPassword = wp_generate_password( 12, false );\n $userEmail = $registration->applicant_email;\n $uarray = split( '@', $userEmail );\n $userName = sanitize_user( $uarray[0] );\n $userId = wp_create_user( $userName, $randomPassword, $userEmail );\n add_user_to_blog($wpdb->blogid, $userId, $role);\n thatcamp_registrations_update_user_data($userId, $userInfo);\n wp_new_user_notification($userId, $randomPassword);\n }\n }\n \n return $userId;\n}\n\n/**\n * Updates the user data. \n * Note: this needs to be altered so that user_url goes in the wp_users table and not the wp_usermeta table. --AF Sample: wp_update_user( array ('ID' => $user_id, 'user_url' => 'http://www.site.com' ) ) ; and http://wordpress.org/support/topic/wordpress-33-update_user_meta-and-wp_userswp_usermeta-issue?replies=8 \n **/\nfunction thatcamp_registrations_update_user_data($userId, $params)\n{\n\n if ( isset( $userId ) && $userData = get_userdata($userId) ) {\n foreach ($params as $key => $value) {\n update_user_meta( $userId, $key, $value );\n }\n } \n}\n\n/**\n * Gets registration record by ID.\n *\n **/\nfunction thatcamp_registrations_get_registration_by_id($id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE id = \" .$id;\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Gets registration record by applicant_email.\n *\n **/\nfunction thatcamp_registrations_get_registration_by_applicant_email($applicant_email)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE applicant_email = '\" .$applicant_email .\"'\";\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Gets registration record by user_id.\n *\n * @param int $user_id The User ID.\n * @return object Registration record.\n **/\nfunction thatcamp_registrations_get_registration_by_user_id($user_id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE user_id = \" .$user_id;\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Deletes a registration record by ID.\n *\n **/\nfunction thatcamp_registrations_delete_registration($id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n if($id) {\n $wpdb->query(\"DELETE FROM \" . $registrations_table . \" WHERE id = '\" . $id . \"'\");\n }\n}\n\n/**\n * Creates a user from a registration record.\n *\n * @param integer $registrationId \n **/\nfunction thatcamp_registrations_create_user($registrationId)\n{\n if ($applicant = thatcamp_registrations_get_registration_applicant($registrationId)) {\n \n // if ( !is_int($applicant) ) {\n return $applicant;\n // }\n }\n}\n\n/**\n * Returns the value for thatcamp_registrations_options\n *\n * @uses get_option()\n * @return array The array of options\n **/\nfunction thatcamp_registrations_options() \n{\n return get_option('thatcamp_registrations_options');\n}\n\n/**\n * Returns the value for a single THATCamp Registrations option.\n *\n * @uses thatcamp_registrations_options()\n * @param string The name of the option\n * @return string\n **/\nfunction thatcamp_registrations_option($optionName) \n{\n if (isset($optionName)) {\n $options = thatcamp_registrations_options();\n return $options[$optionName];\n }\n return false;\n}\n\nfunction thatcamp_registrations_get_applicant_info($registration) \n{\n global $wpdb;\n \n if ($registration) {\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE id = \" .$registration->id;\n $record = $wpdb->get_row($sql, OBJECT);\n if (($record->user_id == 0 || $record->user_id == null) && !empty($record->applicant_info)) {\n return (object) maybe_unserialize($record->applicant_info);\n } else {\n return get_userdata($record->user_id);\n }\n }\n}\n\n/**\n * Send a notification email to a THATCamp Registrations applicant\n *\n * @param string The applicant email address.\n * @param string The status of the application. Options are 'pending',\n * 'approved', and 'rejected. Default is pending.\n */\nfunction thatcamp_registrations_send_applicant_email($to, $status = \"pending\")\n{\n if (is_email($to)) {\n switch ($status) {\n case 'approved':\n $subject = __('Application Approved', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('accepted_application_email');\n break;\n \n case 'rejected':\n $subject = __('Application Rejected', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('rejected_application_email');\n break;\n case 'pending':\n default:\n $subject = __('Application Pending', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('pending_application_email');\n break;\n }\n \n $subject = $subject . ': '.get_bloginfo('name');\n wp_mail($to, $subject, $message);\n \n return __('Email successfully sent!');\n }\n return false;\n}\n\n/**\n * Checks the option to create user accounts upon application approval.\n *\n * @return boolean\n **/\nfunction thatcamp_registrations_create_user_accounts() \n{\n return (bool) thatcamp_registrations_option('create_user_accounts');\n}\n\n/**\n * Checks to see if user authentication is required.\n *\n * @return boolean\n **/\nfunction thatcamp_registrations_user_required() \n{\n return (bool) thatcamp_registrations_option('require_login');\n}\n\n/**\n * Checks if registration is open.\n *\n * @return boolean\n */\nfunction thatcamp_registrations_registration_is_open()\n{\n return (bool) thatcamp_registrations_option('open_registration');\n}\n\n/**\n * Generates a random string for a token\n **/\nfunction thatcamp_registrations_generate_token()\n{\n return sha1(microtime() . mt_rand(1, 100000));\n}\n"}, "files_after": {"thatcamp-registrations-functions.php": "prefix . \"thatcamp_registrations\";\n \n $_POST = stripslashes_deep($_POST); \n \n // The user_id is set to the posted user ID, or null.\n $user_id = isset($_POST['user_id']) ? $_POST['user_id'] : null;\n \n $applicant_info = array();\n \n // Array of applicant info fields. May set up an option in plugin so admins can modify this list.\n $applicant_fields = array(\n 'first_name',\n 'last_name',\n 'user_email',\n 'user_url',\n 'description',\n 'previous_thatcamps',\n 'user_title',\n 'user_organization',\n 'user_twitter',\n 'tshirt_size',\n 'dietary_preferences'\n );\n \n foreach ( $applicant_fields as $field) {\n $applicant_info[$field] = isset($_POST[$field]) ? $_POST[$field] : null;\n }\n \n $date = isset($_POST['date']) ? $_POST['date'] : null;\n $applicationText = isset($_POST['application_text']) ? $_POST['application_text'] : null;\n\n // Let's serialize the applicant_info before putting it in the database.\n $applicant_info = maybe_serialize($applicant_info);\n $applicant_email = isset($_POST['user_email']) ? $_POST['user_email'] : null;\n \n if ( $registration = thatcamp_registrations_get_registration_by_user_id($user_id) \n || $registration = thatcamp_registrations_get_registration_by_applicant_email($applicant_email) ) {\n return 'You have already submitted an application.';\n } else {\n $wpdb->insert(\n $table,\n array(\n 'applicant_info' => $applicant_info,\n 'applicant_email' => $applicant_email,\n 'application_text' => $applicationText,\n 'status' => $status,\n 'date' => $date,\n 'user_id' => $user_id\n )\n );\n thatcamp_registrations_send_applicant_email($applicant_email);\n }\n}\n\n/**\n * Returns registration records based on type\n * \n * @param array The parameters on which to retrieve registrations\n **/\nfunction thatcamp_registrations_get_registrations($params = array()) {\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n \n $sql = \"SELECT * FROM \" . $registrations_table;\n \n if( isset($params['id']) && $id = $params['id']) {\n $sql .= \" WHERE id=\".$params['id'];\n if( isset($params['status']) && $status = $params['status']) {\n $sql .= \" AND status = CONVERT( _utf8 '$status' USING latin1 )\";\n }\n } elseif ( isset($params['status']) && $status = $params['status']) {\n $sql .= \" WHERE status = CONVERT( _utf8 '$status' USING latin1 )\";\n }\n \n // echo $sql; exit;\n $results = $wpdb->get_results($sql, OBJECT);\n return $results;\n}\n\n/**\n * Processes an array of registrations based on ID. Used mainly in the admin.\n * \n * @param array The IDs of the registration records.\n * @param string The status for the registration records.\n **/\nfunction thatcamp_registrations_process_registrations($ids = array(), $status) {\n global $wpdb;\n $table = $wpdb->prefix . \"thatcamp_registrations\";\n \n $idArray = array();\n foreach ($ids as $id) {\n $idArray['id'] = $id;\n }\n \n if ($status && !empty($idArray)) { \n $wpdb->update(\n $table,\n array('status' => $status),\n $idArray\n );\n if ($status == 'approved' && thatcamp_registrations_create_user_accounts()) {\n foreach ($ids as $id) {\n thatcamp_registrations_process_user($id);\n }\n }\n }\n \n return;\n}\n\n/**\n * Process a single registration based on ID. Uses mainly in the admin.\n * \n * @param int The ID of the registration record.\n * @param string The status for the registration record.\n **/\nfunction thatcamp_registrations_process_registration($id, $status) {\n if (isset($id) && isset($status)) {\n thatcamp_registrations_process_registrations(array($id), $status);\n }\n return;\n}\n\n/**\n * Processes a WP user when adding/updating a registration record. Only \n * should be used if we're creating users with approved registrations.\n *\n * @param integer|null The User ID\n * @param array The array of user information.\n * @param $registrationId\n * @return integer The User ID\n **/\nfunction thatcamp_registrations_process_user($registrationId = null, $role = 'author') {\n global $wpdb;\n \n /**\n * If the Registration ID is set, it means we already have a registration \n * record! Booyah. We'll use the user_id and application_info columns from \n * that record to process the user.\n */\n \n if ($registration = thatcamp_registrations_get_registration_by_id($registrationId)) { \n \n $userInfo = maybe_unserialize($registration->applicant_info);\n $userId = $registration->user_id ? $registration->user_id : email_exists($registration->applicant_email);\n \n // If we have a valid a User ID, we're dealing with an existing user.\n if ($userId) {\n add_existing_user_to_blog(array('user_id' => $userId, 'role' => $role));\n wp_new_user_notification($userId);\n }\n // We're probably dealing with a new user. Let's create one and associate it to our blog.\n else { \n $userEmail = $registration->applicant_email;\n $uarray = split( '@', $userEmail );\n $userName = sanitize_user( $uarray[0] );\n $userInfo['user_login'] = $userName;\n $userInfo['user_email'] = $userEmail;\n\n $userId = wp_insert_user( $userInfo );\n add_user_to_blog($wpdb->blogid, $userId, $role);\n wp_new_user_notification($userId);\n }\n }\n \n return $userId;\n}\n\n/**\n * Gets registration record by ID.\n *\n **/\nfunction thatcamp_registrations_get_registration_by_id($id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE id = \" .$id;\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Gets registration record by applicant_email.\n *\n **/\nfunction thatcamp_registrations_get_registration_by_applicant_email($applicant_email)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE applicant_email = '\" .$applicant_email .\"'\";\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Gets registration record by user_id.\n *\n * @param int $user_id The User ID.\n * @return object Registration record.\n **/\nfunction thatcamp_registrations_get_registration_by_user_id($user_id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE user_id = \" .$user_id;\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Deletes a registration record by ID.\n *\n **/\nfunction thatcamp_registrations_delete_registration($id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n if($id) {\n $wpdb->query(\"DELETE FROM \" . $registrations_table . \" WHERE id = '\" . $id . \"'\");\n }\n}\n\n/**\n * Creates a user from a registration record.\n *\n * @param integer $registrationId \n **/\nfunction thatcamp_registrations_create_user($registrationId)\n{\n if ($applicant = thatcamp_registrations_get_registration_applicant($registrationId)) {\n \n // if ( !is_int($applicant) ) {\n return $applicant;\n // }\n }\n}\n\n/**\n * Returns the value for thatcamp_registrations_options\n *\n * @uses get_option()\n * @return array The array of options\n **/\nfunction thatcamp_registrations_options() \n{\n return get_option('thatcamp_registrations_options');\n}\n\n/**\n * Returns the value for a single THATCamp Registrations option.\n *\n * @uses thatcamp_registrations_options()\n * @param string The name of the option\n * @return string\n **/\nfunction thatcamp_registrations_option($optionName) \n{\n if (isset($optionName)) {\n $options = thatcamp_registrations_options();\n return $options[$optionName];\n }\n return false;\n}\n\nfunction thatcamp_registrations_get_applicant_info($registration) \n{\n global $wpdb;\n \n if ($registration) {\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE id = \" .$registration->id;\n $record = $wpdb->get_row($sql, OBJECT);\n if (($record->user_id == 0 || $record->user_id == null) && !empty($record->applicant_info)) {\n return (object) maybe_unserialize($record->applicant_info);\n } else {\n return get_userdata($record->user_id);\n }\n }\n}\n\n/**\n * Send a notification email to a THATCamp Registrations applicant\n *\n * @param string The applicant email address.\n * @param string The status of the application. Options are 'pending',\n * 'approved', and 'rejected. Default is pending.\n */\nfunction thatcamp_registrations_send_applicant_email($to, $status = \"pending\")\n{\n if (is_email($to)) {\n switch ($status) {\n case 'approved':\n $subject = __('Application Approved', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('accepted_application_email');\n break;\n \n case 'rejected':\n $subject = __('Application Rejected', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('rejected_application_email');\n break;\n case 'pending':\n default:\n $subject = __('Application Pending', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('pending_application_email');\n break;\n }\n \n $subject = $subject . ': '.get_bloginfo('name');\n wp_mail($to, $subject, $message);\n \n return __('Email successfully sent!');\n }\n return false;\n}\n\n/**\n * Checks the option to create user accounts upon application approval.\n *\n * @return boolean\n **/\nfunction thatcamp_registrations_create_user_accounts() \n{\n return (bool) thatcamp_registrations_option('create_user_accounts');\n}\n\n/**\n * Checks to see if user authentication is required.\n *\n * @return boolean\n **/\nfunction thatcamp_registrations_user_required() \n{\n return (bool) thatcamp_registrations_option('require_login');\n}\n\n/**\n * Checks if registration is open.\n *\n * @return boolean\n */\nfunction thatcamp_registrations_registration_is_open()\n{\n return (bool) thatcamp_registrations_option('open_registration');\n}\n\n/**\n * Generates a random string for a token\n **/\nfunction thatcamp_registrations_generate_token()\n{\n return sha1(microtime() . mt_rand(1, 100000));\n}\n"}} -{"repo": "roman/warden_oauth", "pr_number": 4, "title": "Added a way to modify the oauth_callback url", "state": "open", "merged_at": null, "additions": 465, "deletions": 4, "files_changed": ["lib/warden_oauth.rb", "lib/warden_oauth/strategy.rb", "lib/warden_oauth2/base.rb", "lib/warden_oauth2/config.rb", "lib/warden_oauth2/config_extension.rb", "lib/warden_oauth2/errors.rb", "lib/warden_oauth2/strategy.rb", "lib/warden_oauth2/strategy_builder.rb", "lib/warden_oauth2/utils.rb"], "files_before": {"lib/warden_oauth/strategy.rb": "module Warden\n module OAuth\n\n #\n # Holds all the main logic of the OAuth authentication, all the generated\n # OAuth classes will extend from this class\n #\n class Strategy < Warden::Strategies::Base\n extend StrategyBuilder\n\n ######################\n ### Strategy Logic ###\n ######################\n\n\n def self.access_token_user_finders\n (@_user_token_finders ||= {})\n end\n\n #\n # An OAuth strategy will be valid to execute if:\n # * A 'warden_oauth_provider' parameter is given, with the name of the OAuth service\n # * A 'oauth_token' is being receive on the request (response from an OAuth provider)\n #\n def valid?\n (params.include?('warden_oauth_provider') && params['warden_oauth_provider'] == config.provider_name.to_s) ||\n params.include?('oauth_token') \n end\n\n\n #\n # Manages the OAuth authentication process, there can be 3 outcomes from this Strategy:\n # 1. The OAuth credentials are invalid and the FailureApp is called\n # 2. The OAuth credentials are valid, but there is no user associated to them. In this case\n # the FailureApp is called, but the env['warden.options'][:oauth][:access_token] will be \n # available.\n # 3. The OAuth credentials are valid, and the user is authenticated successfuly\n #\n # @note\n # If you want to signup users with the twitter credentials, you can manage the creation of a new \n # user in the FailureApp with the given access_token\n #\n def authenticate!\n if params.include?('warden_oauth_provider')\n store_request_token_on_session\n redirect!(request_token.authorize_url)\n throw(:warden)\n elsif params.include?('oauth_token')\n load_request_token_from_session\n if missing_stored_token?\n fail!(\"There is no OAuth authentication in progress\")\n elsif !stored_token_match_recieved_token?\n fail!(\"Received OAuth token didn't match stored OAuth token\")\n else\n user = find_user_by_access_token(access_token)\n if user.nil?\n fail!(\"User with access token not found\")\n throw_error_with_oauth_info\n else\n success!(user)\n end\n end\n end\n\n end\n\n def fail!(msg) #:nodoc:\n self.errors.add(service_param_name.to_sym, msg)\n super\n end\n \n ###################\n ### OAuth Logic ###\n ###################\n\n def consumer\n @consumer ||= ::OAuth::Consumer.new(config.consumer_key, config.consumer_secret, config.options)\n end\n\n def request_token\n host_with_port = Warden::OAuth::Utils.host_with_port(request)\n @request_token ||= consumer.get_request_token(:oauth_callback => host_with_port)\n end\n\n def access_token\n @access_token ||= request_token.get_access_token(:oauth_verifier => params['oauth_verifier'])\n end\n\n protected\n\n def find_user_by_access_token(access_token)\n raise RuntimeError.new(<<-ERROR_MESSAGE) unless self.respond_to?(:_find_user_by_access_token)\n \nYou need to define a finder by access_token for this strategy.\nWrite on the warden initializer the following code:\nWarden::OAuth.access_token_user_finder(:#{config.provider_name}) do |access_token|\n # Logic to get your user from an access_token\nend\n\nERROR_MESSAGE\n self._find_user_by_access_token(access_token)\n end\n\n def throw_error_with_oauth_info\n throw(:warden, :oauth => { \n self.config.provider_name => {\n :provider => config.provider_name,\n :access_token => access_token,\n :consumer_key => config.consumer_key,\n :consumer_secret => config.consumer_secret\n }\n })\n end\n\n def store_request_token_on_session\n session[:request_token] = request_token.token\n session[:request_secret] = request_token.secret\n end\n\n def load_request_token_from_session\n token = session.delete(:request_token)\n secret = session.delete(:request_secret)\n @request_token = ::OAuth::RequestToken.new(consumer, token, secret)\n end\n\n def missing_stored_token? \n !request_token\n end\n\n def stored_token_match_recieved_token?\n request_token.token == params['oauth_token']\n end\n\n def service_param_name\n '%s_oauth' % config.provider_name\n end\n\n def config\n self.class::CONFIG\n end\n\n end\n\n end\nend\n", "lib/warden_oauth.rb": "require \"rack\"\nrequire \"warden\"\nrequire \"oauth\"\n\nmodule Warden\n module OAuth\n\n base_path = File.dirname(__FILE__) + \"/warden_oauth\"\n \n require base_path + \"/base\"\n require base_path + \"/errors\"\n autoload :Utils, base_path + '/utils'\n autoload :StrategyBuilder, base_path + '/strategy_builder'\n autoload :Strategy, base_path + '/strategy'\n autoload :Config, base_path + \"/config\"\n require base_path + \"/config_extension\"\n \n\n end\nend\n"}, "files_after": {"lib/warden_oauth/strategy.rb": "module Warden\n module OAuth\n\n #\n # Holds all the main logic of the OAuth authentication, all the generated\n # OAuth classes will extend from this class\n #\n class Strategy < Warden::Strategies::Base\n extend StrategyBuilder\n\n ######################\n ### Strategy Logic ###\n ######################\n\n\n def self.access_token_user_finders\n (@_user_token_finders ||= {})\n end\n\n #\n # An OAuth strategy will be valid to execute if:\n # * A 'warden_oauth_provider' parameter is given, with the name of the OAuth service\n # * A 'oauth_token' is being receive on the request (response from an OAuth provider)\n #\n def valid?\n (params.include?('warden_oauth_provider') && params['warden_oauth_provider'] == config.provider_name.to_s) ||\n params.include?('oauth_token') \n end\n\n\n #\n # Manages the OAuth authentication process, there can be 3 outcomes from this Strategy:\n # 1. The OAuth credentials are invalid and the FailureApp is called\n # 2. The OAuth credentials are valid, but there is no user associated to them. In this case\n # the FailureApp is called, but the env['warden.options'][:oauth][:access_token] will be \n # available.\n # 3. The OAuth credentials are valid, and the user is authenticated successfuly\n #\n # @note\n # If you want to signup users with the twitter credentials, you can manage the creation of a new \n # user in the FailureApp with the given access_token\n #\n def authenticate!\n if params.include?('warden_oauth_provider')\n store_request_token_on_session\n redirect!(request_token.authorize_url(config.options))\n throw(:warden)\n elsif params.include?('oauth_token')\n load_request_token_from_session\n if missing_stored_token?\n fail!(\"There is no OAuth authentication in progress\")\n elsif !stored_token_match_recieved_token?\n fail!(\"Received OAuth token didn't match stored OAuth token\")\n else\n user = find_user_by_access_token(access_token)\n if user.nil?\n fail!(\"User with access token not found\")\n throw_error_with_oauth_info\n else\n success!(user)\n end\n end\n end\n\n end\n\n def fail!(msg) #:nodoc:\n self.errors.add(service_param_name.to_sym, msg)\n super\n end\n \n ###################\n ### OAuth Logic ###\n ###################\n\n def consumer\n @consumer ||= ::OAuth::Consumer.new(config.consumer_key, config.consumer_secret, config.options)\n end\n\n def request_token\n @request_token ||= consumer.get_request_token(:oauth_callback => config.options[:oauth_callback])\n end\n\n def access_token\n @access_token ||= request_token.get_access_token(:oauth_verifier => params['oauth_verifier'])\n end\n\n protected\n\n def find_user_by_access_token(access_token)\n raise RuntimeError.new(<<-ERROR_MESSAGE) unless self.respond_to?(:_find_user_by_access_token)\n \nYou need to define a finder by access_token for this strategy.\nWrite on the warden initializer the following code:\nWarden::OAuth.access_token_user_finder(:#{config.provider_name}) do |access_token|\n # Logic to get your user from an access_token\nend\n\nERROR_MESSAGE\n self._find_user_by_access_token(access_token)\n end\n\n def throw_error_with_oauth_info\n throw(:warden, :oauth => { \n self.config.provider_name => {\n :provider => config.provider_name,\n :access_token => access_token,\n :consumer_key => config.consumer_key,\n :consumer_secret => config.consumer_secret\n }\n })\n end\n\n def store_request_token_on_session\n session[:request_token] = request_token.token\n session[:request_secret] = request_token.secret\n end\n\n def load_request_token_from_session\n token = session.delete(:request_token)\n secret = session.delete(:request_secret)\n @request_token = ::OAuth::RequestToken.new(consumer, token, secret)\n end\n\n def missing_stored_token? \n !request_token\n end\n\n def stored_token_match_recieved_token?\n request_token.token == params['oauth_token']\n end\n\n def service_param_name\n '%s_oauth' % config.provider_name\n end\n\n def config\n self.class::CONFIG\n end\n\n end\n\n end\nend\n", "lib/warden_oauth.rb": "require \"rack\"\nrequire \"warden\"\nrequire \"oauth\"\n\nmodule Warden\n module OAuth\n\n base_path = File.dirname(__FILE__) + \"/warden_oauth\"\n \n require base_path + \"/base\"\n require base_path + \"/errors\"\n autoload :Utils, base_path + '/utils'\n autoload :StrategyBuilder, base_path + '/strategy_builder'\n autoload :Strategy, base_path + '/strategy'\n autoload :Config, base_path + \"/config\"\n require base_path + \"/config_extension\"\n \n\n end\nend\n\nrequire \"oauth2\"\n\nmodule Warden\n module OAuth2\n\n base_path = File.dirname(__FILE__) + \"/warden_oauth2\"\n \n require base_path + \"/base\"\n require base_path + \"/errors\"\n autoload :Utils, base_path + '/utils'\n autoload :StrategyBuilder, base_path + '/strategy_builder'\n autoload :Strategy, base_path + '/strategy'\n autoload :Config, base_path + \"/config\"\n require base_path + \"/config_extension\"\n \n\n end\nend\n\n"}} -{"repo": "railsfactory-shiv/rupees", "pr_number": 2, "title": "Spacing fix", "state": "closed", "merged_at": null, "additions": 43, "deletions": 38, "files_changed": ["lib/rupees.rb"], "files_before": {"lib/rupees.rb": "module NumberToRupees\n WORDS = {0=>\"zero\", 1=>\"One\", 2=>\"Two\", 3=>\"Three\", 4=>\"Four\", 5=>\"Five\", 6=>\"six\", 7=>\"seven\", 8=>\"Eight\", 9=>\"Nine\",10=>\"Ten\",11=>\"Eleven\",12=>\"Twelve\",13=>\"Thirteen\",14=>\"Fourteen\",15=>\"Fifteen\",16=>\"Sixteen\",17=>\"Seventeen\",18=>\"Eighteen\",19=>\"Nineteen\",20=>\"Twenty\",30=>\"Thirty\",40=>\"Fourty\",50=>\"Fifty\",60=>\"Sixty\",70=>\"Seventy\",80=>\"Eighty\",90=>\"Ninty\"}\n SUFIXES = {0=>\"hundred & \", 1=>\" Crore, \", 2=>\" Lakh, \", 3=>\" Thousand, \", 4=>\" Hundred, \"} # 5=>''\n module Fixnum\n def self.included(recipient)\n recipient.extend(ClassMethods)\n recipient.class_eval do\n include InstanceMethods\n end\n end\n \n module ClassMethods\n end\n \n module InstanceMethods\n def rupees\n result = self >= 0 ? \"\" : \"(-) \"\n\t num = self.abs\n \n # I would prefer One Rupee, insead of One Rupees\n return \"One Rupee.\" if num==1\n\t \n if num > 99\n num.to_s.rjust(11,'0').insert(-4,'0').scan(/../).each_with_index{|x,i| result += self.def_calc(x,i) }\n \t else\t \n result = spell_two_digits(num)\n end\n\t result.sub(/,\\s$/,'')+ \" Rupees.\"\n end\n\n protected\n def def_calc(x,i)\n str=self.proc_unit(x)\n\t return '' if str.length==0\n return \"#{str}#{SUFIXES[i]}\"\n end\n\n def proc_unit(x)\n return \"\" unless x.to_i > 0\n return spell_two_digits(x.to_i)\n end\n\t \n\t def spell_two_digits(x)\n return WORDS[x] if WORDS[x]\n r,f = x.divmod(10)\n return \"#{WORDS[r*10]}#{WORDS[f]}\"\n\t end\n end\n end \nend \nFixnum.send :include, NumberToRupees::Fixnum\n"}, "files_after": {"lib/rupees.rb": "module NumberToRupees\n WORDS = { 0 => 'zero', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'six', 7 => 'seven', 8 => 'Eight', 9 => 'Nine',\n 10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve', 13 => 'Thirteen', 14 => 'Fourteen', 15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen', 19 => 'Nineteen', 20 => 'Twenty', 30 => 'Thirty', 40 => 'Fourty', 50 => 'Fifty', 60 => 'Sixty', 70 => 'Seventy', 80 => 'Eighty', 90 => 'Ninty' }\n SUFIXES = { 0 => 'hundred & ', 1 => ' Crore, ', 2 => ' Lakh, ', 3 => ' Thousand, ', 4 => ' Hundred, ' } # 5=>''\n module Integer\n def self.included(recipient)\n recipient.extend(ClassMethods)\n recipient.class_eval do\n include InstanceMethods\n end\n end\n\n module ClassMethods\n end\n\n module InstanceMethods\n def rupees\n result = self >= 0 ? '' : '(-) '\n num = abs\n\n # I would prefer One Rupee, insead of One Rupees\n return 'One Rupee.' if num == 1\n\n if num > 99\n num.to_s.rjust(11, '0').insert(-4, '0').scan(/../).each_with_index { |x, i| result += def_calc(x, i) }\n else\n result = spell_two_digits(num)\n end\n result.sub(/,\\s$/, '')\n end\n\n protected\n\n def def_calc(x, i)\n str = proc_unit(x)\n return '' if str.length == 0\n\n \"#{str}#{SUFIXES[i]}\"\n end\n\n def proc_unit(x)\n return '' unless x.to_i > 0\n\n spell_two_digits(x.to_i)\n end\n\n def spell_two_digits(x)\n return WORDS[x] if WORDS[x]\n\n r, f = x.divmod(10)\n f.zero? ? \"#{WORDS[r*10]}\" : \"#{WORDS[r*10]} #{WORDS[f]}\"\n end\n end\n end\nend\nInteger.include NumberToRupees::Integer\n"}} -{"repo": "mediavrog/cfe", "pr_number": 1, "title": "update to mootools 1.3", "state": "closed", "merged_at": null, "additions": 83, "deletions": 68, "files_changed": ["cfe/addons/cfe.addon.dependencies.js", "cfe/addons/cfe.addon.toolTips.js", "cfe/base/cfe.base.js", "cfe/modules/button/cfe.module.button.js", "cfe/modules/check/cfe.module.checkbox.js", "cfe/modules/check/cfe.module.radio.js", "cfe/modules/file/cfe.module.file.js", "cfe/modules/select/cfe.module.select.js", "cfe/modules/select/cfe.module.select.multiple.js", "cfe/replace/cfe.replace.js", "demo.html"], "files_before": {"cfe/modules/file/cfe.module.file.js": "/**\n * @module File\n */\n\n/**\n * replaces file upload fields\n *\n *

is not resetted onReset

\n * \n *
Tested in:
\n *
    \n *
  • Safari 4 - implicitly labelled triggers when deletin a file; reset doesnt trigger
  • \n *
  • Firefox 3.6.
  • \n *
  • Google Chrome 6 - implicitly labelled triggers twice, when using alias button & triggers when deletin a file.
  • \n *
  • Opera 10.62.
  • \n *
  • IE 7 - gaga.
  • \n *
  • IE 8 - implicitly labelled triggers when deletin a file.
  • \n *
\n *\n * @class File\n * @namespace cfe.modules\n *\n * @extends cfe.module.Button\n */\n\ncfe.module.File = new Class({\n \n Extends: cfe.module.Button,\n \n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=file]\",\n\t\n options: {\n /**\n * enables the use of fileicons through a bit of markup and css\n * @config fileIcons\n * @type boolean\n * @default true\n */\n fileIcons: true,\n /**\n * show only the filename, not the whole path\n * @config trimFilePath\n * @type boolean\n * @default true\n */\n trimFilePath: true,\n\n innerLabel: \"Choose File\"\n },\n\n hideOriginalElement: false,\n\n toElement: function()\n {\n return this.wrapa\n },\n\n /**\n * retreive the filepath\n *\n * @method getFilePath\n * @return {HTMLElement}\n */\n getFilePath: function()\n {\n return this.v;\n },\n\n afterInitialize: function()\n {\n this.a = this.button;\n \n if(this.hideOriginalElement) this.o.hideInPlace();\n\n if(this.o.id) this.wrapa.addClass(cfe.prefix+this.type+this.o.id.capitalize());\n\n // various additions\n if(!this.o.implicitLabel && !Browser.Engine.webkit) this.wrapa.addEvent(\"click\", this.clicked.bindWithEvent(this));\n\n if(this.isDisabled()) this.disable();\n\n if(!this.options.slidingDoors) this.wrapa.addClass(cfe.prefix+this.type)\n\n if(this.options.buttonStyle) this.a.addClass(cfe.prefix+\"Button\")\n\n this.a.removeClass(cfe.prefix+this.type)\n },\n\n build: function()\n {\n this.parent();\n this.innerlabel.set(\"text\", $pick(this.options.innerLabel, \"\"));\n\n // make original element follow mouse\n // setup wrapper\n this.wrapa = new Element(\"span\",{\n \"class\": cfe.prefix+this.type,\n styles:\n {\n overflow: \"hidden\",\n position: \"relative\"\n }\n }).cloneEvents(this.a)\n \n this.wrapa.inject(this.a, \"after\").adopt(this.a, this.o);\n\n // add positioning styles and events to \"hidden\" file input\n this.o.addEvents({\n \"mouseout\": this.update.bind(this),\n \"change\": this.update.bind(this),\n onDisable: this.disable.bind(this),\n onEnable: this.enable.bind(this)\n }).setStyles({\n opacity: \"0\",\n visibility: \"visible\",\n height: \"100%\",\n width: \"auto\",\n position: \"absolute\",\n top: 0,\n right: 0,\n margin: 0\n });\n\n this.wrapa.addEvent(\"mousemove\", this.follow.bindWithEvent(this));\n\n this.button = this.a;\n this.a = this.wrapa;\n \n // add filepath\n this.v = new Element(\"span\").addClass(cfe.prefix+this.type+\"Path hidden\");\n\t\t\n this.path = new Element(\"span\").addClass(\"filePath\");\n\n if(this.options.fileIcons)\n {\n this.path.addClass(\"fileIcon\");\n }\n\n this.cross = $( new cfe.module.Button({delegateClick: false}).addEvent(\"click\", this.deleteCurrentFile.bind(this)) ).addClass(\"delete\");\n\n this.v.adopt(this.path, this.cross).inject(this.wrapa, \"after\");\n\n this.update();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"file\"\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n type: \"file\"\n });\n },\n\t\n follow: function(ev)\n {\n this.o.setStyle(\"left\",(ev.client.x-this.a.getLeft()-(this.o.getWidth()-30)));\n\t\t\n /* special treatment for internet explorer as the fileinput will not be cut off by overflow:hidden */\n if(Browser.Engine.trident){\n if(ev.client.x < this.a.getLeft() || ev.client.x > this.a.getLeft()+this.a.getWidth())\n this.o.setStyle(\"left\", -9999);\n }\n },\n\t\n update: function()\n {\n // only do stuff if original element is not disabled\n if( !$chk(this.o.disabled) )\n {\n if( this.o.value != \"\" )\n {\n this.o.disable().blur();\n\n this.oldValue = this.o.getProperty(\"value\");\n if(this.options.trimFilePath) this.oldValue = this.oldValue.trimFilePath();\n this.path.set(\"html\", this.oldValue);\n\n if(this.options.fileIcons)\n {\n var ind = this.oldValue.lastIndexOf(\".\");\n this.path.setProperty(\"class\",\"filePath fileIcon \" + this.oldValue.substring(++ind).toLowerCase());\n }\n this.v.removeClass(\"hidden\");\n }\n else\n {\n this.o.enable().focus();\n\n this.path.set(\"html\", \"\");\n this.v.addClass(\"hidden\");\n }\n\n this.parent();\n }\n },\n\t\n deleteCurrentFile: function()\n {\n // we dont clone the old file input here, since the attribute \"value\" would be cloned, too\n // and we cannot modify the value of an file input field without user interaction\n this.o = this.createOriginal().addClass(this.o.getProperty(\"class\")).setProperties({\n name: this.o.getProperty(\"name\"),\n id: this.o.getProperty(\"id\"),\n style: this.o.getProperty(\"style\"),\n title: this.o.getProperty(\"title\")\n }).cloneEvents(this.o).replaces(this.o);\n\t\t\n this.update();\n }\n});\n\n// add trimFilePath to Native String for convenience\nString.implement({\n trimFilePath: function()\n {\n var ind = false;\n if(!(ind = this.lastIndexOf(\"\\\\\")))\n if(!(ind = this.lastIndexOf(\"\\/\")))\n ind = 0;\n\n return this.substring(++ind);\n }\n});", "cfe/base/cfe.base.js": "/**\n * The core of custom form elements. Includes cfe.Generic and some slight addons to the native Element object. \n *\n * @module Core\n * @namespace cfe\n */\n\nvar cfe = {\n version: \"0.9.9\",\n prefix: \"cfe\",\n module: {},\n addon: {}\n};\n\n/**\n * extend Elements with some Helper functions\n * @class Helpers\n * @namespace Element\n */\nElement.Helpers = new Class({\n\n /**\n * cross-browser method for disabling the text selection by setting css attributes\n * \n * @method disableTextSelection\n */\n disableTextSelection: function(){\n if(Browser.Engine.trident || Browser.Engine.presto){\n this.setProperty(\"unselectable\",\"on\");\n }\n else if(Browser.Engine.gecko){\n this.setStyle(\"MozUserSelect\",\"none\");\n }\n else if(Browser.Engine.webkit){\n this.setStyle(\"KhtmlUserSelect\",\"none\");\n }\n\n return this;\n },\n\n /**\n * disables a HTMLElement if its a form element by setting the disabled attribute to true\n *\n * @method disable\n * @return boolean true, if element could be disabled\n */\n disable: function()\n {\n if($type(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", true);\n this.fireEvent(\"onDisable\");\n }\n\n return this;\n },\n\n /**\n * enables a HTMLElement if its a form element by setting the disabled attribute to false\n *\n * @method enable\n * @return {boolean} true, if element could be enabled\n */\n enable: function()\n {\n if($type(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", false);\n this.fireEvent(\"onEnable\");\n }\n\n return this;\n },\n\n /**\n * enables or disabled a HTMLElement if its a form element depending on it's current state\n *\n * @method toggleDisabled\n * @return {boolean} true, if element could be toggled\n */\n toggleDisabled: function()\n {\n if($type(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", !this.getProperty(\"disabled\") );\n this.fireEvent(this.getProperty(\"disabled\")?\"onDisable\":\"onEnable\");\n }\n return this;\n },\n\n /**\n * returns the label-element which belongs to this element\n *\n * @method getLabel\n * @return HTMLElement or NULL\n */\n getLabel: function()\n {\n var label = null;\n\n // get label by id/for-combo\n if(this.id) label = $$(\"label[for=\"+this.id+\"]\")[0];\n \n // no label was found for id/for, let's see if it's implicitly labelled\n if(!label)\n {\n label = this.getParent('label');\n\n if(label) this.implicitLabel = true;\n }\n\n return label;\n },\n\n /**\n * generates the markup used by sliding doors css technique to use with this element\n *\n * @method setSlidingDoors\n *\n * @param count\n * @param type\n * @param prefix\n * \n * @return HTMLElement or NULL the wrapped HTMLElement\n */\n setSlidingDoors: function(count, type, prefix, suffixes)\n {\n var slide = null;\n var wrapped = this;\n prefix = $pick(prefix, \"sd\");\n\n suffixes = $pick(suffixes, []);\n\n for(var i = count; i > 0; --i)\n {\n wrapped.addClass( prefix+\"Slide\"+( (i == 1 && count == i) ? \"\" : (suffixes[i] || i) ));\n slide = new Element(type);\n try{\n wrapped = slide.wraps(wrapped);\n }catch(e){\n wrapped = slide.grab(wrapped);\n }\n }\n\n wrapped = null;\n\n return slide;\n },\n\n /**\n * hide an element but keep it's vertical position and leave it tab- & screenreader-able :)\n *\n * @method hideInPlace\n *\n * @return HTMLElement\n */\n hideInPlace: function()\n {\n return this.setStyles({\n position: \"absolute\",\n left: -99999,\n width: 1,\n height: 1\n });\n }\n});\n\nElement.implement(new Element.Helpers);", "cfe/modules/check/cfe.module.radio.js": "/**\n * @module Checkable\n */\n\n/**\n *

replaces radiobuttons

\n *\n *
Tested in:
\n *
    \n *
  • Safari 4.
  • \n *
  • Firefox 3.6.
  • \n *
  • Google Chrome 6.
  • \n *
  • Opera 10.62.
  • \n *
  • IE 7.
  • \n *\n *
  • IE 8\n *
      \n *
    • labels dont work for normal labelled elements
    • \n *
    \n *
  • \n *\n *
\n *\n * @class Radiobutton\n * @namespace cfe.module\n *\n * @extends cfe.modules.Checkbox\n */\ncfe.module.Radiobutton = new Class({\n\n Extends: cfe.module.Checkbox,\n\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=radio]\",\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"radio\"\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n \"type\": \"radio\",\n \"checked\": this.options.checked\n });\n },\n\n /**\n * @method initializeAdv\n * @protected\n */\n afterInitialize: function()\n {\n this.parent();\n \n if( !(Browser.Engine.trident || Browser.Engine.gecko) ) this.o.addEvent(\"click\", this.update.bind(this));\n\n // on check, disable all other radiobuttons in this group\n this.addEvent(\"check\", function(){\n $$(\"input[name='\"+this.o.get(\"name\")+\"']\").each(function(el)\n {\n if(el != this.o && el.retrieve(\"cfe\")) el.retrieve(\"cfe\").uncheck();\n }.bind(this));\n })\n }\n});", "cfe/replace/cfe.replace.js": "/**\n * replacement class for automated replacment of scoped form elements\n *\n * @module replace\n * @namespace cfe\n *\n */\n\ncfe.Replace = new Class(\n{\n Implements: [new Options, new Events],\n\n options:{\n scope: false,\n\t\t\n onInit: $empty,\n onInitSingle: $empty,\n onBeforeInitSingle: $empty,\n onSetModuleOption: $empty,\n onRegisterModule: $empty,\n onUnregisterModule: $empty,\n onComplete: $empty\n },\n\t\t\n modules: {},\n moduleOptions: {},\n moduleOptionsAll: {},\n\t\n initialize: function()\n {\n this.registerAllModules.bind(this)();\n },\n\t\n /**\n * @method registerAllModules\n\t * registeres all loaded modules onInitialize\n\t */\n registerAllModules: function(){\n\t\t\n //console.log(\"Register all modules\");\n\t\t\n $each(cfe.module, function(modObj, modType){\n //console.log(\"Registering type \"+modType);\n if(modType != \"Generic\")\n this.registerModule(modType);\n\t\t\t\t\n }.bind(this));\n },\n\t\n /* call to register module */\n registerModule: function(mod){\n\t\t\n //console.log(\"Call to registerModule with arg:\"+mod);\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onRegisterModule\", [mod,modObj]);\n this.modules[mod] = modObj;\n this.moduleOptions[mod] = {};\n\n return true;\n },\n\t\n registerModules: function(mods)\n {\n $each(mods,function(mod){\n this.registerModule(mod);\n },this);\n },\n\t\n unregisterModule: function(mod)\n {\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onUnregisterModule\", [mod,modObj]);\n\n delete this.modules[mod];\n },\n\t\n unregisterModules: function(mods)\n {\n $each(mods,function(mod){\n this.unregisterModule(mod);\n },this);\n },\n /**\n\t * sets a single option for a specified module\n\t * if no module was given, it sets the options for all modules\n\t *\n * @method setModuleOption\n *\n\t * @param {String} \tmod \tName of the module\n\t * @param {String} \topt \tName of the option\n\t * @param {Mixed} \tval\t\tThe options value\n\t */\n setModuleOption: function(mod,opt,val){\n\t\t\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onSetModuleOption\", [mod,modObj,opt,val]);\n\t\t\n if(!modObj){\n this.moduleOptionsAll[opt] = val;\n }\n else{\n this.moduleOptions[mod][opt] = val;\n }\n },\n\n setModuleOptions: function(mod,opt){\n\t\t\n $each(opt, function(optionValue, optionName){\n this.setModuleOption(mod,optionName,optionValue);\n }.bind(this));\n\t\t\n },\n\n engage: function(options){\n\n this.setOptions(this.options, options);\n\n if($type(this.options.scope) != \"element\"){\n this.options.scope = $(document.body);\n }\n\n this.fireEvent(\"onInit\");\n\t\t\n $each(this.modules,function(module,moduleName,i){\n\t\t\t\n var selector = module.prototype.selector;\n\t\t\t\n this.options.scope.getElements(selector).each(function(el,i){\n\n if(el.retrieve(\"cfe\") != null){\n\n var basicOptions = {\n replaces: el\n };\n\n this.fireEvent(\"onBeforeInitSingle\", [el,i,basicOptions]);\n\n var single = new module($merge(basicOptions,$merge(this.moduleOptions[moduleName],this.moduleOptionsAll)));\n\t\t\t\t\n this.fireEvent(\"onInitSingle\", single);\n }else{\n this.fireEvent(\"onSkippedInitSingle\", [el,i,basicOptions]); \n }\n\t\t\t\t\n },this);\n },this);\n\t\t\n this.fireEvent(\"onComplete\");\n }\n});", "cfe/modules/check/cfe.module.checkbox.js": "/**\n * @module Checkable\n */\n\n/**\n *

replaces checkboxes

\n * \n *
Tested in:
\n *
    \n *
  • Safari 4.
  • \n *
  • Firefox 3.6.
  • \n *
  • Google Chrome 6.
  • \n *
  • Opera 10.62.
  • \n *
  • IE 7.
  • \n *
  • IE 8.
  • \n *
\n *\n * @class Checkbox\n * @namespace cfe.module\n * \n * @extends cfe.module.Button\n */\ncfe.module.Checkbox = new Class({\n \n Extends: cfe.module.Button,\n \n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=checkbox]\",\n\n options:{\n /**\n * @inherit\n */\n slidingDoors: false\n /**\n * Fired when the original element gets checked\n * @event onCheck\n */\n //onCheck: Class.empty,\n /**\n * Fired when the original element's checked state is set to false\n * @event onUnCheck\n */\n //onUncheck: Class.empty\n },\n\n afterInitialize: function()\n {\n this.parent();\n\n // important for resetting dynamically created cfe\n this.o.defaultChecked = this.o.checked;\n\n if( Browser.Engine.presto || Browser.Engine.trident )\n {\n //console.log(\"fix for element update (IE and Opera)\")\n this.o.addEvent(\"click\", this.update.bind(this) );\n }\n\n\n if(Browser.Engine.trident && this.o.implicitLabel)\n {\n //console.log(\"fix for implicit labels (IE) element[\"+this.o.id+\"]\")\n this.l.removeEvents(\"click\")\n this.a.removeEvents(\"click\").addEvent(\"click\", function(e){\n e.stop();\n this.clicked.bind(this)();\n }.bind(this))\n }\n\n this.update();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"checkbox\"\n * @protected\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n type: \"checkbox\",\n checked: this.options.checked\n });\n },\n\n clicked: function(e)\n {\n if(Browser.Engine.trident && e) e.stop();\n\n this.parent()\n },\n\n /**\n * public method to check a checkbox programatically\n *\n * @method check\n * @public\n */\n check: function()\n {\n this.a.addClass(\"A\");\n this.fireEvent(\"onCheck\");\n },\n\n /**\n * public method to uncheck a checkbox programatically\n *\n * @method uncheck\n * @public\n */\n uncheck: function()\n {\n this.a.removeClass(\"A\");\n this.fireEvent(\"onUncheck\");\n },\n\n update: function()\n {\n this.o.checked ? this.check() : this.uncheck();\n this.parent();\n }\n});", "cfe/addons/cfe.addon.toolTips.js": "/**\n * @module Addon\n */\n\n/**\n * pretty simple integration of auto-generated tooltips (from title-attribute)\n * depends on mootools Tips\n *\n * @class Tips\n * @namespace cfe.addon\n *\n */\ncfe.addon.Tips = new Class({\n\t\n options: $merge(this.parent, {\n enableTips: true,\n ttStyle: \"label\",\n ttClass: cfe.prefix+\"Tip\"\n }),\n\t\n initToolTips: function(){\n\t\t\n if(!window.Tips || !this.options.enableTips){\n if(this.options.debug){\n this.throwMsg.bind(this)(\"CustomFormElements: initialization of toolTips failed.\\nReason: Mootools Plugin 'Tips' not available.\");\n }\n \n return false;\n }\n\t\n switch(this.options.ttStyle){\n default:case 'label': this.toolTipsLabel.bind(this)();break;\n }\n\n return true;\n },\n\t\n toolTipsLabel: function(){\n\t\t\n var labels = this.options.scope.getElements('label');\n \t\t\n labels.each(function(lbl,i){\n\n forEl = lbl.getProperty(\"for\");\n\t\t\t\n if(!forEl){\n var cl = lbl.getProperty(\"class\");\n\t\t\t\t\n if( $defined(cl) ){\n var forEl = cl.match(/for_[a-zA-Z0-9\\-]+/);\n\n if(forEl){\n forEl = forEl.toString();\n el = $( forEl.replace(/for_/,\"\") );\n } \n }\n\t\t\t\t\n if(!el){\n el = lbl.getElement(\"input\");\n }\n }else{\n el = $(forEl);\n }\n\n if(el){\n if($chk(qmTitle = el.getProperty(\"title\"))){\n\t\t\t\t\t\n el.setProperty(\"title\",\"\").setProperty(\"hint\", qmTitle)\n\t\t\t\t\t\n var qm = new Element(\"span\",{\n \"class\": this.options.ttClass,\n \"title\": qmTitle\n });\n \n // check if implicit label span is present\n var impLabel = lbl.getFirst(\"span[class=label]\");\n \n qm.injectInside($chk(impLabel)?impLabel:lbl);\n }\n }\n },this);\n\t\t\n new Tips($$('.'+this.options.ttClass+'[title]'));\n }\n});\n\ncfe.Replace.implement(new cfe.addon.Tips);\ncfe.Replace.prototype.addEvent(\"onComplete\", function(){\n this.initToolTips();\n});", "cfe/addons/cfe.addon.dependencies.js": "/**\n * @module Addon\n */\n\n/**\n * adds dependencies to checkboxes\n *\n * @class Dependencies\n * @namespace cfe.addon\n *\n */\ncfe.addon.Dependencies = new Class({\n\t\n /**\n\t * adds dependencies for an element \n\t * @param {Object} el\n\t * @param {Array} dep\n\t */\n addDependencies: function(el, deps){\n $each(deps,function(dep){\n this.addDependency(el,dep);\n }.bind(this));\n },\n\t\n /**\n\t * adds dependency for an element \n\t * @param {Object} el\n\t * @param {Object} dep\n\t */\n addDependency: function(el, dep){\n\t\t\n // create an array if needed\n if($type( el.retrieve('deps') ) !== \"array\"){\n el.store('deps', []);\n }\n\t\t\n // deps may be objects or strings > if a string was given, try to interpret it as id and fetch element by $()\n if($type(dep) === \"string\" || $type(dep) === \"element\"){\n el.retrieve('deps').push( $(dep) );\n return true;\n }\n\t\t\n return false;\n },\n\t\n getDependencies: function(el)\n {\n return el.retrieve('deps');\n },\n\t\n /**\n\t * this is called when a new item of a cfemodule gets initialized\n\t * it checks, whether there are dependencies for this element and adds them to its options\n\t * \n\t * @param {Object} el\n\t */\n attachDependencies: function(el,i,baseOptions)\n {\n var deps = this.getDependencies(el);\n\t\t\n if($type(deps) === \"array\"){\n baseOptions.deps = deps;\n return true;\n }\n\t\n return false;\n }\n\t\t\n});\ncfe.Replace.implement(new cfe.addon.Dependencies);\ncfe.Replace.prototype.addEvent(\"onBeforeInitSingle\", cfe.Replace.prototype.attachDependencies);\n\ncfe.addon.Dependencies.Helper = new Class({\n resolveDependencies: function()\n {\n var deps = this.o.retrieve('deps');\n\t\t\n if(deps){\n $each(deps, function(dep,i){\n dep.checked = true;\n dep.fireEvent(\"change\");\n }.bind(this));\n }\n }\n});\n\n// support for checkboxes\ncfe.module.Checkbox.implement(new cfe.addon.Dependencies.Helper);\ncfe.module.Checkbox.prototype.addEvent(\"onCheck\", function(){\n this.resolveDependencies();\n});", "cfe/modules/button/cfe.module.button.js": "/**\n * @module Button\n */\n\n/**\n * gets extended by modules to start off with standard, button-like behaviours.\n *\n * when focused and pressed, form gets submitted\n *\n * @class Button\n * @namespace cfe.module\n *\n */\ncfe.module.Button = new Class(\n{\n Implements: [new Options, new Events],\n\n selector: \"button\",\n\n instance: 0,\n\n /**\n * basic options for all cfes and always available\n * @property options\n */\n options: {\n /**\n * if > 0, it will create markup for css sliding doors tech
\n * the number defines the amount of wrappers to create around this element
\n * 2: standard sliding doors (x- or y-Axis)
\n * 4: sliding doors in all directions (x/y-Axis)\n *\n * @config slidingDoors\n * @type int\n * @default 4\n */\n slidingDoors: 2,\n\n /**\n * if this element shall replace an existing html form element, pass it here\n * @config replaces\n * @type HTMLElement\n */\n replaces: null,\n\n /**\n * determines if a click on the decorator should be delegated to the original element\n * @config delegateClick\n * @type Boolean\n */\n delegateClick: true,\n\n /**\n * may pass any element as a label (toggling, hovering,..) for this cfe\n * @config label\n * @type HTMLElement\n */\n label: null,\n\n /**\n * if this cfe is created programatically, it's possible to set the name attribute of the generated input element\n * @config name\n * @type string\n */\n name: \"\",\n\n /**\n * setting this to true will create a disabled element\n * @config disabled\n * @type boolean\n */\n disabled: false,\n\n buttonStyle: true\n\n /**\n * Fired when the mouse is moved over the \"decorator\" element\n * @event onMouseOver\n */\n //onMouseOver: Class.empty,\n\n /**\n * Fired when the mouse is moved away from the \"decorator\" element\n * @event onMouseOut\n */\n //onMouseOut: Class.empty,\n\n /**\n * Fired when the \"original\" element gets focus (e.g. by tabbing)\n * @event onFocus\n */\n //onFocus: Class.empty,\n\n /**\n * Fired when the \"original\" element loses focus\n * @event onBlur\n */\n //onBlur: Class.empty,\n\n /**\n * Fired when \"decorator\" is clicked by mouse\n * @event onClick\n */\n //onClick: Class.empty,\n\n /**\n * Fired when pressing down with the mouse button on the \"decorator\"\n * Fired when pressing the space key while \"original\" has focus\n * @event onPress\n */\n //onPress: Class.empty,\n\n /**\n * Fired when \"decorator\" was pressed and the mouse button is released\n * Fired when \"original\" was pressed by space key and this key is released\n * @event onRelease\n */\n //onRelease: Class.empty,\n\n /**\n * Fired when \"original\"'s value changes\n * @event onUpdate\n */\n //onUpdate: Class.empty,\n\n /**\n * Fired when \"original\" gets disabled by HTMLElement.enable()\n * @event onEnable\n */\n //onEnable: Class.empty,\n\n /**\n * Fired when \"original\" gets disabled by HTMLElement.disable()\n * @event onDisable\n */\n //onDisable: Class.empty,\n\n /**\n * Fired when decorator is completely loaded and is ready to use\n * @event onLoad\n */\n //onLoad: Class.empty\n\n\n },\n\n hideOriginalElement: true,\n\n /**\n * constructor
\n * building algorithm for cfe (template method)
\n *
    \n *
  1. setOptions: set Options
  2. \n *
  3. buildWrapper: setup the \"decorator\"
  4. \n *
  5. setupOriginal: procede the \"original\" element (add Events...)
  6. \n *
  7. addLabel: add and procede the label
  8. \n *
  9. initializeAdv: last chance for subclasses to do initialization
  10. \n *
  11. build: various specific dom handling and \"decorator\" building
  12. \n *\n * @method initialize\n * @constructor\n *\n * @param {Object} options\n **/\n initialize: function(opt)\n {\n // sets instance id\n this.instance = this.constructor.prototype.instance++;\n\n this.setOptions(opt);\n\n this.type = $pick(this.options.type, $H(cfe.module).keyOf(this.constructor));\n\n this.buildWrapper();\n\n // prepares original html element for use with cfe and injects decorator into dom\n this.setupOriginal();\n\n // add a label, if present\n this.addLabel( $pick(this.o.getLabel(), this.setupLabel(this.options.label) ) );\n\n this.build();\n\n // add events to wrapping element\n this.setupWrapperEvents();\n\n // specific initialization\n this.afterInitialize();\n\n this.fireEvent(\"load\")\n },\n\n /**\n * retreive the \"decorator\"\n * mootools supports the use of $(myCfe) if toElement is defined\n *\n * @method toElement\n * @return {HTMLElement}\n */\n toElement: function()\n {\n return this.a;\n },\n\n /**\n * retreive the label\n *\n * @method getLabel\n * @return {HTMLElement}\n */\n getLabel: function()\n {\n return this.l;\n },\n\n /**\n * template method STEP 1\n */\n buildWrapper: function(){\n this.a = new Element(\"span\");\n },\n\n /**\n * handles the creation of the underlying original form element
    \n * stores a reference to the cfe object in the original form element\n * template method STEP 2\n *\n * @method setupOriginal\n * @protected\n */\n setupOriginal: function()\n {\n // get original element\n if( $defined(this.options.replaces) )\n {\n this.o = this.options.replaces;\n this.a.inject(this.o, 'before');\n }\n else // standalone\n {\n this.o = this.createOriginal();\n\n if(this.options.id) this.o.setProperty(\"id\", this.options.id);\n\n if(this.options.disabled) this.o.disable();\n\n if(this.options.name)\n {\n this.o.setProperty(\"name\", this.options.name);\n\n if( !$chk(this.o.id) ) this.o.setProperty(\"id\", this.options.name+this.instance);\n }\n\n if(this.options.value) this.o.setProperty(\"value\", this.options.value);\n\n this.a.adopt(this.o);\n }\n\n this.o.addEvents({\n focus: this.setFocus.bind(this),\n blur: this.removeFocus.bind(this),\n change: this.update.bind(this),\n keydown: function(e){\n if(e.key == \"space\") this.press();\n }.bind(this),\n keyup: function(e){\n if(e.key == \"space\") this.release();\n }.bind(this),\n onDisable: function(){\n this.a.fireEvent(\"disable\");\n }.bind(this),\n onEnable: function(){\n this.a.fireEvent(\"enable\");\n }.bind(this)\n });\n\n // store a reference to this cfe \"in\" the original form element\n this.o.store(\"cfe\", this);\n },\n\n /*\n * adds a label element to this cfe\n * template method STEP 3\n *\n * @method addLabel\n * @protected\n *\n * @param {HTMLElement} the label element to set as label for this cfe\n */\n addLabel: function(label)\n {\n if( !$defined(label) ) return;\n\n this.l = label;\n\n // remove for property\n if(!this.dontRemoveForFromLabel) this.l.removeProperty(\"for\");\n\n // add adequate className, add stdEvents\n this.l.addClass(cfe.prefix+this.type+\"L\");\n\n if(this.o.id || this.o.name) this.l.addClass(\"for_\"+ (this.o.id || (this.o.name+this.o.value).replace(\"]\",\"-\").replace(\"[\",\"\") ));\n\n // add stdevents\n this.l.addEvents({\n mouseover: this.hover.bind(this),\n mouseout: this.unhover.bind(this),\n mousedown: this.press.bind(this),\n mouseup: this.release.bind(this),\n click: this.clicked.bindWithEvent(this)\n });\n\n this.addEvents({\n press: function()\n {\n this.l.addClass(\"P\");\n },\n release: function()\n {\n this.l.removeClass(\"P\");\n },\n mouseOver: function()\n {\n this.l.addClass(\"H\");\n },\n mouseOut: function()\n {\n this.l.removeClass(\"H\");\n this.l.removeClass(\"P\");\n },\n focus: function()\n {\n this.l.addClass(\"F\");\n },\n blur: function()\n {\n this.l.removeClass(\"F\");\n //this.l.removeClass(\"P\");\n },\n enable: function()\n {\n this.l.removeClass(\"D\");\n },\n disable: function()\n {\n this.l.addClass(\"D\");\n }\n });\n },\n\n /**\n * part of the main template method for building the \"decorator\"
    \n * must be extended by subclasses\n *\n * template method STEP 4\n *\n * @method build\n * @protected\n */\n build: function(){\n\n this.innerlabel = this.setupInnerLabel();\n this.a.adopt(this.innerlabel);\n\n if( $chk(this.options.slidingDoors) )\n {\n this.a = this.a.setSlidingDoors(this.options.slidingDoors-1, \"span\", cfe.prefix).addClass(cfe.prefix+this.type);\n }\n },\n\n\n /**\n * adds events and mousepointer style to the \"decorator\"\n * usually gets called by buildWrapper\n *\n * template method STEP 5\n *\n * @method setupWrapperEvents\n * @protected\n */\n setupWrapperEvents: function()\n {\n if(!this.o.implicitLabel)\n {\n this.a.addEvents({\n mouseover: this.hover.bind(this),\n mouseout: this.unhover.bind(this),\n mousedown: this.press.bind(this),\n mouseup: this.release.bind(this)\n });\n }\n\n this.a.addEvents({\n disable: this.disable.bind(this),\n enable: this.enable.bind(this)\n })\n \n },\n\n /**\n * part of the main template method for building the \"decorator\"
    \n * gets called immediately before the build-method
    \n * may be extended by subclasses\n *\n * template method STEP 6\n *\n * @method initializeAdv\n * @protected\n */\n afterInitialize: function()\n {\n if(this.hideOriginalElement) this.o.hideInPlace();\n\n if(this.o.id) this.a.addClass(cfe.prefix+this.type+this.o.id.capitalize());\n\n // various additions\n if(!this.o.implicitLabel) this.a.addEvent(\"click\", this.clicked.bindWithEvent(this));\n\n if(this.isDisabled()) this.a.fireEvent(\"disable\");\n\n if(!this.options.slidingDoors) this.a.addClass(cfe.prefix+this.type)\n\n if(this.options.buttonStyle) this.a.addClass(cfe.prefix+\"Button\")\n },\n\n setupInnerLabel: function(){\n return new Element(\"span\").addClass(\"label\").disableTextSelection();\n },\n\n\n /**\n * getter for retrieving the disabled state of the \"original\" element\n *\n * @method isDisabled\n * @return boolean\n */\n isDisabled: function()\n {\n return this.o.getProperty(\"disabled\")\n },\n\n /**\n * programatically creates an \"original\" element
    \n * each subclass has to implement this\n *\n * @method createOriginal\n * @return {HTMLElement}\n */\n createOriginal: function()\n {\n return new Element(\"button\")\n },\n\n /*\n * creates a label element and fills it with the contents (may be html) given by option \"label\"\n *\n * @method setupLabel\n * @protected\n *\n * @return {HTMLElement or NULL} if option \"label\" is not set\n */\n setupLabel: function()\n {\n if( $defined(this.options.label) ) return new Element(\"label\").set(\"html\", this.options.label).setProperty(\"for\", this.o.id);\n\n return null;\n },\n\n /**\n * wrapper method for event onPress
    \n * may be extended by subclasses\n *\n * @method press\n * @protected\n */\n press: function()\n {\n if(this.isDisabled()) return\n\n this.a.addClass(\"P\");\n this.fireEvent(\"onPress\");\n\n //console.log(this.type + \"pressed\");\n },\n\n /**\n * wrapper method for event onRelease
    \n * may be extended by subclasses\n *\n * @method release\n * @protected\n */\n release: function()\n {\n if(this.isDisabled()) return\n\n this.a.removeClass(\"P\");\n this.fireEvent(\"onRelease\");\n \n //console.log(this.type + \"released\");\n\n },\n\n /**\n * wrapper method for event onMouseOver
    \n * may be extended by subclasses\n *\n * @method onMouseOver\n * @protected\n */\n hover: function()\n {\n if(this.isDisabled()) return\n\n this.a.addClass(\"H\");\n this.fireEvent(\"onMouseOver\");\n\n //console.log(this.type + \"hovered\");\n },\n\n /**\n * wrapper method for event onMouseOut
    \n * may be extended by subclasses\n *\n * @method unhover\n * @protected\n */\n unhover: function()\n {\n if(this.isDisabled()) return\n\n this.a.removeClass(\"H\");\n this.fireEvent(\"onMouseOut\");\n this.release();\n\n //console.log(this.type + \"unhovered\");\n },\n\n /**\n * wrapper method for event onFocus
    \n * may be extended by subclasses\n *\n * @method setFocus\n * @protected\n */\n setFocus: function()\n {\n this.a.addClass(\"F\");\n this.fireEvent(\"onFocus\");\n\n //console.log(this.type + \"focused\");\n },\n\n /**\n * wrapper method for event onBlur
    \n * may be extended by subclasses\n *\n * @method removeFocus\n * @protected\n */\n removeFocus: function()\n {\n //console.log(\"o blurred\");\n this.a.removeClass(\"F\");\n // if cfe gets blurred, also clear press state\n //this.a.removeClass(\"P\");\n this.fireEvent(\"onBlur\");\n\n //console.log(this.type + \"blurred\");\n\n },\n\n /**\n * wrapper method for event onClick
    \n * delegates the click to the \"original\" element
    \n * may be extended by subclasses\n *\n * @method clicked\n * @protected\n */\n clicked: function(e)\n {\n //causes problems in other browsers than ie - gonna took into this later; its the best approach to stop the event from bubbling right here though imho\n //e.stop();\n\n if(this.isDisabled()) return\n\n if( $chk(this.o.click) && $chk(this.options.delegateClick) ) this.o.click();\n this.o.focus();\n\n this.fireEvent(\"onClick\");\n\n //console.log(this.type + \" clicked\");\n },\n\n /**\n * wrapper method for event onUpdate
    \n * may be extended by subclasses\n *\n * @method update\n * @protected\n */\n update: function()\n {\n this.fireEvent(\"onUpdate\");\n\n //console.log(\"o was updated\");\n },\n\n /**\n * wrapper method for event onEnable
    \n * may be extended by subclasses\n *\n * @method enable\n * @protected\n */\n enable: function()\n {\n this.a.removeClass(\"D\");\n this.fireEvent(\"onEnable\");\n\n //console.log(this.type+\"-\"+this.instance+\" now enabled\");\n },\n\n /**\n * wrapper method for event onDisable
    \n * may be extended by subclasses\n *\n * @method disable\n * @protected\n */\n disable: function()\n {\n this.a.addClass(\"D\");\n this.fireEvent(\"onDisable\");\n\n //console.log(this.type+\"-\"+this.instance+\" now disabled\");\n }\n});", "cfe/modules/select/cfe.module.select.js": "/**\n * @module Scrollable\n */\n\n/**\n * SCROLLING functionality for select boxes;\n * TODO: refactor to standalone module\n * \n * creates handles and sets up a slider object\n *\n * @class Scrollable\n * @namespace cfe.helper\n *\n * \n */\ncfe.helper = cfe.helper || {}\n\ncfe.helper.Scrollable = {\n\n options: {\n size: 4,\n scrolling: true\n },\n \n setupScrolling: function()\n {\n // slider config\n this.scrollerWrapper = new Element(\"span\",{\n \"class\": cfe.prefix+\"ScrollerWrapper\",\n \"styles\":{\n height: this.container.getHeight()\n }\n }).inject(this.container, \"after\");\n\n var scrollTimer, scrollTimeout;\n var scrollStepHeight = this.allOptions[0].getHeight();\n\n function scroll(by){\n clearInterval(scrollTimer);\n clearTimeout(scrollTimeout);\n\n slider.set(slider.step+by);\n\n scrollTimeout = (function(){\n scrollTimer = (function(){\n slider.set(slider.step+by);\n }.bind(this)).periodical(50)\n }.bind(this)).delay(200)\n }\n\n function clearScroll(){\n clearInterval(scrollTimer);\n clearTimeout(scrollTimeout);\n }\n\n this.scrollerTop = $(new cfe.module.Button({\n delegateClick: false\n }).addEvent(\"release\", clearScroll).addEvent(\"press\", scroll.pass(-1))).addClass(\"scrollTop\");\n\n this.scrollerBottom = $(new cfe.module.Button({\n delegateClick: false\n }).addEvent(\"release\", clearScroll).addEvent(\"press\", scroll.pass(1))).addClass(\"scrollBottom\")\n\n this.scrollerKnob = new Element(\"span\").addClass(\"scrollKnob\");\n this.scrollerBack = new Element(\"span\").addClass(\"scrollRail\");\n\n this.scrollerBack.adopt(this.scrollerKnob);\n this.scrollerWrapper.adopt(this.scrollerBack, this.scrollerTop, this.scrollerBottom);\n\n var slider = new Slider(this.scrollerBack, this.scrollerKnob, {\n steps: this.allOptions.length-this.options.size,\n mode: \"vertical\" ,\n onChange: function(step){\n this.container.scrollTo(false,step*scrollStepHeight);\n }.bind(this)\n }).set(this.selectedIndex);\n\n this.scrollerKnob.setStyle(\"position\", \"absolute\");\n\n // scrolling\n function wheelListener(ev)\n {\n ev.stop();\n slider.set(slider.step-ev.wheel);\n }\n\n this.boundWheelListener = wheelListener.bindWithEvent(this)\n\n this.addEvent(\"containerShow\", function(){\n $(document.body).addEvent(\"mousewheel\", this.boundWheelListener)\n\n slider.set(this.o.selectedIndex);\n this.container.scrollTo(false,this.o.selectedIndex*scrollStepHeight);\n })\n\n this.addEvent(\"containerHide\", function(){\n $(document.body).removeEvent(\"mousewheel\", this.boundWheelListener);\n })\n\n this.o.addEvent(\"change\", function(){\n slider.set(this.o.selectedIndex)\n }.bind(this))\n }\n}\n\n/**\n * @module Selectable\n */\n\n/**\n * replaces select fields\n *\n *

    disabled should also disable scrolling

    \n * \n *
    Tested in:
    \n *
      \n *
    • Safari 4.
    • \n *
    • Firefox 3.6.
    • \n *
    • Google Chrome 6.
    • \n *
    • Opera 10.62 - key autocompletion closes box.
    • \n *
    • IE 7.
    • \n *
    • IE 8.
    • \n *
    \n *\n * @class Select\n * @namespace cfe.module\n *\n * @extends cfe.module.Button\n *\n */\ncfe.module.Select = new Class({\n\t\n Extends: cfe.module.Button,\n Implements: cfe.helper.Scrollable,\n \n Binds: \"clickedOutsideListener\",\n\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"select:not(select[multiple])\",\n\t\n selectedIndex: 0,\n\n setupOriginal: function()\n {\n this.parent();\n \n this.o.addEvents({\n \"keyup\": this.keyup.bind(this),\n \"keydown\": this.keydown.bind(this)\n });\n },\n\n afterInitialize: function()\n {\n this.parent();\n\n // set width to widest option if no width is given to select via css\n if(this.cssWidth == \"auto\") this.a.setStyle(\"width\", this.container.getWidth())\n\n // inject labelArrow as IE 7 doesn't support :after css selector\n if(Browser.Engine.trident5) new Element(\"span\").addClass(\"labelArrow\").inject(this.innerlabel, \"after\")\n\n // select default option\n if(this.selectedIndex != -1) this.selectOption(this.selectedIndex, true);\n\n if(this.options.scrolling)\n {\n this.container.setStyle(\"height\", this.allOptions[0].getHeight()*this.options.size);\n this.setupScrolling();\n }\n\n this.hideContainer();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} a select input\n */\n createOriginal: function()\n {\n var ori = new Element(\"select\");\n\n if( $chk(this.options.options) )\n {\n for(var key in this.options.options)\n {\n ori.adopt( new Element(\"option\", {\n value: key,\n selected: this.options.options[key].selected?\"selected\":\"\"\n }).set(\"html\", this.options.options[key].label ) );\n }\n }\n return ori;\n },\n\n build: function()\n {\n this.origOptions = this.o.getChildren();\n\n this.selectedIndex = this.o.selectedIndex || this.selectedIndex;\n\n // integrity check\n if(this.options.size > this.origOptions.length || this.options.scrolling != true) this.options.size = this.origOptions.length;\n \n this.parent();\n\n this.a.setStyles({\"position\": \"relative\", \"z-index\": 100000 - this.instance});\n\n // build container which shows on click\n this.buildContainer();\n\n this.cssWidth = this.a.getStyle(\"width\");\n },\n\n buildContainer: function()\n {\n this.container = new Element(\"span\",{\n \"class\": cfe.prefix+this.type+\"Container\",\n \"styles\":{\n \"overflow\":\"hidden\"\n }\n });\n \n this.containerWrapper = this.container.setSlidingDoors(4, \"span\", cfe.prefix).addClass(cfe.prefix+this.type+\"ContainerWrapper\").setStyles({\n position: \"absolute\",\n \"z-index\": this.instance + 1\n }).inject(this.a);\n\n // insert option elements\n this.allOptions = [];\n this.origOptions.each(function(el,i)\n {\n this.allOptions.push(this.buildOption(el, i))\n }.bind(this));\n\n this.container.adopt(this.allOptions);\n\n },\n\n buildOption: function(el, i)\n {\n return new Element(\"span\",{\n \"class\": cfe.prefix+\"Option \"+cfe.prefix+\"Option\"+i+(el.get('class')?\" \"+el.get('class'):\"\"),\n \"events\":{\n \"mouseover\": this.highlightOption.pass([i,true],this)/*,\n \"mouseout\": this.highlightOption.pass([i,true],this)*/\n }\n }).set('html', el.innerHTML.replace(/\\s/g, \" \")).disableTextSelection().store(\"index\", i);\n },\n\n selectOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n this.highlightOption(index);\n\n this.selectedIndex = index;\n\n this.innerlabel.set('html', (this.allOptions[index]).innerHTML);\n\n this.fireEvent(\"onSelectOption\", index);\n },\n\n highlightOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n if(this.highlighted) this.highlighted.removeClass(\"H\");\n\n this.highlighted = this.allOptions[index].addClass(\"H\");\n\n this.highlightedIndex = index;\n\n this.fireEvent(\"onHighlightOption\", index);\n },\n\n updateOption: function(by)\n {\n // fix for IE 7\n if(this.containerWrapper.retrieve(\"hidden\") != true && !Browser.Engine.trident5) this.o.selectedIndex = (this.highlightedIndex+by).limit(0,this.origOptions.length-1);\n this.o.fireEvent(\"change\");\n },\n\n hideContainer: function()\n {\n $(document.body).removeEvent(\"click\", this.clickedOutsideListener);\n \n this.containerWrapper.setStyle(\"display\",\"none\").removeClass(\"F\").store(\"hidden\", true);\n\n this.fireEvent(\"onContainerHide\", this.selectedIndex);\n },\n\n showContainer: function()\n {\n $(document.body).addEvent(\"click\", this.clickedOutsideListener);\n\n this.containerWrapper.setStyle(\"display\", \"block\").addClass(\"F\").store(\"hidden\", false);\n\n this.highlightOption(this.o.selectedIndex);\n\n this.fireEvent(\"onContainerShow\", this.selectedIndex);\n },\n\n clicked: function(ev)\n {\n if(!this.isDisabled())\n {\n if( $defined(ev.target) )\n {\n var oTarget = $(ev.target);\n\n if( oTarget.getParent() == this.container )\n {\n this.selectOption(oTarget.retrieve(\"index\"), true);\n this.hideContainer();\n this.parent();\n this.o.selectedIndex = oTarget.retrieve(\"index\");\n this.o.fireEvent(\"change\");\n return;\n }\n else if(this.options.scrolling && oTarget.getParent(\".\"+this.scrollerWrapper.getProperty(\"class\")) == this.scrollerWrapper)\n {\n //console.log(\"no toggle\");\n return;\n }\n }\n\n this.toggle();\n this.parent();\n }\n },\n\n toggle: function()\n {\n this.containerWrapper.retrieve(\"hidden\") == true ? this.showContainer() : this.hideContainer();\n },\n\t\n keyup: function(ev)\n {\n // toggle on alt+arrow\n if(ev.alt && (ev.key == \"up\" || ev.key == \"down\") )\n {\n this.toggle();\n return;\n }\n\n switch(ev.key){\n case \"enter\":\n case \"space\":\n this.toggle();\n break;\n\n case \"up\":\n this.updateOption(-1);\n break;\n\n case \"down\":\n this.updateOption(1);\n break;\n\n case \"esc\":\n this.hideContainer();\n break;\n \n default:\n this.o.fireEvent(\"change\");\n break;\n }\n },\n\n keydown: function(ev)\n {\n if(ev.key == \"tab\")\n {\n this.hideContainer();\n }\n },\n\n clickedOutsideListener: function(ev)\n {\n if ($(ev.target).getParent(\".\"+cfe.prefix+this.type) != this.a && !( (Browser.Engine.trident || (Browser.Engine.presto && Browser.Engine.version > 950)) && ev.target == this.o) && ( !$chk(this.l) || (this.l && $(ev.target) != this.l) ) ) this.hideContainer();\n },\n\n update: function()\n {\n this.parent();\n this.selectOption(this.o.selectedIndex);\n }\n});", "demo.html": "\n\n \n \n \n\n \n \n \n \n\n \n \n

    CFE Barebone Example

    \n

    for mootools 1.2

    \n

    \n Visit homepage\n

    \n\n
    \n\n\n
    Checkboxes (input[checkbox])\n \n\n
    \n\n
    Checkboxes with implicit labelling\n

    NOTE: 3rd Checkbox has dependencies: 1st and 2nd get automatically checked if not already

    \n
      \n
    • \n
    • \n\n
    • \n
    • \n\n
    • \n\n
    \n
    \n\n\n
    Radiobuttons (input[radio])\n
      \n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • \n
    • \n\n
    • \n
    • \n\n\n
    • \n
    • \n\n
    • \n
    • \n
    \n
    \n\n\n
    Textinput&-area(input[text,password],textarea)- w/ slidingDoors\n
      \n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • trigger textfield 4 disabled/enabled\n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • trigger textarea 2 disabled/enabled\n
    • \n\n
    • \n \n
    • \n
    \n
    \n\n\n\n
    Textinput&-area with implicit labelling\n
      \n
    • \n
    • \n\n
    • \n
    • \n\n
    • \n
    • \n\n
    • \n\n
    • \n\n
    • \n
    • \n
    \n
    \n\n\n\n \n\n
    Selectfield (select) with and without multiple option and preselected\n
      \n\n
    • \n \n
    • \n\n
    • \n\n \n
    • \n\n
    • \n \n
    • \n\n
    • trigger select 3 disabled/enabled\n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • trigger multiple select 2 disabled/enabled\n
    • \n
    \n
    \n\n\n\n
    file upload (input[file]) -- without and with implicit labelling\n
      \n
    • \n \n
    • \n\n
    • \n
    • \n\n
    • \n \n
    • \n
    \n
    \n\n\n
    \n Check POST Data or Reset Data via Buttons (input[submit], input[reset], input[image])\n\n
      \n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n\n
    • \n \n
    • \n
    \n\n
    \n\n
    Advanced example: Search field\n
      \n
    • \n \n \" name=\"inputSearchSubmit\" />\n
    • \n
    \n
    \n
    \n\n \n \n \n \n \n \n \n \n\n", "cfe/modules/select/cfe.module.select.multiple.js": "/**\n * @module Selectable\n */\n\n/**\n * replaces select fields with attribute multiple set\n *\n * bug:\n * mouseWheel support needed\n * \n * @class SelectMultiple\n * @namespace cfe.module\n *\n * @extends cfe.module.Select\n */\ncfe.module.SelectMultiple = new Class({\n\t\n Extends: cfe.module.Select,\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"select[multiple]\",\n\n options: {\n buttonStyle: false\n },\n\n afterInitialize: function()\n {\n this.containerWrapper.addClass(cfe.prefix+\"SelectContainerWrapper\").setStyles({\n \"position\": \"relative\",\n \"z-index\": \"auto\"\n });\n this.container.addClass(cfe.prefix+\"SelectContainer\");\n\n this.o.addEvents({\n onDisable: function(){\n this.containerWrapper.getElements(\"input, button\").each(function(el){\n el.disable();\n });\n }.bind(this),\n onEnable: function(){\n this.containerWrapper.getElements(\"input, button\").each(function(el){\n el.enable();\n });\n }.bind(this)\n });\n \n this.parent();\n },\n\n setupWrapperEvents: function()\n {\n this.a = this.containerWrapper;\n this.parent();\n },\n\n buildOption: function(el, index)\n {\n var oOpt = new cfe.module.Checkbox({\n label: el.innerHTML,\n checked: $chk(el.selected),\n disabled: this.isDisabled()\n });\n oOpt.index = index;\n\n oOpt.addEvents({\n \"check\": function(index){\n this.origOptions[index].selected = true;\n this.o.fireEvent(\"change\")\n }.pass(index, this),\n \"uncheck\": function(index){\n this.origOptions[index].selected = false;\n this.o.fireEvent(\"change\")\n }.pass(index, this)\n });\n\n $(oOpt).addClass(cfe.prefix+\"Option \"+cfe.prefix+\"Option\"+index+(el.get('class')?\" \".el.get('class'):\"\")).disableTextSelection();\n oOpt.getLabel().removeEvents().inject( $(oOpt) );\n\n return $(oOpt);\n },\n\n selectOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n this.highlightOption(index);\n },\n\n clicked: function()\n {\n if(!this.isDisabled())\n {\n this.o.focus();\n this.fireEvent(\"onClick\");\n }\n },\n\n update: function()\n {\n this.fireEvent(\"onUpdate\");\n },\n\n toggle: function(){},\n keydown: function(){},\n hideContainer: function(){},\n showContainer: function(){}\n});"}, "files_after": {"cfe/modules/file/cfe.module.file.js": "/**\n * @module File\n */\n\n/**\n * replaces file upload fields\n *\n *

    is not resetted onReset

    \n * \n *
    Tested in:
    \n *
      \n *
    • Safari 4 - implicitly labelled triggers when deletin a file; reset doesnt trigger
    • \n *
    • Firefox 3.6.
    • \n *
    • Google Chrome 6 - implicitly labelled triggers twice, when using alias button & triggers when deletin a file.
    • \n *
    • Opera 10.62.
    • \n *
    • IE 7 - gaga.
    • \n *
    • IE 8 - implicitly labelled triggers when deletin a file.
    • \n *
    \n *\n * @class File\n * @namespace cfe.modules\n *\n * @extends cfe.module.Button\n */\n\ncfe.module.File = new Class({\n \n Extends: cfe.module.Button,\n \n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=file]\",\n\t\n options: {\n /**\n * enables the use of fileicons through a bit of markup and css\n * @config fileIcons\n * @type boolean\n * @default true\n */\n fileIcons: true,\n /**\n * show only the filename, not the whole path\n * @config trimFilePath\n * @type boolean\n * @default true\n */\n trimFilePath: true,\n\n innerLabel: \"Choose File\"\n },\n\n hideOriginalElement: false,\n\n toElement: function()\n {\n return this.wrapa\n },\n\n /**\n * retreive the filepath\n *\n * @method getFilePath\n * @return {HTMLElement}\n */\n getFilePath: function()\n {\n return this.v;\n },\n\n afterInitialize: function()\n {\n this.a = this.button;\n \n if(this.hideOriginalElement) this.o.hideInPlace();\n\n if(this.o.id) this.wrapa.addClass(cfe.prefix+this.type+this.o.id.capitalize());\n\n // various additions\n if(!this.o.implicitLabel && !Browser.safari && !Browser.chrome) this.wrapa.addEvent(\"click\", this.clicked.pass([e],this));\n\n if(this.isDisabled()) this.disable();\n\n if(!this.options.slidingDoors) this.wrapa.addClass(cfe.prefix+this.type)\n\n if(this.options.buttonStyle) this.a.addClass(cfe.prefix+\"Button\")\n\n this.a.removeClass(cfe.prefix+this.type)\n },\n\n build: function()\n {\n this.parent();\n this.innerlabel.set(\"text\", Array.pick(this.options.innerLabel, \"\"));\n\n // make original element follow mouse\n // setup wrapper\n this.wrapa = new Element(\"span\",{\n \"class\": cfe.prefix+this.type,\n styles:\n {\n overflow: \"hidden\",\n position: \"relative\"\n }\n }).cloneEvents(this.a)\n \n this.wrapa.inject(this.a, \"after\").adopt(this.a, this.o);\n\n // add positioning styles and events to \"hidden\" file input\n this.o.addEvents({\n \"mouseout\": this.update.bind(this),\n \"change\": this.update.bind(this),\n onDisable: this.disable.bind(this),\n onEnable: this.enable.bind(this)\n }).setStyles({\n opacity: \"0\",\n visibility: \"visible\",\n height: \"100%\",\n width: \"auto\",\n position: \"absolute\",\n top: 0,\n right: 0,\n margin: 0\n });\n\n this.wrapa.addEvent(\"mousemove\", this.follow.pass([e],this));\n\n this.button = this.a;\n this.a = this.wrapa;\n \n // add filepath\n this.v = new Element(\"span\").addClass(cfe.prefix+this.type+\"Path hidden\");\n\t\t\n this.path = new Element(\"span\").addClass(\"filePath\");\n\n if(this.options.fileIcons)\n {\n this.path.addClass(\"fileIcon\");\n }\n\n this.cross = $( new cfe.module.Button({delegateClick: false}).addEvent(\"click\", this.deleteCurrentFile.bind(this)) ).addClass(\"delete\");\n\n this.v.adopt(this.path, this.cross).inject(this.wrapa, \"after\");\n\n this.update();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"file\"\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n type: \"file\"\n });\n },\n\t\n follow: function(ev)\n {\n this.o.setStyle(\"left\",(ev.client.x-this.a.getLeft()-(this.o.getWidth()-30)));\n\t\t\n /* special treatment for internet explorer as the fileinput will not be cut off by overflow:hidden */\n if(Browser.ie){\n if(ev.client.x < this.a.getLeft() || ev.client.x > this.a.getLeft()+this.a.getWidth())\n this.o.setStyle(\"left\", -9999);\n }\n },\n\t\n update: function()\n {\n // only do stuff if original element is not disabled\n if( this.o.disabled == null )\n {\n if( this.o.value != \"\" )\n {\n this.o.disable().blur();\n\n this.oldValue = this.o.getProperty(\"value\");\n if(this.options.trimFilePath) this.oldValue = this.oldValue.trimFilePath();\n this.path.set(\"html\", this.oldValue);\n\n if(this.options.fileIcons)\n {\n var ind = this.oldValue.lastIndexOf(\".\");\n this.path.setProperty(\"class\",\"filePath fileIcon \" + this.oldValue.substring(++ind).toLowerCase());\n }\n this.v.removeClass(\"hidden\");\n }\n else\n {\n this.o.enable().focus();\n\n this.path.set(\"html\", \"\");\n this.v.addClass(\"hidden\");\n }\n\n this.parent();\n }\n },\n\t\n deleteCurrentFile: function()\n {\n // we dont clone the old file input here, since the attribute \"value\" would be cloned, too\n // and we cannot modify the value of an file input field without user interaction\n this.o = this.createOriginal().addClass(this.o.getProperty(\"class\")).setProperties({\n name: this.o.getProperty(\"name\"),\n id: this.o.getProperty(\"id\"),\n style: this.o.getProperty(\"style\"),\n title: this.o.getProperty(\"title\")\n }).cloneEvents(this.o).replaces(this.o);\n\t\t\n this.update();\n }\n});\n\n// add trimFilePath to Native String for convenience\nString.implement({\n trimFilePath: function()\n {\n var ind = false;\n if(!(ind = this.lastIndexOf(\"\\\\\")))\n if(!(ind = this.lastIndexOf(\"\\/\")))\n ind = 0;\n\n return this.substring(++ind);\n }\n});", "cfe/base/cfe.base.js": "/**\n * The core of custom form elements. Includes cfe.Generic and some slight addons to the native Element object. \n *\n * @module Core\n * @namespace cfe\n */\n\nvar cfe = {\n version: \"0.9.9\",\n prefix: \"cfe\",\n module: {},\n addon: {}\n};\n\n/**\n * extend Elements with some Helper functions\n * @class Helpers\n * @namespace Element\n */\nElement.Helpers = new Class({\n\n /**\n * cross-browser method for disabling the text selection by setting css attributes\n * \n * @method disableTextSelection\n */\n disableTextSelection: function(){\n if(Browser.ie || Browser.opera){\n this.setProperty(\"unselectable\",\"on\");\n }\n else if(Browser.firefox){\n this.setStyle(\"MozUserSelect\",\"none\");\n }\n else if(Browser.safari || Browser.chrome){\n this.setStyle(\"KhtmlUserSelect\",\"none\");\n }\n\n return this;\n },\n\n /**\n * disables a HTMLElement if its a form element by setting the disabled attribute to true\n *\n * @method disable\n * @return boolean true, if element could be disabled\n */\n disable: function()\n {\n if(typeOf(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", true);\n this.fireEvent(\"onDisable\");\n }\n\n return this;\n },\n\n /**\n * enables a HTMLElement if its a form element by setting the disabled attribute to false\n *\n * @method enable\n * @return {boolean} true, if element could be enabled\n */\n enable: function()\n {\n if(typeOf(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", false);\n this.fireEvent(\"onEnable\");\n }\n\n return this;\n },\n\n /**\n * enables or disabled a HTMLElement if its a form element depending on it's current state\n *\n * @method toggleDisabled\n * @return {boolean} true, if element could be toggled\n */\n toggleDisabled: function()\n {\n if(typeOf(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", !this.getProperty(\"disabled\") );\n this.fireEvent(this.getProperty(\"disabled\")?\"onDisable\":\"onEnable\");\n }\n return this;\n },\n\n /**\n * returns the label-element which belongs to this element\n *\n * @method getLabel\n * @return HTMLElement or NULL\n */\n getLabel: function()\n {\n var label = null;\n\n // get label by id/for-combo\n if(this.id) label = $$(\"label[for=\"+this.id+\"]\")[0];\n \n // no label was found for id/for, let's see if it's implicitly labelled\n if(!label)\n {\n label = this.getParent('label');\n\n if(label) this.implicitLabel = true;\n }\n\n return label;\n },\n\n /**\n * generates the markup used by sliding doors css technique to use with this element\n *\n * @method setSlidingDoors\n *\n * @param count\n * @param type\n * @param prefix\n * \n * @return HTMLElement or NULL the wrapped HTMLElement\n */\n setSlidingDoors: function(count, type, prefix, suffixes)\n {\n var slide = null;\n var wrapped = this;\n prefix = Array.pick(prefix, \"sd\");\n\n suffixes = Array.pick(suffixes, []);\n\n for(var i = count; i > 0; --i)\n {\n wrapped.addClass( prefix+\"Slide\"+( (i == 1 && count == i) ? \"\" : (suffixes[i] || i) ));\n slide = new Element(type);\n try{\n wrapped = slide.wraps(wrapped);\n }catch(e){\n wrapped = slide.grab(wrapped);\n }\n }\n\n wrapped = null;\n\n return slide;\n },\n\n /**\n * hide an element but keep it's vertical position and leave it tab- & screenreader-able :)\n *\n * @method hideInPlace\n *\n * @return HTMLElement\n */\n hideInPlace: function()\n {\n return this.setStyles({\n position: \"absolute\",\n left: -99999,\n width: 1,\n height: 1\n });\n }\n});\n\nElement.implement(new Element.Helpers);", "cfe/modules/check/cfe.module.radio.js": "/**\n * @module Checkable\n */\n\n/**\n *

    replaces radiobuttons

    \n *\n *
    Tested in:
    \n *
      \n *
    • Safari 4.
    • \n *
    • Firefox 3.6.
    • \n *
    • Google Chrome 6.
    • \n *
    • Opera 10.62.
    • \n *
    • IE 7.
    • \n *\n *
    • IE 8\n *
        \n *
      • labels dont work for normal labelled elements
      • \n *
      \n *
    • \n *\n *
    \n *\n * @class Radiobutton\n * @namespace cfe.module\n *\n * @extends cfe.modules.Checkbox\n */\ncfe.module.Radiobutton = new Class({\n\n Extends: cfe.module.Checkbox,\n\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=radio]\",\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"radio\"\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n \"type\": \"radio\",\n \"checked\": this.options.checked\n });\n },\n\n /**\n * @method initializeAdv\n * @protected\n */\n afterInitialize: function()\n {\n this.parent();\n \n if( !(Browser.ie || Browser.firefox) ) this.o.addEvent(\"click\", this.update.bind(this));\n\n // on check, disable all other radiobuttons in this group\n this.addEvent(\"check\", function(){\n $$(\"input[name='\"+this.o.get(\"name\")+\"']\").each(function(el)\n {\n if(el != this.o && el.retrieve(\"cfe\")) el.retrieve(\"cfe\").uncheck();\n }.bind(this));\n })\n }\n});", "cfe/replace/cfe.replace.js": "/**\n * replacement class for automated replacment of scoped form elements\n *\n * @module replace\n * @namespace cfe\n *\n */\n\ncfe.Replace = new Class(\n{\n Implements: [new Options, new Events],\n\n options:{\n scope: false,\n\t\t\n onInit: function(){},\n onInitSingle: function(){},\n onBeforeInitSingle: function(){},\n onSetModuleOption: function(){},\n onRegisterModule: function(){},\n onUnregisterModule: function(){},\n onComplete: function(){}\n },\n\t\t\n modules: {},\n moduleOptions: {},\n moduleOptionsAll: {},\n\t\n initialize: function()\n {\n this.registerAllModules.bind(this)();\n },\n\t\n /**\n * @method registerAllModules\n\t * registeres all loaded modules onInitialize\n\t */\n registerAllModules: function(){\n\t\t\n //console.log(\"Register all modules\");\n\t\t\n Object.each(cfe.module, function(modObj, modType){\n //console.log(\"Registering type \"+modType);\n if(modType != \"Generic\")\n this.registerModule(modType);\n\t\t\t\t\n },this);\n },\n\t\n /* call to register module */\n registerModule: function(mod){\n\t\t\n //console.log(\"Call to registerModule with arg:\"+mod);\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onRegisterModule\", [mod,modObj]);\n this.modules[mod] = modObj;\n this.moduleOptions[mod] = {};\n\n return true;\n },\n\t\n registerModules: function(mods)\n {\n Object.each(mods,function(mod){\n this.registerModule(mod);\n },this);\n },\n\t\n unregisterModule: function(mod)\n {\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onUnregisterModule\", [mod,modObj]);\n\n delete this.modules[mod];\n },\n\t\n unregisterModules: function(mods)\n {\n Object.each(mods,function(mod){\n this.unregisterModule(mod);\n },this);\n },\n /**\n\t * sets a single option for a specified module\n\t * if no module was given, it sets the options for all modules\n\t *\n * @method setModuleOption\n *\n\t * @param {String} \tmod \tName of the module\n\t * @param {String} \topt \tName of the option\n\t * @param {Mixed} \tval\t\tThe options value\n\t */\n setModuleOption: function(mod,opt,val){\n\t\t\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onSetModuleOption\", [mod,modObj,opt,val]);\n\t\t\n if(!modObj){\n this.moduleOptionsAll[opt] = val;\n }\n else{\n this.moduleOptions[mod][opt] = val;\n }\n },\n\n setModuleOptions: function(mod,opt){\n\t\t\n Object.each(opt, function(optionValue, optionName){\n this.setModuleOption(mod,optionName,optionValue);\n },this);\n\t\t\n },\n\n engage: function(options){\n\n this.setOptions(this.options, options);\n\n if(typeOf(this.options.scope) != \"element\"){\n this.options.scope = $(document.body);\n }\n\n this.fireEvent(\"onInit\");\n\t\t\n Object.each(this.modules,function(module,moduleName,i){\n\t\t\t\n var selector = module.prototype.selector;\n\t\t\t\n this.options.scope.getElements(selector).each(function(el,i){\n\n if(el.retrieve(\"cfe\") != null){\n\n var basicOptions = {\n replaces: el\n };\n\n this.fireEvent(\"onBeforeInitSingle\", [el,i,basicOptions]);\n\n var single = new module(Object.merge({},basicOptions,Object.merge({},this.moduleOptions[moduleName],this.moduleOptionsAll)));\n\t\t\t\t\n this.fireEvent(\"onInitSingle\", single);\n }else{\n this.fireEvent(\"onSkippedInitSingle\", [el,i,basicOptions]); \n }\n\t\t\t\t\n },this);\n },this);\n\t\t\n this.fireEvent(\"onComplete\");\n }\n});", "cfe/modules/check/cfe.module.checkbox.js": "/**\n * @module Checkable\n */\n\n/**\n *

    replaces checkboxes

    \n * \n *
    Tested in:
    \n *
      \n *
    • Safari 4.
    • \n *
    • Firefox 3.6.
    • \n *
    • Google Chrome 6.
    • \n *
    • Opera 10.62.
    • \n *
    • IE 7.
    • \n *
    • IE 8.
    • \n *
    \n *\n * @class Checkbox\n * @namespace cfe.module\n * \n * @extends cfe.module.Button\n */\ncfe.module.Checkbox = new Class({\n \n Extends: cfe.module.Button,\n \n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=checkbox]\",\n\n options:{\n /**\n * @inherit\n */\n slidingDoors: false\n /**\n * Fired when the original element gets checked\n * @event onCheck\n */\n //onCheck: Class.empty,\n /**\n * Fired when the original element's checked state is set to false\n * @event onUnCheck\n */\n //onUncheck: Class.empty\n },\n\n afterInitialize: function()\n {\n this.parent();\n\n // important for resetting dynamically created cfe\n this.o.defaultChecked = this.o.checked;\n\n if( Browser.ie || Browser.opera )\n {\n //console.log(\"fix for element update (IE and Opera)\")\n this.o.addEvent(\"click\", this.update.bind(this) );\n }\n\n\n if(Browser.ie && this.o.implicitLabel)\n {\n //console.log(\"fix for implicit labels (IE) element[\"+this.o.id+\"]\")\n this.l.removeEvents(\"click\")\n this.a.removeEvents(\"click\").addEvent(\"click\", function(e){\n e.stop();\n this.clicked.bind(this)();\n }.bind(this))\n }\n\n this.update();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"checkbox\"\n * @protected\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n type: \"checkbox\",\n checked: this.options.checked\n });\n },\n\n clicked: function(e)\n {\n if(Browser.ie && e) e.stop();\n\n this.parent()\n },\n\n /**\n * public method to check a checkbox programatically\n *\n * @method check\n * @public\n */\n check: function()\n {\n this.a.addClass(\"A\");\n this.fireEvent(\"onCheck\");\n },\n\n /**\n * public method to uncheck a checkbox programatically\n *\n * @method uncheck\n * @public\n */\n uncheck: function()\n {\n this.a.removeClass(\"A\");\n this.fireEvent(\"onUncheck\");\n },\n\n update: function()\n {\n this.o.checked ? this.check() : this.uncheck();\n this.parent();\n }\n});", "cfe/addons/cfe.addon.toolTips.js": "/**\n * @module Addon\n */\n\n/**\n * pretty simple integration of auto-generated tooltips (from title-attribute)\n * depends on mootools Tips\n *\n * @class Tips\n * @namespace cfe.addon\n *\n */\ncfe.addon.Tips = new Class({\n\t\n options: Object.merge({},this.parent, {\n enableTips: true,\n ttStyle: \"label\",\n ttClass: cfe.prefix+\"Tip\"\n }),\n\t\n initToolTips: function(){\n\t\t\n if(!window.Tips || !this.options.enableTips){\n if(this.options.debug){\n this.throwMsg.bind(this)(\"CustomFormElements: initialization of toolTips failed.\\nReason: Mootools Plugin 'Tips' not available.\");\n }\n \n return false;\n }\n\t\n switch(this.options.ttStyle){\n default:case 'label': this.toolTipsLabel.bind(this)();break;\n }\n\n return true;\n },\n\t\n toolTipsLabel: function(){\n\t\t\n var labels = this.options.scope.getElements('label');\n \t\t\n labels.each(function(lbl,i){\n\n forEl = lbl.getProperty(\"for\");\n\t\t\t\n if(!forEl){\n var cl = lbl.getProperty(\"class\");\n\t\t\t\t\n if( cl != null ){\n var forEl = cl.match(/for_[a-zA-Z0-9\\-]+/);\n\n if(forEl){\n forEl = forEl.toString();\n el = $( forEl.replace(/for_/,\"\") );\n } \n }\n\t\t\t\t\n if(!el){\n el = lbl.getElement(\"input\");\n }\n }else{\n el = $(forEl);\n }\n\n if(el){\n if((qmTitle = el.getProperty(\"title\")) != null){\n\t\t\t\t\t\n el.setProperty(\"title\",\"\").setProperty(\"hint\", qmTitle)\n\t\t\t\t\t\n var qm = new Element(\"span\",{\n \"class\": this.options.ttClass,\n \"title\": qmTitle\n });\n \n // check if implicit label span is present\n var impLabel = lbl.getFirst(\"span[class=label]\");\n \n qm.inject((impLabel != null)?impLabel:lbl,'inside');\n }\n }\n },this);\n\t\t\n new Tips($$('.'+this.options.ttClass+'[title]'));\n }\n});\n\ncfe.Replace.implement(new cfe.addon.Tips);\ncfe.Replace.prototype.addEvent(\"onComplete\", function(){\n this.initToolTips();\n});", "cfe/addons/cfe.addon.dependencies.js": "/**\n * @module Addon\n */\n\n/**\n * adds dependencies to checkboxes\n *\n * @class Dependencies\n * @namespace cfe.addon\n *\n */\ncfe.addon.Dependencies = new Class({\n\t\n /**\n\t * adds dependencies for an element \n\t * @param {Object} el\n\t * @param {Array} dep\n\t */\n addDependencies: function(el, deps){\n Array.each(deps,function(dep){\n this.addDependency(el,dep);\n },this);\n },\n\t\n /**\n\t * adds dependency for an element \n\t * @param {Object} el\n\t * @param {Object} dep\n\t */\n addDependency: function(el, dep){\n\t\t\n // create an array if needed\n if(typeOf( el.retrieve('deps') ) !== \"array\"){\n el.store('deps', []);\n }\n\t\t\n // deps may be objects or strings > if a string was given, try to interpret it as id and fetch element by $()\n if(typeOf(dep) === \"string\" || typeOf(dep) === \"element\"){\n el.retrieve('deps').push( $(dep) );\n return true;\n }\n\t\t\n return false;\n },\n\t\n getDependencies: function(el)\n {\n return el.retrieve('deps');\n },\n\t\n /**\n\t * this is called when a new item of a cfemodule gets initialized\n\t * it checks, whether there are dependencies for this element and adds them to its options\n\t * \n\t * @param {Object} el\n\t */\n attachDependencies: function(el,i,baseOptions)\n {\n var deps = this.getDependencies(el);\n\t\t\n if(typeOf(deps) === \"array\"){\n baseOptions.deps = deps;\n return true;\n }\n\t\n return false;\n }\n\t\t\n});\ncfe.Replace.implement(new cfe.addon.Dependencies);\ncfe.Replace.prototype.addEvent(\"onBeforeInitSingle\", cfe.Replace.prototype.attachDependencies);\n\ncfe.addon.Dependencies.Helper = new Class({\n resolveDependencies: function()\n {\n var deps = this.o.retrieve('deps');\n\t\t\n if(deps){\n Array.each(deps, function(dep,i){\n dep.checked = true;\n dep.fireEvent(\"change\");\n },this);\n }\n }\n});\n\n// support for checkboxes\ncfe.module.Checkbox.implement(new cfe.addon.Dependencies.Helper);\ncfe.module.Checkbox.prototype.addEvent(\"onCheck\", function(){\n this.resolveDependencies();\n});", "cfe/modules/button/cfe.module.button.js": "/**\n * @module Button\n */\n\n/**\n * gets extended by modules to start off with standard, button-like behaviours.\n *\n * when focused and pressed, form gets submitted\n *\n * @class Button\n * @namespace cfe.module\n *\n */\ncfe.module.Button = new Class(\n{\n Implements: [new Options, new Events],\n\n selector: \"button\",\n\n instance: 0,\n\n /**\n * basic options for all cfes and always available\n * @property options\n */\n options: {\n /**\n * if > 0, it will create markup for css sliding doors tech
    \n * the number defines the amount of wrappers to create around this element
    \n * 2: standard sliding doors (x- or y-Axis)
    \n * 4: sliding doors in all directions (x/y-Axis)\n *\n * @config slidingDoors\n * @type int\n * @default 4\n */\n slidingDoors: 2,\n\n /**\n * if this element shall replace an existing html form element, pass it here\n * @config replaces\n * @type HTMLElement\n */\n replaces: null,\n\n /**\n * determines if a click on the decorator should be delegated to the original element\n * @config delegateClick\n * @type Boolean\n */\n delegateClick: true,\n\n /**\n * may pass any element as a label (toggling, hovering,..) for this cfe\n * @config label\n * @type HTMLElement\n */\n label: null,\n\n /**\n * if this cfe is created programatically, it's possible to set the name attribute of the generated input element\n * @config name\n * @type string\n */\n name: \"\",\n\n /**\n * setting this to true will create a disabled element\n * @config disabled\n * @type boolean\n */\n disabled: false,\n\n buttonStyle: true\n\n /**\n * Fired when the mouse is moved over the \"decorator\" element\n * @event onMouseOver\n */\n //onMouseOver: Class.empty,\n\n /**\n * Fired when the mouse is moved away from the \"decorator\" element\n * @event onMouseOut\n */\n //onMouseOut: Class.empty,\n\n /**\n * Fired when the \"original\" element gets focus (e.g. by tabbing)\n * @event onFocus\n */\n //onFocus: Class.empty,\n\n /**\n * Fired when the \"original\" element loses focus\n * @event onBlur\n */\n //onBlur: Class.empty,\n\n /**\n * Fired when \"decorator\" is clicked by mouse\n * @event onClick\n */\n //onClick: Class.empty,\n\n /**\n * Fired when pressing down with the mouse button on the \"decorator\"\n * Fired when pressing the space key while \"original\" has focus\n * @event onPress\n */\n //onPress: Class.empty,\n\n /**\n * Fired when \"decorator\" was pressed and the mouse button is released\n * Fired when \"original\" was pressed by space key and this key is released\n * @event onRelease\n */\n //onRelease: Class.empty,\n\n /**\n * Fired when \"original\"'s value changes\n * @event onUpdate\n */\n //onUpdate: Class.empty,\n\n /**\n * Fired when \"original\" gets disabled by HTMLElement.enable()\n * @event onEnable\n */\n //onEnable: Class.empty,\n\n /**\n * Fired when \"original\" gets disabled by HTMLElement.disable()\n * @event onDisable\n */\n //onDisable: Class.empty,\n\n /**\n * Fired when decorator is completely loaded and is ready to use\n * @event onLoad\n */\n //onLoad: Class.empty\n\n\n },\n\n hideOriginalElement: true,\n\n /**\n * constructor
    \n * building algorithm for cfe (template method)
    \n *
      \n *
    1. setOptions: set Options
    2. \n *
    3. buildWrapper: setup the \"decorator\"
    4. \n *
    5. setupOriginal: procede the \"original\" element (add Events...)
    6. \n *
    7. addLabel: add and procede the label
    8. \n *
    9. initializeAdv: last chance for subclasses to do initialization
    10. \n *
    11. build: various specific dom handling and \"decorator\" building
    12. \n *\n * @method initialize\n * @constructor\n *\n * @param {Object} options\n **/\n initialize: function(opt)\n {\n // sets instance id\n this.instance = this.constructor.prototype.instance++;\n\n this.setOptions(opt);\n\n this.type = Array.pick(this.options.type, cfe.module.keyOf(this.constructor));\n\n this.buildWrapper();\n\n // prepares original html element for use with cfe and injects decorator into dom\n this.setupOriginal();\n\n // add a label, if present\n this.addLabel( Array.pick(this.o.getLabel(), this.setupLabel(this.options.label) ) );\n\n this.build();\n\n // add events to wrapping element\n this.setupWrapperEvents();\n\n // specific initialization\n this.afterInitialize();\n\n this.fireEvent(\"load\")\n },\n\n /**\n * retreive the \"decorator\"\n * mootools supports the use of $(myCfe) if toElement is defined\n *\n * @method toElement\n * @return {HTMLElement}\n */\n toElement: function()\n {\n return this.a;\n },\n\n /**\n * retreive the label\n *\n * @method getLabel\n * @return {HTMLElement}\n */\n getLabel: function()\n {\n return this.l;\n },\n\n /**\n * template method STEP 1\n */\n buildWrapper: function(){\n this.a = new Element(\"span\");\n },\n\n /**\n * handles the creation of the underlying original form element
      \n * stores a reference to the cfe object in the original form element\n * template method STEP 2\n *\n * @method setupOriginal\n * @protected\n */\n setupOriginal: function()\n {\n // get original element\n if( this.options.replaces != null )\n {\n this.o = this.options.replaces;\n this.a.inject(this.o, 'before');\n }\n else // standalone\n {\n this.o = this.createOriginal();\n\n if(this.options.id) this.o.setProperty(\"id\", this.options.id);\n\n if(this.options.disabled) this.o.disable();\n\n if(this.options.name)\n {\n this.o.setProperty(\"name\", this.options.name);\n\n if( this.o.id == null ) this.o.setProperty(\"id\", this.options.name+this.instance);\n }\n\n if(this.options.value) this.o.setProperty(\"value\", this.options.value);\n\n this.a.adopt(this.o);\n }\n\n this.o.addEvents({\n focus: this.setFocus.bind(this),\n blur: this.removeFocus.bind(this),\n change: this.update.bind(this),\n keydown: function(e){\n if(e.key == \"space\") this.press();\n }.bind(this),\n keyup: function(e){\n if(e.key == \"space\") this.release();\n }.bind(this),\n onDisable: function(){\n this.a.fireEvent(\"disable\");\n }.bind(this),\n onEnable: function(){\n this.a.fireEvent(\"enable\");\n }.bind(this)\n });\n\n // store a reference to this cfe \"in\" the original form element\n this.o.store(\"cfe\", this);\n },\n\n /*\n * adds a label element to this cfe\n * template method STEP 3\n *\n * @method addLabel\n * @protected\n *\n * @param {HTMLElement} the label element to set as label for this cfe\n */\n addLabel: function(label)\n {\n if( label == null ) return;\n\n this.l = label;\n\n // remove for property\n if(!this.dontRemoveForFromLabel) this.l.removeProperty(\"for\");\n\n // add adequate className, add stdEvents\n this.l.addClass(cfe.prefix+this.type+\"L\");\n\n if(this.o.id || this.o.name) this.l.addClass(\"for_\"+ (this.o.id || (this.o.name+this.o.value).replace(\"]\",\"-\").replace(\"[\",\"\") ));\n\n // add stdevents\n this.l.addEvents({\n mouseover: this.hover.bind(this),\n mouseout: this.unhover.bind(this),\n mousedown: this.press.bind(this),\n mouseup: this.release.bind(this),\n click: this.clicked.bind(this,[e])\n });\n\n this.addEvents({\n press: function()\n {\n this.l.addClass(\"P\");\n },\n release: function()\n {\n this.l.removeClass(\"P\");\n },\n mouseOver: function()\n {\n this.l.addClass(\"H\");\n },\n mouseOut: function()\n {\n this.l.removeClass(\"H\");\n this.l.removeClass(\"P\");\n },\n focus: function()\n {\n this.l.addClass(\"F\");\n },\n blur: function()\n {\n this.l.removeClass(\"F\");\n //this.l.removeClass(\"P\");\n },\n enable: function()\n {\n this.l.removeClass(\"D\");\n },\n disable: function()\n {\n this.l.addClass(\"D\");\n }\n });\n },\n\n /**\n * part of the main template method for building the \"decorator\"
      \n * must be extended by subclasses\n *\n * template method STEP 4\n *\n * @method build\n * @protected\n */\n build: function(){\n\n this.innerlabel = this.setupInnerLabel();\n this.a.adopt(this.innerlabel);\n\n if( this.options.slidingDoors != null )\n {\n this.a = this.a.setSlidingDoors(this.options.slidingDoors-1, \"span\", cfe.prefix).addClass(cfe.prefix+this.type);\n }\n },\n\n\n /**\n * adds events and mousepointer style to the \"decorator\"\n * usually gets called by buildWrapper\n *\n * template method STEP 5\n *\n * @method setupWrapperEvents\n * @protected\n */\n setupWrapperEvents: function()\n {\n if(!this.o.implicitLabel)\n {\n this.a.addEvents({\n mouseover: this.hover.bind(this),\n mouseout: this.unhover.bind(this),\n mousedown: this.press.bind(this),\n mouseup: this.release.bind(this)\n });\n }\n\n this.a.addEvents({\n disable: this.disable.bind(this),\n enable: this.enable.bind(this)\n })\n \n },\n\n /**\n * part of the main template method for building the \"decorator\"
      \n * gets called immediately before the build-method
      \n * may be extended by subclasses\n *\n * template method STEP 6\n *\n * @method initializeAdv\n * @protected\n */\n afterInitialize: function()\n {\n if(this.hideOriginalElement) this.o.hideInPlace();\n\n if(this.o.id) this.a.addClass(cfe.prefix+this.type+this.o.id.capitalize());\n\n // various additions\n if(!this.o.implicitLabel) this.a.addEvent(\"click\", this.clicked.pass([e],this));\n\n if(this.isDisabled()) this.a.fireEvent(\"disable\");\n\n if(!this.options.slidingDoors) this.a.addClass(cfe.prefix+this.type)\n\n if(this.options.buttonStyle) this.a.addClass(cfe.prefix+\"Button\")\n },\n\n setupInnerLabel: function(){\n return new Element(\"span\").addClass(\"label\").disableTextSelection();\n },\n\n\n /**\n * getter for retrieving the disabled state of the \"original\" element\n *\n * @method isDisabled\n * @return boolean\n */\n isDisabled: function()\n {\n return this.o.getProperty(\"disabled\")\n },\n\n /**\n * programatically creates an \"original\" element
      \n * each subclass has to implement this\n *\n * @method createOriginal\n * @return {HTMLElement}\n */\n createOriginal: function()\n {\n return new Element(\"button\")\n },\n\n /*\n * creates a label element and fills it with the contents (may be html) given by option \"label\"\n *\n * @method setupLabel\n * @protected\n *\n * @return {HTMLElement or NULL} if option \"label\" is not set\n */\n setupLabel: function()\n {\n if( this.options.label != null ) return new Element(\"label\").set(\"html\", this.options.label).setProperty(\"for\", this.o.id);\n\n return null;\n },\n\n /**\n * wrapper method for event onPress
      \n * may be extended by subclasses\n *\n * @method press\n * @protected\n */\n press: function()\n {\n if(this.isDisabled()) return\n\n this.a.addClass(\"P\");\n this.fireEvent(\"onPress\");\n\n //console.log(this.type + \"pressed\");\n },\n\n /**\n * wrapper method for event onRelease
      \n * may be extended by subclasses\n *\n * @method release\n * @protected\n */\n release: function()\n {\n if(this.isDisabled()) return\n\n this.a.removeClass(\"P\");\n this.fireEvent(\"onRelease\");\n \n //console.log(this.type + \"released\");\n\n },\n\n /**\n * wrapper method for event onMouseOver
      \n * may be extended by subclasses\n *\n * @method onMouseOver\n * @protected\n */\n hover: function()\n {\n if(this.isDisabled()) return\n\n this.a.addClass(\"H\");\n this.fireEvent(\"onMouseOver\");\n\n //console.log(this.type + \"hovered\");\n },\n\n /**\n * wrapper method for event onMouseOut
      \n * may be extended by subclasses\n *\n * @method unhover\n * @protected\n */\n unhover: function()\n {\n if(this.isDisabled()) return\n\n this.a.removeClass(\"H\");\n this.fireEvent(\"onMouseOut\");\n this.release();\n\n //console.log(this.type + \"unhovered\");\n },\n\n /**\n * wrapper method for event onFocus
      \n * may be extended by subclasses\n *\n * @method setFocus\n * @protected\n */\n setFocus: function()\n {\n this.a.addClass(\"F\");\n this.fireEvent(\"onFocus\");\n\n //console.log(this.type + \"focused\");\n },\n\n /**\n * wrapper method for event onBlur
      \n * may be extended by subclasses\n *\n * @method removeFocus\n * @protected\n */\n removeFocus: function()\n {\n //console.log(\"o blurred\");\n this.a.removeClass(\"F\");\n // if cfe gets blurred, also clear press state\n //this.a.removeClass(\"P\");\n this.fireEvent(\"onBlur\");\n\n //console.log(this.type + \"blurred\");\n\n },\n\n /**\n * wrapper method for event onClick
      \n * delegates the click to the \"original\" element
      \n * may be extended by subclasses\n *\n * @method clicked\n * @protected\n */\n clicked: function(e)\n {\n //causes problems in other browsers than ie - gonna took into this later; its the best approach to stop the event from bubbling right here though imho\n //e.stop();\n\n if(this.isDisabled()) return\n\n if( $chk(this.o.click) && this.options.delegateClick != null ) this.o.click();\n this.o.focus();\n\n this.fireEvent(\"onClick\");\n\n //console.log(this.type + \" clicked\");\n },\n\n /**\n * wrapper method for event onUpdate
      \n * may be extended by subclasses\n *\n * @method update\n * @protected\n */\n update: function()\n {\n this.fireEvent(\"onUpdate\");\n\n //console.log(\"o was updated\");\n },\n\n /**\n * wrapper method for event onEnable
      \n * may be extended by subclasses\n *\n * @method enable\n * @protected\n */\n enable: function()\n {\n this.a.removeClass(\"D\");\n this.fireEvent(\"onEnable\");\n\n //console.log(this.type+\"-\"+this.instance+\" now enabled\");\n },\n\n /**\n * wrapper method for event onDisable
      \n * may be extended by subclasses\n *\n * @method disable\n * @protected\n */\n disable: function()\n {\n this.a.addClass(\"D\");\n this.fireEvent(\"onDisable\");\n\n //console.log(this.type+\"-\"+this.instance+\" now disabled\");\n }\n});", "cfe/modules/select/cfe.module.select.js": "/**\n * @module Scrollable\n */\n\n/**\n * SCROLLING functionality for select boxes;\n * TODO: refactor to standalone module\n * \n * creates handles and sets up a slider object\n *\n * @class Scrollable\n * @namespace cfe.helper\n *\n * \n */\ncfe.helper = cfe.helper || {}\n\ncfe.helper.Scrollable = {\n\n options: {\n size: 4,\n scrolling: true\n },\n \n setupScrolling: function()\n {\n // slider config\n this.scrollerWrapper = new Element(\"span\",{\n \"class\": cfe.prefix+\"ScrollerWrapper\",\n \"styles\":{\n height: this.container.getHeight()\n }\n }).inject(this.container, \"after\");\n\n var scrollTimer, scrollTimeout;\n var scrollStepHeight = this.allOptions[0].getHeight();\n\n function scroll(by){\n clearInterval(scrollTimer);\n clearTimeout(scrollTimeout);\n\n slider.set(slider.step+by);\n\n scrollTimeout = (function(){\n scrollTimer = (function(){\n slider.set(slider.step+by);\n }.bind(this)).periodical(50)\n }.bind(this)).delay(200)\n }\n\n function clearScroll(){\n clearInterval(scrollTimer);\n clearTimeout(scrollTimeout);\n }\n\n this.scrollerTop = $(new cfe.module.Button({\n delegateClick: false\n }).addEvent(\"release\", clearScroll).addEvent(\"press\", scroll.pass(-1))).addClass(\"scrollTop\");\n\n this.scrollerBottom = $(new cfe.module.Button({\n delegateClick: false\n }).addEvent(\"release\", clearScroll).addEvent(\"press\", scroll.pass(1))).addClass(\"scrollBottom\")\n\n this.scrollerKnob = new Element(\"span\").addClass(\"scrollKnob\");\n this.scrollerBack = new Element(\"span\").addClass(\"scrollRail\");\n\n this.scrollerBack.adopt(this.scrollerKnob);\n this.scrollerWrapper.adopt(this.scrollerBack, this.scrollerTop, this.scrollerBottom);\n\n var slider = new Slider(this.scrollerBack, this.scrollerKnob, {\n steps: this.allOptions.length-this.options.size,\n mode: \"vertical\" ,\n onChange: function(step){\n this.container.scrollTo(false,step*scrollStepHeight);\n }.bind(this)\n }).set(this.selectedIndex);\n\n this.scrollerKnob.setStyle(\"position\", \"absolute\");\n\n // scrolling\n function wheelListener(ev)\n {\n ev.stop();\n slider.set(slider.step-ev.wheel);\n }\n\n this.boundWheelListener = wheelListener.pass([e],this)\n\n this.addEvent(\"containerShow\", function(){\n $(document.body).addEvent(\"mousewheel\", this.boundWheelListener)\n\n slider.set(this.o.selectedIndex);\n this.container.scrollTo(false,this.o.selectedIndex*scrollStepHeight);\n })\n\n this.addEvent(\"containerHide\", function(){\n $(document.body).removeEvent(\"mousewheel\", this.boundWheelListener);\n })\n\n this.o.addEvent(\"change\", function(){\n slider.set(this.o.selectedIndex)\n }.bind(this))\n }\n}\n\n/**\n * @module Selectable\n */\n\n/**\n * replaces select fields\n *\n *

      disabled should also disable scrolling

      \n * \n *
      Tested in:
      \n *
        \n *
      • Safari 4.
      • \n *
      • Firefox 3.6.
      • \n *
      • Google Chrome 6.
      • \n *
      • Opera 10.62 - key autocompletion closes box.
      • \n *
      • IE 7.
      • \n *
      • IE 8.
      • \n *
      \n *\n * @class Select\n * @namespace cfe.module\n *\n * @extends cfe.module.Button\n *\n */\ncfe.module.Select = new Class({\n\t\n Extends: cfe.module.Button,\n Implements: cfe.helper.Scrollable,\n \n Binds: \"clickedOutsideListener\",\n\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"select:not(select[multiple])\",\n\t\n selectedIndex: 0,\n\n setupOriginal: function()\n {\n this.parent();\n \n this.o.addEvents({\n \"keyup\": this.keyup.bind(this),\n \"keydown\": this.keydown.bind(this)\n });\n },\n\n afterInitialize: function()\n {\n this.parent();\n\n // set width to widest option if no width is given to select via css\n if(this.cssWidth == \"auto\") this.a.setStyle(\"width\", this.container.getWidth())\n\n // inject labelArrow as IE 7 doesn't support :after css selector\n if(Browser.ie) new Element(\"span\").addClass(\"labelArrow\").inject(this.innerlabel, \"after\")\n\n // select default option\n if(this.selectedIndex != -1) this.selectOption(this.selectedIndex, true);\n\n if(this.options.scrolling)\n {\n this.container.setStyle(\"height\", this.allOptions[0].getHeight()*this.options.size);\n this.setupScrolling();\n }\n\n this.hideContainer();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} a select input\n */\n createOriginal: function()\n {\n var ori = new Element(\"select\");\n\n if( this.options.options != null )\n {\n for(var key in this.options.options)\n {\n ori.adopt( new Element(\"option\", {\n value: key,\n selected: this.options.options[key].selected?\"selected\":\"\"\n }).set(\"html\", this.options.options[key].label ) );\n }\n }\n return ori;\n },\n\n build: function()\n {\n this.origOptions = this.o.getChildren();\n\n this.selectedIndex = this.o.selectedIndex || this.selectedIndex;\n\n // integrity check\n if(this.options.size > this.origOptions.length || this.options.scrolling != true) this.options.size = this.origOptions.length;\n \n this.parent();\n\n this.a.setStyles({\"position\": \"relative\", \"z-index\": 100000 - this.instance});\n\n // build container which shows on click\n this.buildContainer();\n\n this.cssWidth = this.a.getStyle(\"width\");\n },\n\n buildContainer: function()\n {\n this.container = new Element(\"span\",{\n \"class\": cfe.prefix+this.type+\"Container\",\n \"styles\":{\n \"overflow\":\"hidden\"\n }\n });\n \n this.containerWrapper = this.container.setSlidingDoors(4, \"span\", cfe.prefix).addClass(cfe.prefix+this.type+\"ContainerWrapper\").setStyles({\n position: \"absolute\",\n \"z-index\": this.instance + 1\n }).inject(this.a);\n\n // insert option elements\n this.allOptions = [];\n this.origOptions.each(function(el,i)\n {\n this.allOptions.push(this.buildOption(el, i))\n }.bind(this));\n\n this.container.adopt(this.allOptions);\n\n },\n\n buildOption: function(el, i)\n {\n return new Element(\"span\",{\n \"class\": cfe.prefix+\"Option \"+cfe.prefix+\"Option\"+i+(el.get('class')?\" \"+el.get('class'):\"\"),\n \"events\":{\n \"mouseover\": this.highlightOption.pass([i,true],this)/*,\n \"mouseout\": this.highlightOption.pass([i,true],this)*/\n }\n }).set('html', el.innerHTML.replace(/\\s/g, \" \")).disableTextSelection().store(\"index\", i);\n },\n\n selectOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n this.highlightOption(index);\n\n this.selectedIndex = index;\n\n this.innerlabel.set('html', (this.allOptions[index]).innerHTML);\n\n this.fireEvent(\"onSelectOption\", index);\n },\n\n highlightOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n if(this.highlighted) this.highlighted.removeClass(\"H\");\n\n this.highlighted = this.allOptions[index].addClass(\"H\");\n\n this.highlightedIndex = index;\n\n this.fireEvent(\"onHighlightOption\", index);\n },\n\n updateOption: function(by)\n {\n // fix for IE 7\n if(this.containerWrapper.retrieve(\"hidden\") != true && !Browser.ie) this.o.selectedIndex = (this.highlightedIndex+by).limit(0,this.origOptions.length-1);\n this.o.fireEvent(\"change\");\n },\n\n hideContainer: function()\n {\n $(document.body).removeEvent(\"click\", this.clickedOutsideListener);\n \n this.containerWrapper.setStyle(\"display\",\"none\").removeClass(\"F\").store(\"hidden\", true);\n\n this.fireEvent(\"onContainerHide\", this.selectedIndex);\n },\n\n showContainer: function()\n {\n $(document.body).addEvent(\"click\", this.clickedOutsideListener);\n\n this.containerWrapper.setStyle(\"display\", \"block\").addClass(\"F\").store(\"hidden\", false);\n\n this.highlightOption(this.o.selectedIndex);\n\n this.fireEvent(\"onContainerShow\", this.selectedIndex);\n },\n\n clicked: function(ev)\n {\n if(!this.isDisabled())\n {\n if( ev.target != null )\n {\n var oTarget = $(ev.target);\n\n if( oTarget.getParent() == this.container )\n {\n this.selectOption(oTarget.retrieve(\"index\"), true);\n this.hideContainer();\n this.parent();\n this.o.selectedIndex = oTarget.retrieve(\"index\");\n this.o.fireEvent(\"change\");\n return;\n }\n else if(this.options.scrolling && oTarget.getParent(\".\"+this.scrollerWrapper.getProperty(\"class\")) == this.scrollerWrapper)\n {\n //console.log(\"no toggle\");\n return;\n }\n }\n\n this.toggle();\n this.parent();\n }\n },\n\n toggle: function()\n {\n this.containerWrapper.retrieve(\"hidden\") == true ? this.showContainer() : this.hideContainer();\n },\n\t\n keyup: function(ev)\n {\n // toggle on alt+arrow\n if(ev.alt && (ev.key == \"up\" || ev.key == \"down\") )\n {\n this.toggle();\n return;\n }\n\n switch(ev.key){\n case \"enter\":\n case \"space\":\n this.toggle();\n break;\n\n case \"up\":\n this.updateOption(-1);\n break;\n\n case \"down\":\n this.updateOption(1);\n break;\n\n case \"esc\":\n this.hideContainer();\n break;\n \n default:\n this.o.fireEvent(\"change\");\n break;\n }\n },\n\n keydown: function(ev)\n {\n if(ev.key == \"tab\")\n {\n this.hideContainer();\n }\n },\n\n clickedOutsideListener: function(ev)\n {\n if ($(ev.target).getParent(\".\"+cfe.prefix+this.type) != this.a && !( (Browser.ie || Browser.opera) && ev.target == this.o) && ( this.l == null || (this.l && $(ev.target) != this.l) ) ) this.hideContainer();\n },\n\n update: function()\n {\n this.parent();\n this.selectOption(this.o.selectedIndex);\n }\n});", "demo.html": "\n\n \n \n \n\n \n \n \n \n\n \n \n

      CFE Barebone Example

      \n

      for mootools 1.2

      \n

      \n Visit homepage\n

      \n\n
      \n\n\n
      Checkboxes (input[checkbox])\n \n\n
      \n\n
      Checkboxes with implicit labelling\n

      NOTE: 3rd Checkbox has dependencies: 1st and 2nd get automatically checked if not already

      \n
        \n
      • \n
      • \n\n
      • \n
      • \n\n
      • \n\n
      \n
      \n\n\n
      Radiobuttons (input[radio])\n
        \n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • \n
      • \n\n
      • \n
      • \n\n\n
      • \n
      • \n\n
      • \n
      • \n
      \n
      \n\n\n
      Textinput&-area(input[text,password],textarea)- w/ slidingDoors\n
        \n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • trigger textfield 4 disabled/enabled\n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • trigger textarea 2 disabled/enabled\n
      • \n\n
      • \n \n
      • \n
      \n
      \n\n\n\n
      Textinput&-area with implicit labelling\n
        \n
      • \n
      • \n\n
      • \n
      • \n\n
      • \n
      • \n\n
      • \n\n
      • \n\n
      • \n
      • \n
      \n
      \n\n\n\n \n\n
      Selectfield (select) with and without multiple option and preselected\n
        \n\n
      • \n \n
      • \n\n
      • \n\n \n
      • \n\n
      • \n \n
      • \n\n
      • trigger select 3 disabled/enabled\n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • trigger multiple select 2 disabled/enabled\n
      • \n
      \n
      \n\n\n\n
      file upload (input[file]) -- without and with implicit labelling\n
        \n
      • \n \n
      • \n\n
      • \n
      • \n\n
      • \n \n
      • \n
      \n
      \n\n\n
      \n Check POST Data or Reset Data via Buttons (input[submit], input[reset], input[image])\n\n
        \n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n\n
      • \n \n
      • \n
      \n\n
      \n\n
      Advanced example: Search field\n
        \n
      • \n \n \" name=\"inputSearchSubmit\" />\n
      • \n
      \n
      \n
      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n", "cfe/modules/select/cfe.module.select.multiple.js": "/**\n * @module Selectable\n */\n\n/**\n * replaces select fields with attribute multiple set\n *\n * bug:\n * mouseWheel support needed\n * \n * @class SelectMultiple\n * @namespace cfe.module\n *\n * @extends cfe.module.Select\n */\ncfe.module.SelectMultiple = new Class({\n\t\n Extends: cfe.module.Select,\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"select[multiple]\",\n\n options: {\n buttonStyle: false\n },\n\n afterInitialize: function()\n {\n this.containerWrapper.addClass(cfe.prefix+\"SelectContainerWrapper\").setStyles({\n \"position\": \"relative\",\n \"z-index\": \"auto\"\n });\n this.container.addClass(cfe.prefix+\"SelectContainer\");\n\n this.o.addEvents({\n onDisable: function(){\n this.containerWrapper.getElements(\"input, button\").each(function(el){\n el.disable();\n });\n }.bind(this),\n onEnable: function(){\n this.containerWrapper.getElements(\"input, button\").each(function(el){\n el.enable();\n });\n }.bind(this)\n });\n \n this.parent();\n },\n\n setupWrapperEvents: function()\n {\n this.a = this.containerWrapper;\n this.parent();\n },\n\n buildOption: function(el, index)\n {\n var oOpt = new cfe.module.Checkbox({\n label: el.innerHTML,\n checked: (el.selected != null),\n disabled: this.isDisabled()\n });\n oOpt.index = index;\n\n oOpt.addEvents({\n \"check\": function(index){\n this.origOptions[index].selected = true;\n this.o.fireEvent(\"change\")\n }.pass(index, this),\n \"uncheck\": function(index){\n this.origOptions[index].selected = false;\n this.o.fireEvent(\"change\")\n }.pass(index, this)\n });\n\n $(oOpt).addClass(cfe.prefix+\"Option \"+cfe.prefix+\"Option\"+index+(el.get('class')?\" \".el.get('class'):\"\")).disableTextSelection();\n oOpt.getLabel().removeEvents().inject( $(oOpt) );\n\n return $(oOpt);\n },\n\n selectOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n this.highlightOption(index);\n },\n\n clicked: function()\n {\n if(!this.isDisabled())\n {\n this.o.focus();\n this.fireEvent(\"onClick\");\n }\n },\n\n update: function()\n {\n this.fireEvent(\"onUpdate\");\n },\n\n toggle: function(){},\n keydown: function(){},\n hideContainer: function(){},\n showContainer: function(){}\n});"}} +{"repo": "dokufreaks/plugin-discussion", "pr_number": 348, "filename": "helper.php", "file_before": "\n */\n\n/**\n * Class helper_plugin_discussion\n */\nclass helper_plugin_discussion extends DokuWiki_Plugin\n{\n\n /**\n * @return array\n */\n public function getMethods()\n {\n $result = [];\n $result[] = [\n 'name' => 'th',\n 'desc' => 'returns the header of the comments column for pagelist',\n 'return' => ['header' => 'string'],\n ];\n $result[] = [\n 'name' => 'td',\n 'desc' => 'returns the link to the discussion section with number of comments',\n 'params' => [\n 'id' => 'string',\n 'number of comments (optional)' => 'integer'],\n 'return' => ['link' => 'string'],\n ];\n $result[] = [\n 'name' => 'getThreads',\n 'desc' => 'returns pages with discussion sections, sorted by recent comments',\n 'params' => [\n 'namespace' => 'string',\n 'number (optional)' => 'integer'],\n 'return' => ['pages' => 'array'],\n ];\n $result[] = [\n 'name' => 'getComments',\n 'desc' => 'returns recently added or edited comments individually',\n 'params' => [\n 'namespace' => 'string',\n 'number (optional)' => 'integer'],\n 'return' => ['pages' => 'array'],\n ];\n $result[] = [\n 'name' => 'isDiscussionModerator',\n 'desc' => 'check if current user is member of moderator groups',\n 'params' => [],\n 'return' => ['isModerator' => 'boolean']\n ];\n return $result;\n }\n\n /**\n * Returns the column header for the Pagelist Plugin\n *\n * @return string\n */\n public function th()\n {\n return $this->getLang('discussion');\n }\n\n /**\n * Returns the link to the discussion section of a page\n *\n * @param string $id page id\n * @param string $col column name, used if more columns needed per plugin\n * @param string $class class name per cell set by reference\n * @param null|int $num number of visible comments -- internally used, not by pagelist plugin\n * @return string\n */\n public function td($id, $col = null, &$class = null, $num = null)\n {\n $section = '#discussion__section';\n\n if (!isset($num)) {\n $cfile = metaFN($id, '.comments');\n $comments = unserialize(io_readFile($cfile, false));\n\n $num = $comments['number'];\n if (!$comments['status'] || ($comments['status'] == 2 && !$num)) {\n return '';\n }\n }\n\n if ($num == 0) {\n $comment = '0 ' . $this->getLang('nocomments');\n } elseif ($num == 1) {\n $comment = '1 ' . $this->getLang('comment');\n } else {\n $comment = $num . ' ' . $this->getLang('comments');\n }\n\n return ''\n . $comment\n . '';\n }\n\n /**\n * Returns an array of pages with discussion sections, sorted by recent comments\n * Note: also used for content by Feed Plugin\n *\n * @param string $ns\n * @param null|int $num\n * @param string|bool $skipEmpty\n * @return array\n */\n public function getThreads($ns, $num = null, $skipEmpty = false)\n {\n global $conf;\n\n // returns the list of pages in the given namespace and it's subspaces\n $dir = utf8_encodeFN(str_replace(':', '/', $ns));\n $opts = [\n 'depth' => 0, // 0=all\n 'skipacl' => true // is checked later\n ];\n $items = [];\n search($items, $conf['datadir'], 'search_allpages', $opts, $dir);\n\n // add pages with comments to result\n $result = [];\n foreach ($items as $item) {\n $id = $item['id'];\n\n // some checks\n $perm = auth_quickaclcheck($id);\n if ($perm < AUTH_READ) continue; // skip if no permission\n $file = metaFN($id, '.comments');\n if (!@file_exists($file)) continue; // skip if no comments file\n $data = unserialize(io_readFile($file, false));\n $status = $data['status'];\n $number = $data['number'];\n\n if (!$status || ($status == 2 && !$number)) continue; // skip if comments are off or closed without comments\n if ($skipEmpty && $number == 0) continue; // skip if discussion is empty and flag is set\n\n //new comments are added to the end of array\n $date = false;\n if(isset($data['comments'])) {\n $latestcomment = end($data['comments']);\n $date = $latestcomment['date']['created'] ?? false;\n }\n //e.g. if no comments\n if(!$date) {\n $date = filemtime($file);\n }\n\n $meta = p_get_metadata($id);\n $result[$date . '_' . $id] = [\n 'id' => $id,\n 'file' => $file,\n 'title' => $meta['title'] ?? '',\n 'date' => $date,\n 'user' => $meta['creator'],\n 'desc' => $meta['description']['abstract'],\n 'num' => $number,\n 'comments' => $this->td($id, null, $class, $number),\n 'status' => $status,\n 'perm' => $perm,\n 'exists' => true,\n 'anchor' => 'discussion__section',\n ];\n }\n\n // finally sort by time of last comment\n krsort($result);\n\n if (is_numeric($num)) {\n $result = array_slice($result, 0, $num);\n }\n\n return $result;\n }\n\n /**\n * Returns an array of recently added comments to a given page or namespace\n * Note: also used for content by Feed Plugin\n *\n * @param string $ns\n * @param int|null $num number of comment per page\n * @return array\n */\n public function getComments($ns, $num = null)\n {\n global $conf, $INPUT;\n\n $first = $INPUT->int('first');\n\n if (!$num || !is_numeric($num)) {\n $num = $conf['recent'];\n }\n\n $result = [];\n $count = 0;\n\n if (!@file_exists($conf['metadir'] . '/_comments.changes')) {\n return $result;\n }\n\n // read all recent changes. (kept short)\n $lines = file($conf['metadir'] . '/_comments.changes');\n\n $seen = []; //caches seen pages in order to skip them\n // handle lines\n $line_num = count($lines);\n for ($i = ($line_num - 1); $i >= 0; $i--) {\n $rec = $this->handleRecentComment($lines[$i], $ns, $seen);\n if ($rec !== false) {\n if (--$first >= 0) continue; // skip first entries\n\n $result[$rec['date']] = $rec;\n $count++;\n // break when we have enough entries\n if ($count >= $num) break;\n }\n }\n\n // finally sort by time of last comment\n krsort($result);\n\n return $result;\n }\n\n /* ---------- Changelog function adapted for the Discussion Plugin ---------- */\n\n /**\n * Internal function used by $this->getComments()\n *\n * don't call directly\n *\n * @param string $line comment changelog line\n * @param string $ns namespace (or id) to filter\n * @param array $seen array to cache seen pages\n * @return array|false with\n * 'type' => string,\n * 'extra' => string comment id,\n * 'id' => string page id,\n * 'perm' => int ACL permission\n * 'file' => string file path of wiki page\n * 'exists' => bool wiki page exists\n * 'name' => string name of user\n * 'desc' => string text of comment\n * 'anchor' => string\n *\n * @see getRecentComments()\n * @author Andreas Gohr \n * @author Ben Coburn \n * @author Esther Brunner \n *\n */\n protected function handleRecentComment($line, $ns, &$seen)\n {\n if (empty($line)) return false; //skip empty lines\n\n // split the line into parts\n $recent = parseChangelogLine($line);\n if ($recent === false) return false;\n\n $cid = $recent['extra'];\n $fullcid = $recent['id'] . '#' . $recent['extra'];\n\n // skip seen ones\n if (isset($seen[$fullcid])) return false;\n\n // skip 'show comment' log entries\n if ($recent['type'] === 'sc') return false;\n\n // remember in seen to skip additional sights\n $seen[$fullcid] = 1;\n\n // check if it's a hidden page or comment\n if (isHiddenPage($recent['id'])) return false;\n if ($recent['type'] === 'hc') return false;\n\n // filter namespace or id\n if ($ns && strpos($recent['id'] . ':', $ns . ':') !== 0) return false;\n\n // check ACL\n $recent['perm'] = auth_quickaclcheck($recent['id']);\n if ($recent['perm'] < AUTH_READ) return false;\n\n // check existance\n $recent['file'] = wikiFN($recent['id']);\n $recent['exists'] = @file_exists($recent['file']);\n if (!$recent['exists']) return false;\n if ($recent['type'] === 'dc') return false;\n\n // get discussion meta file name\n $data = unserialize(io_readFile(metaFN($recent['id'], '.comments'), false));\n\n // check if discussion is turned off\n if ($data['status'] === 0) return false;\n\n $parent_id = $cid;\n // Check for the comment and all parents if they exist and are visible.\n do {\n $tcid = $parent_id;\n\n // check if the comment still exists\n if (!isset($data['comments'][$tcid])) return false;\n // check if the comment is visible\n if ($data['comments'][$tcid]['show'] != 1) return false;\n\n $parent_id = $data['comments'][$tcid]['parent'];\n } while ($parent_id && $parent_id != $tcid);\n\n // okay, then add some additional info\n if (is_array($data['comments'][$cid]['user'])) {\n $recent['name'] = $data['comments'][$cid]['user']['name'];\n } else {\n $recent['name'] = $data['comments'][$cid]['name'];\n }\n $recent['desc'] = strip_tags($data['comments'][$cid]['xhtml']);\n $recent['anchor'] = 'comment_' . $cid;\n\n return $recent;\n }\n\n /**\n * Check if current user is member of the moderator groups\n *\n * @return bool is moderator?\n */\n public function isDiscussionModerator()\n {\n global $USERINFO, $INPUT;\n $groups = trim($this->getConf('moderatorgroups'));\n\n if (auth_ismanager()) {\n return true;\n }\n // Check if user is member of the moderator groups\n if (!empty($groups) && auth_isMember($groups, $INPUT->server->str('REMOTE_USER'), (array)$USERINFO['grps'])) {\n return true;\n }\n\n return false;\n }\n}\n", "file_after": "\n */\n\n/**\n * Class helper_plugin_discussion\n */\nclass helper_plugin_discussion extends DokuWiki_Plugin\n{\n\n /**\n * @return array\n */\n public function getMethods()\n {\n $result = [];\n $result[] = [\n 'name' => 'th',\n 'desc' => 'returns the header of the comments column for pagelist',\n 'return' => ['header' => 'string'],\n ];\n $result[] = [\n 'name' => 'td',\n 'desc' => 'returns the link to the discussion section with number of comments',\n 'params' => [\n 'id' => 'string',\n 'number of comments (optional)' => 'integer'],\n 'return' => ['link' => 'string'],\n ];\n $result[] = [\n 'name' => 'getThreads',\n 'desc' => 'returns pages with discussion sections, sorted by recent comments',\n 'params' => [\n 'namespace' => 'string',\n 'number (optional)' => 'integer'],\n 'return' => ['pages' => 'array'],\n ];\n $result[] = [\n 'name' => 'getComments',\n 'desc' => 'returns recently added or edited comments individually',\n 'params' => [\n 'namespace' => 'string',\n 'number (optional)' => 'integer'],\n 'return' => ['pages' => 'array'],\n ];\n $result[] = [\n 'name' => 'isDiscussionModerator',\n 'desc' => 'check if current user is member of moderator groups',\n 'params' => [],\n 'return' => ['isModerator' => 'boolean']\n ];\n return $result;\n }\n\n /**\n * Returns the column header for the Pagelist Plugin\n *\n * @return string\n */\n public function th()\n {\n return $this->getLang('discussion');\n }\n\n /**\n * Returns the link to the discussion section of a page\n *\n * @param string $id page id\n * @param string $col column name, used if more columns needed per plugin\n * @param string $class class name per cell set by reference\n * @param null|int $num number of visible comments -- internally used, not by pagelist plugin\n * @return string\n */\n public function td($id, $col = null, &$class = null, $num = null)\n {\n $section = '#discussion__section';\n\n if (!isset($num)) {\n $cfile = metaFN($id, '.comments');\n $comments = unserialize(io_readFile($cfile, false));\n\n if ($comments) {\n $num = $comments['number'];\n if (!$comments['status'] || ($comments['status'] == 2 && !$num)) {\n return '';\n }\n } else {\n $num = 0;\n }\n }\n\n if ($num == 0) {\n $comment = '0 ' . $this->getLang('nocomments');\n } elseif ($num == 1) {\n $comment = '1 ' . $this->getLang('comment');\n } else {\n $comment = $num . ' ' . $this->getLang('comments');\n }\n\n return ''\n . $comment\n . '';\n }\n\n /**\n * Returns an array of pages with discussion sections, sorted by recent comments\n * Note: also used for content by Feed Plugin\n *\n * @param string $ns\n * @param null|int $num\n * @param string|bool $skipEmpty\n * @return array\n */\n public function getThreads($ns, $num = null, $skipEmpty = false)\n {\n global $conf;\n\n // returns the list of pages in the given namespace and it's subspaces\n $dir = utf8_encodeFN(str_replace(':', '/', $ns));\n $opts = [\n 'depth' => 0, // 0=all\n 'skipacl' => true // is checked later\n ];\n $items = [];\n search($items, $conf['datadir'], 'search_allpages', $opts, $dir);\n\n // add pages with comments to result\n $result = [];\n foreach ($items as $item) {\n $id = $item['id'];\n\n // some checks\n $perm = auth_quickaclcheck($id);\n if ($perm < AUTH_READ) continue; // skip if no permission\n $file = metaFN($id, '.comments');\n if (!@file_exists($file)) continue; // skip if no comments file\n $data = unserialize(io_readFile($file, false));\n $status = $data['status'];\n $number = $data['number'];\n\n if (!$status || ($status == 2 && !$number)) continue; // skip if comments are off or closed without comments\n if ($skipEmpty && $number == 0) continue; // skip if discussion is empty and flag is set\n\n //new comments are added to the end of array\n $date = false;\n if(isset($data['comments'])) {\n $latestcomment = end($data['comments']);\n $date = $latestcomment['date']['created'] ?? false;\n }\n //e.g. if no comments\n if(!$date) {\n $date = filemtime($file);\n }\n\n $meta = p_get_metadata($id);\n $result[$date . '_' . $id] = [\n 'id' => $id,\n 'file' => $file,\n 'title' => $meta['title'] ?? '',\n 'date' => $date,\n 'user' => $meta['creator'],\n 'desc' => $meta['description']['abstract'],\n 'num' => $number,\n 'comments' => $this->td($id, null, $class, $number),\n 'status' => $status,\n 'perm' => $perm,\n 'exists' => true,\n 'anchor' => 'discussion__section',\n ];\n }\n\n // finally sort by time of last comment\n krsort($result);\n\n if (is_numeric($num)) {\n $result = array_slice($result, 0, $num);\n }\n\n return $result;\n }\n\n /**\n * Returns an array of recently added comments to a given page or namespace\n * Note: also used for content by Feed Plugin\n *\n * @param string $ns\n * @param int|null $num number of comment per page\n * @return array\n */\n public function getComments($ns, $num = null)\n {\n global $conf, $INPUT;\n\n $first = $INPUT->int('first');\n\n if (!$num || !is_numeric($num)) {\n $num = $conf['recent'];\n }\n\n $result = [];\n $count = 0;\n\n if (!@file_exists($conf['metadir'] . '/_comments.changes')) {\n return $result;\n }\n\n // read all recent changes. (kept short)\n $lines = file($conf['metadir'] . '/_comments.changes');\n\n $seen = []; //caches seen pages in order to skip them\n // handle lines\n $line_num = count($lines);\n for ($i = ($line_num - 1); $i >= 0; $i--) {\n $rec = $this->handleRecentComment($lines[$i], $ns, $seen);\n if ($rec !== false) {\n if (--$first >= 0) continue; // skip first entries\n\n $result[$rec['date']] = $rec;\n $count++;\n // break when we have enough entries\n if ($count >= $num) break;\n }\n }\n\n // finally sort by time of last comment\n krsort($result);\n\n return $result;\n }\n\n /* ---------- Changelog function adapted for the Discussion Plugin ---------- */\n\n /**\n * Internal function used by $this->getComments()\n *\n * don't call directly\n *\n * @param string $line comment changelog line\n * @param string $ns namespace (or id) to filter\n * @param array $seen array to cache seen pages\n * @return array|false with\n * 'type' => string,\n * 'extra' => string comment id,\n * 'id' => string page id,\n * 'perm' => int ACL permission\n * 'file' => string file path of wiki page\n * 'exists' => bool wiki page exists\n * 'name' => string name of user\n * 'desc' => string text of comment\n * 'anchor' => string\n *\n * @see getRecentComments()\n * @author Andreas Gohr \n * @author Ben Coburn \n * @author Esther Brunner \n *\n */\n protected function handleRecentComment($line, $ns, &$seen)\n {\n if (empty($line)) return false; //skip empty lines\n\n // split the line into parts\n $recent = parseChangelogLine($line);\n if ($recent === false) return false;\n\n $cid = $recent['extra'];\n $fullcid = $recent['id'] . '#' . $recent['extra'];\n\n // skip seen ones\n if (isset($seen[$fullcid])) return false;\n\n // skip 'show comment' log entries\n if ($recent['type'] === 'sc') return false;\n\n // remember in seen to skip additional sights\n $seen[$fullcid] = 1;\n\n // check if it's a hidden page or comment\n if (isHiddenPage($recent['id'])) return false;\n if ($recent['type'] === 'hc') return false;\n\n // filter namespace or id\n if ($ns && strpos($recent['id'] . ':', $ns . ':') !== 0) return false;\n\n // check ACL\n $recent['perm'] = auth_quickaclcheck($recent['id']);\n if ($recent['perm'] < AUTH_READ) return false;\n\n // check existance\n $recent['file'] = wikiFN($recent['id']);\n $recent['exists'] = @file_exists($recent['file']);\n if (!$recent['exists']) return false;\n if ($recent['type'] === 'dc') return false;\n\n // get discussion meta file name\n $data = unserialize(io_readFile(metaFN($recent['id'], '.comments'), false));\n\n // check if discussion is turned off\n if ($data['status'] === 0) return false;\n\n $parent_id = $cid;\n // Check for the comment and all parents if they exist and are visible.\n do {\n $tcid = $parent_id;\n\n // check if the comment still exists\n if (!isset($data['comments'][$tcid])) return false;\n // check if the comment is visible\n if ($data['comments'][$tcid]['show'] != 1) return false;\n\n $parent_id = $data['comments'][$tcid]['parent'];\n } while ($parent_id && $parent_id != $tcid);\n\n // okay, then add some additional info\n if (is_array($data['comments'][$cid]['user'])) {\n $recent['name'] = $data['comments'][$cid]['user']['name'];\n } else {\n $recent['name'] = $data['comments'][$cid]['name'];\n }\n $recent['desc'] = strip_tags($data['comments'][$cid]['xhtml']);\n $recent['anchor'] = 'comment_' . $cid;\n\n return $recent;\n }\n\n /**\n * Check if current user is member of the moderator groups\n *\n * @return bool is moderator?\n */\n public function isDiscussionModerator()\n {\n global $USERINFO, $INPUT;\n $groups = trim($this->getConf('moderatorgroups'));\n\n if (auth_ismanager()) {\n return true;\n }\n // Check if user is member of the moderator groups\n if (!empty($groups) && auth_isMember($groups, $INPUT->server->str('REMOTE_USER'), (array)$USERINFO['grps'])) {\n return true;\n }\n\n return false;\n }\n}\n"} +{"repo": "dokufreaks/plugin-discussion", "pr_number": 348, "filename": "action.php", "file_before": "\n */\n\nuse dokuwiki\\Extension\\Event;\nuse dokuwiki\\Subscriptions\\SubscriberManager;\nuse dokuwiki\\Utf8\\PhpString;\n\n/**\n * Class action_plugin_discussion\n *\n * Data format of file metadir/.comments:\n * array = [\n * 'status' => int whether comments are 0=disabled/1=open/2=closed,\n * 'number' => int number of visible comments,\n * 'title' => string|null alternative title for discussion section\n * 'comments' => [\n * ''=> [\n * 'cid' => string comment id - long random string\n * 'raw' => string comment text,\n * 'xhtml' => string rendered html,\n * 'parent' => null|string null or empty string at highest level, otherwise comment id of parent\n * 'replies' => string[] array with comment ids\n * 'user' => [\n * 'id' => string,\n * 'name' => string,\n * 'mail' => string,\n * 'address' => string,\n * 'url' => string\n * ],\n * 'date' => [\n * 'created' => int timestamp,\n * 'modified' => int (not defined if not modified)\n * ],\n * 'show' => bool, whether shown (still be moderated, or hidden by moderator or user self)\n * ],\n * ...\n * ]\n * 'subscribers' => [\n * '' => [\n * 'hash' => string unique token,\n * 'active' => bool, true if confirmed\n * 'confirmsent' => bool, true if confirmation mail is sent\n * ],\n * ...\n * ]\n */\nclass action_plugin_discussion extends DokuWiki_Action_Plugin\n{\n\n /** @var helper_plugin_avatar */\n protected $avatar = null;\n /** @var null|string */\n protected $style = null;\n /** @var null|bool */\n protected $useAvatar = null;\n /** @var helper_plugin_discussion */\n protected $helper = null;\n\n /**\n * load helper\n */\n public function __construct()\n {\n $this->helper = plugin_load('helper', 'discussion');\n }\n\n /**\n * Register the handlers\n *\n * @param Doku_Event_Handler $controller DokuWiki's event controller object.\n */\n public function register(Doku_Event_Handler $controller)\n {\n $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleCommentActions');\n $controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, 'renderCommentsSection');\n $controller->register_hook('INDEXER_PAGE_ADD', 'AFTER', $this, 'addCommentsToIndex', ['id' => 'page', 'text' => 'body']);\n $controller->register_hook('FULLTEXT_SNIPPET_CREATE', 'BEFORE', $this, 'addCommentsToIndex', ['id' => 'id', 'text' => 'text']);\n $controller->register_hook('INDEXER_VERSION_GET', 'BEFORE', $this, 'addIndexVersion', []);\n $controller->register_hook('FULLTEXT_PHRASE_MATCH', 'AFTER', $this, 'fulltextPhraseMatchInComments', []);\n $controller->register_hook('PARSER_METADATA_RENDER', 'AFTER', $this, 'updateCommentStatusFromMetadata', []);\n $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'addToolbarToCommentfield', []);\n $controller->register_hook('TOOLBAR_DEFINE', 'AFTER', $this, 'modifyToolbar', []);\n $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajaxPreviewComments', []);\n $controller->register_hook('TPL_TOC_RENDER', 'BEFORE', $this, 'addDiscussionToTOC', []);\n }\n\n /**\n * Preview Comments\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function ajaxPreviewComments(Doku_Event $event)\n {\n global $INPUT;\n if ($event->data != 'discussion_preview') return;\n\n $event->preventDefault();\n $event->stopPropagation();\n print p_locale_xhtml('preview');\n print '
      ';\n if (!$INPUT->server->str('REMOTE_USER') && !$this->getConf('allowguests')) {\n print p_locale_xhtml('denied');\n } else {\n print $this->renderComment($INPUT->post->str('comment'));\n }\n print '
      ';\n }\n\n /**\n * Adds a TOC item if a discussion exists\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function addDiscussionToTOC(Doku_Event $event)\n {\n global $ACT;\n if ($this->hasDiscussion($title) && $event->data && $ACT != 'admin') {\n $tocitem = [\n 'hid' => 'discussion__section',\n 'title' => $title ?: $this->getLang('discussion'),\n 'type' => 'ul',\n 'level' => 1\n ];\n\n $event->data[] = $tocitem;\n }\n }\n\n /**\n * Modify Toolbar for use with discussion plugin\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function modifyToolbar(Doku_Event $event)\n {\n global $ACT;\n if ($ACT != 'show') return;\n\n if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) {\n $toolbar = [];\n foreach ($event->data as $btn) {\n if ($btn['type'] == 'mediapopup') continue;\n if ($btn['type'] == 'signature') continue;\n if ($btn['type'] == 'linkwiz') continue;\n if ($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin\n //FIXME does nothing. Checks for '=' on toplevel, but today it are special buttons and a picker with subarray\n if (isset($btn['open']) && preg_match(\"/=+?/\", $btn['open'])) continue;\n\n $toolbar[] = $btn;\n }\n $event->data = $toolbar;\n }\n }\n\n /**\n * Dirty workaround to add a toolbar to the discussion plugin\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function addToolbarToCommentfield(Doku_Event $event)\n {\n global $ACT;\n global $ID;\n if ($ACT != 'show') return;\n\n if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) {\n // FIXME ugly workaround, replace this once DW the toolbar code is more flexible\n @require_once(DOKU_INC . 'inc/toolbar.php');\n ob_start();\n print 'NS = \"' . getNS($ID) . '\";'; // we have to define NS, otherwise we get get JS errors\n toolbar_JSdefines('toolbar');\n $script = ob_get_clean();\n $event->data['script'][] = ['type' => 'text/javascript', 'charset' => \"utf-8\", '_data' => $script];\n }\n }\n\n /**\n * Handles comment actions, dispatches data processing routines\n *\n * @param Doku_Event $event\n */\n public function handleCommentActions(Doku_Event $event)\n {\n global $ID, $INFO, $lang, $INPUT;\n\n // handle newthread ACTs\n if ($event->data == 'newthread') {\n // we can handle it -> prevent others\n $event->data = $this->newThread();\n }\n\n // enable captchas\n if (in_array($INPUT->str('comment'), ['add', 'save'])) {\n $this->captchaCheck();\n $this->recaptchaCheck();\n }\n\n // if we are not in show mode or someone wants to unsubscribe, that was all for now\n if ($event->data != 'show'\n && $event->data != 'discussion_unsubscribe'\n && $event->data != 'discussion_confirmsubscribe') {\n return;\n }\n\n if ($event->data == 'discussion_unsubscribe' or $event->data == 'discussion_confirmsubscribe') {\n if ($INPUT->has('hash')) {\n $file = metaFN($ID, '.comments');\n $data = unserialize(io_readFile($file));\n $matchedMail = '';\n foreach ($data['subscribers'] as $mail => $info) {\n // convert old style subscribers just in case\n if (!is_array($info)) {\n $hash = $data['subscribers'][$mail];\n $data['subscribers'][$mail]['hash'] = $hash;\n $data['subscribers'][$mail]['active'] = true;\n $data['subscribers'][$mail]['confirmsent'] = true;\n }\n\n if ($data['subscribers'][$mail]['hash'] == $INPUT->str('hash')) {\n $matchedMail = $mail;\n }\n }\n\n if ($matchedMail != '') {\n if ($event->data == 'discussion_unsubscribe') {\n unset($data['subscribers'][$matchedMail]);\n msg(sprintf($lang['subscr_unsubscribe_success'], $matchedMail, $ID), 1);\n } else { //$event->data == 'discussion_confirmsubscribe'\n $data['subscribers'][$matchedMail]['active'] = true;\n msg(sprintf($lang['subscr_subscribe_success'], $matchedMail, $ID), 1);\n }\n io_saveFile($file, serialize($data));\n $event->data = 'show';\n }\n\n }\n return;\n }\n\n // do the data processing for comments\n $cid = $INPUT->str('cid');\n switch ($INPUT->str('comment')) {\n case 'add':\n if (empty($INPUT->str('text'))) return; // don't add empty comments\n\n if ($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) {\n $comment['user']['id'] = $INPUT->server->str('REMOTE_USER');\n $comment['user']['name'] = $INFO['userinfo']['name'];\n $comment['user']['mail'] = $INFO['userinfo']['mail'];\n } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionModerator())\n || !$INPUT->server->has('REMOTE_USER')) {\n // don't add anonymous comments\n if (empty($INPUT->str('name')) or empty($INPUT->str('mail'))) {\n return;\n }\n\n if (!mail_isvalid($INPUT->str('mail'))) {\n msg($lang['regbadmail'], -1);\n return;\n } else {\n $comment['user']['id'] = ''; //prevent overlap with loggedin users, before: 'test'\n $comment['user']['name'] = hsc($INPUT->str('name'));\n $comment['user']['mail'] = hsc($INPUT->str('mail'));\n }\n }\n $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($INPUT->str('address')) : '';\n $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->checkURL($INPUT->str('url')) : '';\n $comment['subscribe'] = ($this->getConf('subscribe')) ? $INPUT->has('subscribe') : '';\n $comment['date'] = ['created' => $INPUT->str('date')];\n $comment['raw'] = cleanText($INPUT->str('text'));\n $reply = $INPUT->str('reply');\n if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) {\n $comment['show'] = false;\n } else {\n $comment['show'] = true;\n }\n $this->add($comment, $reply);\n break;\n\n case 'save':\n $raw = cleanText($INPUT->str('text'));\n $this->save([$cid], $raw);\n break;\n\n case 'delete':\n $this->save([$cid], '');\n break;\n\n case 'toogle':\n $this->save([$cid], '', 'toogle');\n break;\n }\n }\n\n /**\n * Main function; dispatches the visual comment actions\n *\n * @param Doku_Event $event\n */\n public function renderCommentsSection(Doku_Event $event)\n {\n global $INPUT;\n if ($event->data != 'show') return; // nothing to do for us\n\n $cid = $INPUT->str('cid');\n\n if (!$cid) {\n $cid = $INPUT->str('reply');\n }\n\n switch ($INPUT->str('comment')) {\n case 'edit':\n $this->showDiscussionSection(null, $cid);\n break;\n default: //'reply' or no action specified\n $this->showDiscussionSection($cid);\n break;\n }\n }\n\n /**\n * Redirects browser to given comment anchor\n *\n * @param string $cid comment id\n */\n protected function redirect($cid)\n {\n global $ID;\n global $ACT;\n\n if ($ACT !== 'show') return;\n\n if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) {\n msg($this->getLang('moderation'), 1);\n @session_start();\n global $MSG;\n $_SESSION[DOKU_COOKIE]['msg'] = $MSG;\n session_write_close();\n $url = wl($ID);\n } else {\n $url = wl($ID) . '#comment_' . $cid;\n }\n\n if (function_exists('send_redirect')) {\n send_redirect($url);\n } else {\n header('Location: ' . $url);\n }\n exit();\n }\n\n /**\n * Checks config settings to enable/disable discussions\n *\n * @return bool true if enabled\n */\n public function isDiscussionEnabled()\n {\n global $ID;\n\n if ($this->getConf('excluded_ns') == '') {\n $isNamespaceExcluded = false;\n } else {\n $ns = getNS($ID); // $INFO['namespace'] is not yet available, if used in update_comment_status()\n $isNamespaceExcluded = preg_match($this->getConf('excluded_ns'), $ns);\n }\n\n if ($this->getConf('automatic')) {\n if ($isNamespaceExcluded) {\n return false;\n } else {\n return true;\n }\n } else {\n if ($isNamespaceExcluded) {\n return true;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Shows all comments of the current page, if no reply or edit requested, then comment form is shown on the end\n *\n * @param null|string $reply comment id on which the user requested a reply\n * @param null|string $edit comment id which the user requested for editing\n */\n protected function showDiscussionSection($reply = null, $edit = null)\n {\n global $ID, $INFO, $INPUT;\n\n // get .comments meta file name\n $file = metaFN($ID, '.comments');\n\n if (!$INFO['exists']) return;\n if (!@file_exists($file) && !$this->isDiscussionEnabled()) return;\n if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('showguests')) return;\n\n // load data\n $data = [];\n if (@file_exists($file)) {\n $data = unserialize(io_readFile($file, false));\n // comments are turned off\n if (!$data['status']) {\n return;\n }\n } elseif (!@file_exists($file) && $this->isDiscussionEnabled()) {\n // set status to show the comment form\n $data['status'] = 1;\n $data['number'] = 0;\n $data['title'] = null;\n }\n\n // show discussion wrapper only on certain circumstances\n if (empty($data['comments']) || !is_array($data['comments'])) {\n $cnt = 0;\n $cids = [];\n } else {\n $cnt = count($data['comments']);\n $cids = array_keys($data['comments']);\n }\n\n $show = false;\n if ($cnt > 1 || ($cnt == 1 && $data['comments'][$cids[0]]['show'] == 1)\n || $this->getConf('allowguests')\n || $INPUT->server->has('REMOTE_USER')) {\n $show = true;\n // section title\n $title = (!empty($data['title']) ? hsc($data['title']) : $this->getLang('discussion'));\n ptln('
      '); // the id value is used for visibility toggling the section\n ptln('

      ', 2);\n ptln($title, 4);\n ptln('

      ', 2);\n ptln('
      ', 2);\n }\n\n // now display the comments\n if (isset($data['comments'])) {\n if (!$this->getConf('usethreading')) {\n $data['comments'] = $this->flattenThreads($data['comments']);\n uasort($data['comments'], [$this, 'sortThreadsOnCreation']);\n }\n if ($this->getConf('newestfirst')) {\n $data['comments'] = array_reverse($data['comments']);\n }\n foreach ($data['comments'] as $cid => $value) {\n if ($cid == $edit) { // edit form\n $this->showCommentForm($value['raw'], 'save', $edit);\n } else {\n $this->showCommentWithReplies($cid, $data, '', $reply);\n }\n }\n }\n\n // comment form shown on the end, if no comment form of $reply or $edit is requested before\n if ($data['status'] == 1 && (!$reply || !$this->getConf('usethreading')) && !$edit) {\n $this->showCommentForm('', 'add');\n }\n\n if ($show) {\n ptln('
      ', 2); // level2 hfeed\n ptln('
      '); // comment_wrapper\n }\n\n // check for toggle print configuration\n if ($this->getConf('visibilityButton')) {\n // print the hide/show discussion section button\n $this->showDiscussionToggleButton();\n }\n }\n\n /**\n * Remove the parent-child relation, such that the comment structure becomes flat\n *\n * @param array $comments array with all comments\n * @param null|array $cids comment ids of replies, which should be flatten\n * @return array returned array with flattened comment structure\n */\n protected function flattenThreads($comments, $cids = null)\n {\n if (is_null($cids)) {\n $cids = array_keys($comments);\n }\n\n foreach ($cids as $cid) {\n if (!empty($comments[$cid]['replies'])) {\n $rids = $comments[$cid]['replies'];\n $comments = $this->flattenThreads($comments, $rids);\n $comments[$cid]['replies'] = [];\n }\n $comments[$cid]['parent'] = '';\n }\n return $comments;\n }\n\n /**\n * Adds a new comment and then displays all comments\n *\n * @param array $comment with\n * 'raw' => string comment text,\n * 'user' => [\n * 'id' => string,\n * 'name' => string,\n * 'mail' => string\n * ],\n * 'date' => [\n * 'created' => int timestamp\n * ]\n * 'show' => bool\n * 'subscribe' => bool\n * @param string $parent comment id of parent\n * @return bool\n */\n protected function add($comment, $parent)\n {\n global $ID, $TEXT, $INPUT;\n\n $originalTxt = $TEXT; // set $TEXT to comment text for wordblock check\n $TEXT = $comment['raw'];\n\n // spamcheck against the DokuWiki blacklist\n if (checkwordblock()) {\n msg($this->getLang('wordblock'), -1);\n return false;\n }\n\n if (!$this->getConf('allowguests')\n && $comment['user']['id'] != $INPUT->server->str('REMOTE_USER')\n ) {\n return false; // guest comments not allowed\n }\n\n $TEXT = $originalTxt; // restore global $TEXT\n\n // get discussion meta file name\n $file = metaFN($ID, '.comments');\n\n // create comments file if it doesn't exist yet\n if (!@file_exists($file)) {\n $data = [\n 'status' => 1,\n 'number' => 0,\n 'title' => null\n ];\n io_saveFile($file, serialize($data));\n } else {\n $data = unserialize(io_readFile($file, false));\n // comments off or closed\n if ($data['status'] != 1) {\n return false;\n }\n }\n\n if ($comment['date']['created']) {\n $date = strtotime($comment['date']['created']);\n } else {\n $date = time();\n }\n\n if ($date == -1) {\n $date = time();\n }\n\n $cid = md5($comment['user']['id'] . $date); // create a unique id\n\n if (!isset($data['comments'][$parent]) || !is_array($data['comments'][$parent])) {\n $parent = null; // invalid parent comment\n }\n\n // render the comment\n $xhtml = $this->renderComment($comment['raw']);\n\n // fill in the new comment\n $data['comments'][$cid] = [\n 'user' => $comment['user'],\n 'date' => ['created' => $date],\n 'raw' => $comment['raw'],\n 'xhtml' => $xhtml,\n 'parent' => $parent,\n 'replies' => [],\n 'show' => $comment['show']\n ];\n\n if ($comment['subscribe']) {\n $mail = $comment['user']['mail'];\n if (isset($data['subscribers'])) {\n if (!$data['subscribers'][$mail]) {\n $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());\n $data['subscribers'][$mail]['active'] = false;\n $data['subscribers'][$mail]['confirmsent'] = false;\n } else {\n // convert old style subscribers and set them active\n if (!is_array($data['subscribers'][$mail])) {\n $hash = $data['subscribers'][$mail];\n $data['subscribers'][$mail]['hash'] = $hash;\n $data['subscribers'][$mail]['active'] = true;\n $data['subscribers'][$mail]['confirmsent'] = true;\n }\n }\n } else {\n $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());\n $data['subscribers'][$mail]['active'] = false;\n $data['subscribers'][$mail]['confirmsent'] = false;\n }\n }\n\n // update parent comment\n if ($parent) {\n $data['comments'][$parent]['replies'][] = $cid;\n }\n\n // update the number of comments\n $data['number']++;\n\n // notify subscribers of the page\n $data['comments'][$cid]['cid'] = $cid;\n $this->notify($data['comments'][$cid], $data['subscribers']);\n\n // save the comment metadata file\n io_saveFile($file, serialize($data));\n $this->addLogEntry($date, $ID, 'cc', '', $cid);\n\n $this->redirect($cid);\n return true;\n }\n\n /**\n * Saves the comment with the given ID and then displays all comments\n *\n * @param array|string $cids array with comment ids to save, or a single string comment id\n * @param string $raw if empty comment is deleted, otherwise edited text is stored (note: storing is per one cid!)\n * @param string|null $act 'toogle', 'show', 'hide', null. If null, it depends on $raw\n * @return bool succeed?\n */\n public function save($cids, $raw, $act = null)\n {\n global $ID, $INPUT;\n\n if (empty($cids)) return false; // do nothing if we get no comment id\n\n if ($raw) {\n global $TEXT;\n\n $otxt = $TEXT; // set $TEXT to comment text for wordblock check\n $TEXT = $raw;\n\n // spamcheck against the DokuWiki blacklist\n if (checkwordblock()) {\n msg($this->getLang('wordblock'), -1);\n return false;\n }\n\n $TEXT = $otxt; // restore global $TEXT\n }\n\n // get discussion meta file name\n $file = metaFN($ID, '.comments');\n $data = unserialize(io_readFile($file, false));\n\n if (!is_array($cids)) {\n $cids = [$cids];\n }\n foreach ($cids as $cid) {\n\n if (is_array($data['comments'][$cid]['user'])) {\n $user = $data['comments'][$cid]['user']['id'];\n $convert = false;\n } else {\n $user = $data['comments'][$cid]['user'];\n $convert = true;\n }\n\n // someone else was trying to edit our comment -> abort\n if ($user != $INPUT->server->str('REMOTE_USER') && !$this->helper->isDiscussionModerator()) {\n return false;\n }\n\n $date = time();\n\n // need to convert to new format?\n if ($convert) {\n $data['comments'][$cid]['user'] = [\n 'id' => $user,\n 'name' => $data['comments'][$cid]['name'],\n 'mail' => $data['comments'][$cid]['mail'],\n 'url' => $data['comments'][$cid]['url'],\n 'address' => $data['comments'][$cid]['address'],\n ];\n $data['comments'][$cid]['date'] = [\n 'created' => $data['comments'][$cid]['date']\n ];\n }\n\n if ($act == 'toogle') { // toogle visibility\n $now = $data['comments'][$cid]['show'];\n $data['comments'][$cid]['show'] = !$now;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');\n\n } elseif ($act == 'show') { // show comment\n $data['comments'][$cid]['show'] = true;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'sc'; // show comment\n\n } elseif ($act == 'hide') { // hide comment\n $data['comments'][$cid]['show'] = false;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'hc'; // hide comment\n\n } elseif (!$raw) { // remove the comment\n $data['comments'] = $this->removeComment($cid, $data['comments']);\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'dc'; // delete comment\n\n } else { // save changed comment\n $xhtml = $this->renderComment($raw);\n\n // now change the comment's content\n $data['comments'][$cid]['date']['modified'] = $date;\n $data['comments'][$cid]['raw'] = $raw;\n $data['comments'][$cid]['xhtml'] = $xhtml;\n\n $type = 'ec'; // edit comment\n }\n }\n\n // save the comment metadata file\n io_saveFile($file, serialize($data));\n $this->addLogEntry($date, $ID, $type, '', $cid);\n\n $this->redirect($cid);\n return true;\n }\n\n /**\n * Recursive function to remove a comment from the data array\n *\n * @param string $cid comment id to be removed\n * @param array $comments array with all comments\n * @return array returns modified array with all remaining comments\n */\n protected function removeComment($cid, $comments)\n {\n if (is_array($comments[$cid]['replies'])) {\n foreach ($comments[$cid]['replies'] as $rid) {\n $comments = $this->removeComment($rid, $comments);\n }\n }\n unset($comments[$cid]);\n return $comments;\n }\n\n /**\n * Prints an individual comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent comment id of parent\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible is marked as visible\n */\n protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = '', $isVisible = true)\n {\n // comment was removed\n if (!isset($data['comments'][$cid])) {\n return;\n }\n $comment = $data['comments'][$cid];\n\n // corrupt datatype\n if (!is_array($comment)) {\n return;\n }\n\n // handle only replies to given parent comment\n if ($comment['parent'] != $parent) {\n return;\n }\n\n // comment hidden, only shown for moderators\n if (!$comment['show'] && !$this->helper->isDiscussionModerator()) {\n return;\n }\n\n // print the actual comment\n $this->showComment($cid, $data, $reply, $isVisible);\n // replies to this comment entry?\n $this->showReplies($cid, $data, $reply, $isVisible);\n // reply form\n $this->showReplyForm($cid, $reply);\n }\n\n /**\n * Print the comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible (grand)parent is marked as visible\n */\n protected function showComment($cid, $data, $reply, $isVisible)\n {\n global $conf, $lang, $HIGH, $INPUT;\n $comment = $data['comments'][$cid];\n\n //only moderators can arrive here if hidden\n $class = '';\n if (!$comment['show'] || !$isVisible) {\n $class = ' comment_hidden';\n }\n if($cid === $reply) {\n $class .= ' reply';\n }\n // comment head with date and user data\n ptln('
      ', 4);\n ptln('
      ', 6);\n ptln('', 8);\n $head = '';\n\n // prepare variables\n if (is_array($comment['user'])) { // new format\n $user = $comment['user']['id'];\n $name = $comment['user']['name'];\n $mail = $comment['user']['mail'];\n $url = $comment['user']['url'];\n $address = $comment['user']['address'];\n } else { // old format\n $user = $comment['user'];\n $name = $comment['name'];\n $mail = $comment['mail'];\n $url = $comment['url'];\n $address = $comment['address'];\n }\n if (is_array($comment['date'])) { // new format\n $created = $comment['date']['created'];\n $modified = $comment['date']['modified'] ?? null;\n } else { // old format\n $created = $comment['date'];\n $modified = $comment['edited'];\n }\n\n // show username or real name?\n if (!$this->getConf('userealname') && $user) {\n //not logged-in users have currently username set to '', but before 'test'\n if(substr($user, 0,4) === 'test'\n && (strpos($user, ':', 4) !== false || strpos($user, '.', 4) !== false)) {\n $showname = $name;\n } else {\n $showname = $user;\n }\n } else {\n $showname = $name;\n }\n\n // show avatar image?\n if ($this->useAvatar()) {\n $user_data['name'] = $name;\n $user_data['user'] = $user;\n $user_data['mail'] = $mail;\n $align = $lang['direction'] === 'ltr' ? 'left' : 'right';\n $avatar = $this->avatar->getXHTML($user_data, $name, $align);\n if ($avatar) {\n $head .= $avatar;\n }\n }\n\n if ($this->getConf('linkemail') && $mail) {\n $head .= $this->email($mail, $showname, 'email fn');\n } elseif ($url) {\n $head .= $this->external_link($this->checkURL($url), $showname, 'urlextern url fn');\n } else {\n $head .= '' . $showname . '';\n }\n\n if ($address) {\n $head .= ', ' . $address . '';\n }\n $head .= ', ' .\n '' .\n dformat($created, $conf['dformat']) . '';\n if ($modified) {\n $head .= ', ' . dformat($modified, $conf['dformat']) .\n '';\n }\n ptln($head, 8);\n ptln('
      ', 6); // class=\"comment_head\"\n\n // main comment content\n ptln('
      useAvatar() ? $this->getWidthStyle() : '') . '>', 6);\n echo ($HIGH ? html_hilight($comment['xhtml'], $HIGH) : $comment['xhtml']) . DOKU_LF;\n ptln('
      ', 6); // class=\"comment_body\"\n\n if ($isVisible) {\n ptln('
      ', 6);\n\n // show reply button?\n if ($data['status'] == 1 && !$reply && $comment['show']\n && ($this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER'))\n && $this->getConf('usethreading')\n ) {\n $this->showButton($cid, $this->getLang('btn_reply'), 'reply', true);\n }\n\n // show edit, show/hide and delete button?\n if (($user == $INPUT->server->str('REMOTE_USER') && $user != '') || $this->helper->isDiscussionModerator()) {\n $this->showButton($cid, $lang['btn_secedit'], 'edit', true);\n $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));\n $this->showButton($cid, $label, 'toogle');\n $this->showButton($cid, $lang['btn_delete'], 'delete');\n }\n ptln('
      ', 6); // class=\"comment_buttons\"\n }\n ptln('
      ', 4); // class=\"hentry\"\n }\n\n /**\n * If requested by user, show comment form to write a reply\n *\n * @param string $cid current comment id\n * @param string $reply comment id on which the user requested a reply\n */\n protected function showReplyForm($cid, $reply)\n {\n if ($this->getConf('usethreading') && $reply == $cid) {\n ptln('
      ', 4);\n $this->showCommentForm('', 'add', $cid);\n ptln('
      ', 4); // class=\"comment_replies\"\n }\n }\n\n /**\n * Show the replies to the given comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible is marked as visible by reference\n */\n protected function showReplies($cid, &$data, $reply, &$isVisible)\n {\n $comment = $data['comments'][$cid];\n if (!count($comment['replies'])) {\n return;\n }\n ptln('
      getWidthStyle() . '>', 4);\n $isVisible = ($comment['show'] && $isVisible);\n foreach ($comment['replies'] as $rid) {\n $this->showCommentWithReplies($rid, $data, $cid, $reply, $isVisible);\n }\n ptln('
      ', 4);\n }\n\n /**\n * Is an avatar displayed?\n *\n * @return bool\n */\n protected function useAvatar()\n {\n if (is_null($this->useAvatar)) {\n $this->useAvatar = $this->getConf('useavatar')\n && ($this->avatar = $this->loadHelper('avatar', false));\n }\n return $this->useAvatar;\n }\n\n /**\n * Calculate width of indent\n *\n * @return string\n */\n protected function getWidthStyle()\n {\n global $lang;\n\n if (is_null($this->style)) {\n $side = $lang['direction'] === 'ltr' ? 'left' : 'right';\n\n if ($this->useAvatar()) {\n $this->style = ' style=\"margin-' . $side . ': ' . ($this->avatar->getConf('size') + 14) . 'px;\"';\n } else {\n $this->style = ' style=\"margin-' . $side . ': 20px;\"';\n }\n }\n return $this->style;\n }\n\n /**\n * Show the button which toggles between show/hide of the entire discussion section\n */\n protected function showDiscussionToggleButton()\n {\n ptln('
      ');\n ptln('getLang('toggle_display') . '\">');\n ptln('
      ');\n }\n\n /**\n * Outputs the comment form\n *\n * @param string $raw the existing comment text in case of edit\n * @param string $act action 'add' or 'save'\n * @param string|null $cid comment id to be responded to or null\n */\n protected function showCommentForm($raw, $act, $cid = null)\n {\n global $lang, $conf, $ID, $INPUT;\n\n // not for unregistered users when guest comments aren't allowed\n if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('allowguests')) {\n ?>\n
      \n getLang('noguests'); ?>\n
      \n str('text') if it's empty (for failed CAPTCHA check)\n if (!$raw && $INPUT->str('comment') == 'show') {\n $raw = $INPUT->str('text');\n }\n ?>\n\n
      \n
      \"\n accept-charset=\"\">\n
      \n \"/>\n \n \"/>\n \n \"/>\n server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionModerator())) {\n ?>\n \n
      \n \n
      \n
      \n \n
      \n getConf('urlfield')) {\n ?>\n
      \n \n
      \n getConf('addressfield')) {\n ?>\n
      \n \n
      \n getConf('adminimport') && ($this->helper->isDiscussionModerator())) {\n ?>\n
      \n \n
      \n \n \"/>\n \n
      \n getLang('entercomment');\n echo($this->getConf('wikisyntaxok') ? \"\" : \":\");\n if ($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?>\n\n \n getConf('wikisyntaxok')) { ?>\n
      \n \n
      \n \n
      \n str('comment') == 'add' && empty($INPUT->str('text'))) echo ' error' ?>\"\n name=\"text\" cols=\"80\" rows=\"10\" id=\"discussion__comment_text\" tabindex=\"5\">str('text'));\n }\n ?>\n
      \n\n loadHelper('captcha', false);\n if ($captcha && $captcha->isEnabled()) {\n echo $captcha->getHTML();\n }\n\n /** @var helper_plugin_recaptcha $recaptcha */\n $recaptcha = $this->loadHelper('recaptcha', false);\n if ($recaptcha && $recaptcha->isEnabled()) {\n echo $recaptcha->getHTML();\n }\n ?>\n\n \"\n title=\" [S]\" tabindex=\"7\"/>\n server->has('REMOTE_USER')\n || $INPUT->server->has('REMOTE_USER') && !$conf['subscribers'])\n && $this->getConf('subscribe')) { ?>\n \n \n \"\n title=\" [P]\"/>\n \n \" >\n \n\n
      \n
       
      \n
      \n \n
      \n \n
      \" method=\"get\" action=\"\">\n
      \n \"/>\n \n \"/>\n \"/>\n \" class=\"button\" title=\"\"/>\n
      \n
      \n \n *\n * @author Esther Brunner \n */\n protected function addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '')\n {\n global $conf, $INPUT;\n\n $changelog = $conf['metadir'] . '/_comments.changes';\n\n //use current time if none supplied\n if (!$date) {\n $date = time();\n }\n $remote = $INPUT->server->str('REMOTE_ADDR');\n $user = $INPUT->server->str('REMOTE_USER');\n\n $strip = [\"\\t\", \"\\n\"];\n $logline = [\n 'date' => $date,\n 'ip' => $remote,\n 'type' => str_replace($strip, '', $type),\n 'id' => $id,\n 'user' => $user,\n 'sum' => str_replace($strip, '', $summary),\n 'extra' => str_replace($strip, '', $extra)\n ];\n\n // add changelog line\n $logline = implode(\"\\t\", $logline) . \"\\n\";\n io_saveFile($changelog, $logline, true); //global changelog cache\n $this->trimRecentCommentsLog($changelog);\n\n // tell the indexer to re-index the page\n @unlink(metaFN($id, '.indexed'));\n }\n\n /**\n * Trims the recent comments cache to the last $conf['changes_days'] recent\n * changes or $conf['recent'] items, which ever is larger.\n * The trimming is only done once a day.\n *\n * @param string $changelog file path\n * @return bool\n * @author Ben Coburn \n *\n */\n protected function trimRecentCommentsLog($changelog)\n {\n global $conf;\n\n if (@file_exists($changelog)\n && (filectime($changelog) + 86400) < time()\n && !@file_exists($changelog . '_tmp')\n ) {\n\n io_lock($changelog);\n $lines = file($changelog);\n if (count($lines) < $conf['recent']) {\n // nothing to trim\n io_unlock($changelog);\n return true;\n }\n\n // presave tmp as 2nd lock\n io_saveFile($changelog . '_tmp', '');\n $trim_time = time() - $conf['recent_days'] * 86400;\n $out_lines = [];\n\n $num = count($lines);\n for ($i = 0; $i < $num; $i++) {\n $log = parseChangelogLine($lines[$i]);\n if ($log === false) continue; // discard junk\n if ($log['date'] < $trim_time) {\n $old_lines[$log['date'] . \".$i\"] = $lines[$i]; // keep old lines for now (append .$i to prevent key collisions)\n } else {\n $out_lines[$log['date'] . \".$i\"] = $lines[$i]; // definitely keep these lines\n }\n }\n\n // sort the final result, it shouldn't be necessary,\n // however the extra robustness in making the changelog cache self-correcting is worth it\n ksort($out_lines);\n $extra = $conf['recent'] - count($out_lines); // do we need extra lines do bring us up to minimum\n if ($extra > 0) {\n ksort($old_lines);\n $out_lines = array_merge(array_slice($old_lines, -$extra), $out_lines);\n }\n\n // save trimmed changelog\n io_saveFile($changelog . '_tmp', implode('', $out_lines));\n @unlink($changelog);\n if (!rename($changelog . '_tmp', $changelog)) {\n // rename failed so try another way...\n io_unlock($changelog);\n io_saveFile($changelog, implode('', $out_lines));\n @unlink($changelog . '_tmp');\n } else {\n io_unlock($changelog);\n }\n return true;\n }\n return true;\n }\n\n /**\n * Sends a notify mail on new comment\n *\n * @param array $comment data array of the new comment\n * @param array $subscribers data of the subscribers by reference\n *\n * @author Andreas Gohr \n * @author Esther Brunner \n */\n protected function notify($comment, &$subscribers)\n {\n global $conf, $ID, $INPUT, $auth;\n\n $notify_text = io_readfile($this->localfn('subscribermail'));\n $confirm_text = io_readfile($this->localfn('confirmsubscribe'));\n $subject_notify = '[' . $conf['title'] . '] ' . $this->getLang('mail_newcomment');\n $subject_subscribe = '[' . $conf['title'] . '] ' . $this->getLang('subscribe');\n\n $mailer = new Mailer();\n if (!$INPUT->server->has('REMOTE_USER')) {\n $mailer->from($conf['mailfromnobody']);\n }\n\n $replace = [\n 'PAGE' => $ID,\n 'TITLE' => $conf['title'],\n 'DATE' => dformat($comment['date']['created'], $conf['dformat']),\n 'NAME' => $comment['user']['name'],\n 'TEXT' => $comment['raw'],\n 'COMMENTURL' => wl($ID, '', true) . '#comment_' . $comment['cid'],\n 'UNSUBSCRIBE' => wl($ID, 'do=subscribe', true, '&'),\n 'DOKUWIKIURL' => DOKU_URL\n ];\n\n $confirm_replace = [\n 'PAGE' => $ID,\n 'TITLE' => $conf['title'],\n 'DOKUWIKIURL' => DOKU_URL\n ];\n\n\n $mailer->subject($subject_notify);\n $mailer->setBody($notify_text, $replace);\n\n // send mail to notify address\n if ($conf['notify']) {\n $mailer->bcc($conf['notify']);\n $mailer->send();\n }\n\n // send email to moderators\n if ($this->getConf('moderatorsnotify')) {\n $moderatorgrpsString = trim($this->getConf('moderatorgroups'));\n if (!empty($moderatorgrpsString)) {\n // create a clean mods list\n $moderatorgroups = explode(',', $moderatorgrpsString);\n $moderatorgroups = array_map('trim', $moderatorgroups);\n $moderatorgroups = array_unique($moderatorgroups);\n $moderatorgroups = array_filter($moderatorgroups);\n // search for moderators users\n foreach ($moderatorgroups as $moderatorgroup) {\n if (!$auth->isCaseSensitive()) {\n $moderatorgroup = PhpString::strtolower($moderatorgroup);\n }\n // create a clean mailing list\n $bccs = [];\n if ($moderatorgroup[0] == '@') {\n foreach ($auth->retrieveUsers(0, 0, ['grps' => $auth->cleanGroup(substr($moderatorgroup, 1))]) as $user) {\n if (!empty($user['mail'])) {\n $bccs[] = $user['mail'];\n }\n }\n } else {\n //it is an user\n $userdata = $auth->getUserData($auth->cleanUser($moderatorgroup));\n if (!empty($userdata['mail'])) {\n $bccs[] = $userdata['mail'];\n }\n }\n $bccs = array_unique($bccs);\n // notify the users\n $mailer->bcc(implode(',', $bccs));\n $mailer->send();\n }\n }\n }\n\n // notify page subscribers\n if (actionOK('subscribe')) {\n $data = ['id' => $ID, 'addresslist' => '', 'self' => false];\n //FIXME default callback, needed to mentioned it again?\n Event::createAndTrigger(\n 'COMMON_NOTIFY_ADDRESSLIST', $data,\n [new SubscriberManager(), 'notifyAddresses']\n );\n\n $to = $data['addresslist'];\n if (!empty($to)) {\n $mailer->bcc($to);\n $mailer->send();\n }\n }\n\n // notify comment subscribers\n if (!empty($subscribers)) {\n\n foreach ($subscribers as $mail => $data) {\n $mailer->bcc($mail);\n if ($data['active']) {\n $replace['UNSUBSCRIBE'] = wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&');\n\n $mailer->subject($subject_notify);\n $mailer->setBody($notify_text, $replace);\n $mailer->send();\n } elseif (!$data['confirmsent']) {\n $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&');\n\n $mailer->subject($subject_subscribe);\n $mailer->setBody($confirm_text, $confirm_replace);\n $mailer->send();\n $subscribers[$mail]['confirmsent'] = true;\n }\n }\n }\n }\n\n /**\n * Counts the number of visible comments\n *\n * @param array $data array with all comments\n * @return int\n */\n protected function countVisibleComments($data)\n {\n $number = 0;\n foreach ($data['comments'] as $comment) {\n if ($comment['parent']) continue;\n if (!$comment['show']) continue;\n\n $number++;\n $rids = $comment['replies'];\n if (count($rids)) {\n $number = $number + $this->countVisibleReplies($data, $rids);\n }\n }\n return $number;\n }\n\n /**\n * Count visible replies on the comments\n *\n * @param array $data\n * @param array $rids\n * @return int counted replies\n */\n protected function countVisibleReplies(&$data, $rids)\n {\n $number = 0;\n foreach ($rids as $rid) {\n if (!isset($data['comments'][$rid])) continue; // reply was removed\n if (!$data['comments'][$rid]['show']) continue;\n\n $number++;\n $rids = $data['comments'][$rid]['replies'];\n if (count($rids)) {\n $number = $number + $this->countVisibleReplies($data, $rids);\n }\n }\n return $number;\n }\n\n /**\n * Renders the raw comment (wiki)text to html\n *\n * @param string $raw comment text\n * @return null|string\n */\n protected function renderComment($raw)\n {\n if ($this->getConf('wikisyntaxok')) {\n // Note the warning for render_text:\n // \"very ineffecient for small pieces of data - try not to use\"\n // in dokuwiki/inc/plugin.php\n $xhtml = $this->render_text($raw);\n } else { // wiki syntax not allowed -> just encode special chars\n $xhtml = hsc(trim($raw));\n $xhtml = str_replace(\"\\n\", '
      ', $xhtml);\n }\n return $xhtml;\n }\n\n /**\n * Finds out whether there is a discussion section for the current page\n *\n * @param string $title set to title from metadata or empty string\n * @return bool discussion section is shown?\n */\n protected function hasDiscussion(&$title)\n {\n global $ID;\n\n $file = metaFN($ID, '.comments');\n\n if (!@file_exists($file)) {\n if ($this->isDiscussionEnabled()) {\n return true;\n } else {\n return false;\n }\n }\n\n $data = unserialize(io_readFile($file, false));\n\n $title = $data['title'] ?? '';\n\n $num = $data['number'] ?? 0;\n if (!$data['status'] || ($data['status'] == 2 && $num == 0)) {\n //disabled, or closed and no comments\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Creates a new thread page\n *\n * @return string\n */\n protected function newThread()\n {\n global $ID, $INFO, $INPUT;\n\n $ns = cleanID($INPUT->str('ns'));\n $title = str_replace(':', '', $INPUT->str('title'));\n $back = $ID;\n $ID = ($ns ? $ns . ':' : '') . cleanID($title);\n $INFO = pageinfo();\n\n // check if we are allowed to create this file\n if ($INFO['perm'] >= AUTH_CREATE) {\n\n //check if locked by anyone - if not lock for my self\n if ($INFO['locked']) {\n return 'locked';\n } else {\n lock($ID);\n }\n\n // prepare the new thread file with default stuff\n if (!@file_exists($INFO['filepath'])) {\n global $TEXT;\n\n $TEXT = pageTemplate(($ns ? $ns . ':' : '') . $title);\n if (!$TEXT) {\n $data = ['id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back];\n $TEXT = $this->pageTemplate($data);\n }\n return 'preview';\n } else {\n return 'edit';\n }\n } else {\n return 'show';\n }\n }\n\n /**\n * Adapted version of pageTemplate() function\n *\n * @param array $data\n * @return string\n */\n protected function pageTemplate($data)\n {\n global $conf, $INFO, $INPUT;\n\n $id = $data['id'];\n $user = $INPUT->server->str('REMOTE_USER');\n $tpl = io_readFile(DOKU_PLUGIN . 'discussion/_template.txt');\n\n // standard replacements\n $replace = [\n '@NS@' => $data['ns'],\n '@PAGE@' => strtr(noNS($id), '_', ' '),\n '@USER@' => $user,\n '@NAME@' => $INFO['userinfo']['name'],\n '@MAIL@' => $INFO['userinfo']['mail'],\n '@DATE@' => dformat(time(), $conf['dformat']),\n ];\n\n // additional replacements\n $replace['@BACK@'] = $data['back'];\n $replace['@TITLE@'] = $data['title'];\n\n // avatar if useavatar and avatar plugin available\n if ($this->getConf('useavatar') && !plugin_isdisabled('avatar')) {\n $replace['@AVATAR@'] = '{{avatar>' . $user . ' }} ';\n } else {\n $replace['@AVATAR@'] = '';\n }\n\n // tag if tag plugin is available\n if (!plugin_isdisabled('tag')) {\n $replace['@TAG@'] = \"\\n\\n{{tag>}}\";\n } else {\n $replace['@TAG@'] = '';\n }\n\n // perform the replacements in tpl\n return str_replace(array_keys($replace), array_values($replace), $tpl);\n }\n\n /**\n * Checks if the CAPTCHA string submitted is valid, modifies action if needed\n */\n protected function captchaCheck()\n {\n global $INPUT;\n /** @var helper_plugin_captcha $captcha */\n if (!$captcha = $this->loadHelper('captcha', false)) {\n // CAPTCHA is disabled or not available\n return;\n }\n\n if ($captcha->isEnabled() && !$captcha->check()) {\n if ($INPUT->str('comment') == 'save') {\n $INPUT->set('comment', 'edit');\n } elseif ($INPUT->str('comment') == 'add') {\n $INPUT->set('comment', 'show');\n }\n }\n }\n\n /**\n * checks if the submitted reCAPTCHA string is valid, modifies action if needed\n *\n * @author Adrian Schlegel \n */\n protected function recaptchaCheck()\n {\n global $INPUT;\n /** @var helper_plugin_recaptcha $recaptcha */\n if (!$recaptcha = plugin_load('helper', 'recaptcha'))\n return; // reCAPTCHA is disabled or not available\n\n // do nothing if logged in user and no reCAPTCHA required\n if (!$recaptcha->getConf('forusers') && $INPUT->server->has('REMOTE_USER')) return;\n\n $response = $recaptcha->check();\n if (!$response->is_valid) {\n msg($recaptcha->getLang('testfailed'), -1);\n if ($INPUT->str('comment') == 'save') {\n $INPUT->str('comment', 'edit');\n } elseif ($INPUT->str('comment') == 'add') {\n $INPUT->str('comment', 'show');\n }\n }\n }\n\n /**\n * Add discussion plugin version to the indexer version\n * This means that all pages will be indexed again in order to add the comments\n * to the index whenever there has been a change that concerns the index content.\n *\n * @param Doku_Event $event\n */\n public function addIndexVersion(Doku_Event $event)\n {\n $event->data['discussion'] = '0.1';\n }\n\n /**\n * Adds the comments to the index\n *\n * @param Doku_Event $event\n * @param array $param with\n * 'id' => string 'page'/'id' for respectively INDEXER_PAGE_ADD and FULLTEXT_SNIPPET_CREATE event\n * 'text' => string 'body'/'text'\n */\n public function addCommentsToIndex(Doku_Event $event, $param)\n {\n // get .comments meta file name\n $file = metaFN($event->data[$param['id']], '.comments');\n\n if (!@file_exists($file)) return;\n $data = unserialize(io_readFile($file, false));\n\n // comments are turned off or no comments available to index\n if (!$data['status'] || $data['number'] == 0) return;\n\n // now add the comments\n if (isset($data['comments'])) {\n foreach ($data['comments'] as $key => $value) {\n $event->data[$param['text']] .= DOKU_LF . $this->addCommentWords($key, $data);\n }\n }\n }\n\n /**\n * Checks if the phrase occurs in the comments and return event result true if matching\n *\n * @param Doku_Event $event\n */\n public function fulltextPhraseMatchInComments(Doku_Event $event)\n {\n if ($event->result === true) return;\n\n // get .comments meta file name\n $file = metaFN($event->data['id'], '.comments');\n\n if (!@file_exists($file)) return;\n $data = unserialize(io_readFile($file, false));\n\n // comments are turned off or no comments available to match\n if (!$data['status'] || $data['number'] == 0) return;\n\n $matched = false;\n\n // now add the comments\n if (isset($data['comments'])) {\n foreach ($data['comments'] as $cid => $value) {\n $matched = $this->phraseMatchInComment($event->data['phrase'], $cid, $data);\n if ($matched) break;\n }\n }\n\n if ($matched) {\n $event->result = true;\n }\n }\n\n /**\n * Match the phrase in the comment and its replies\n *\n * @param string $phrase phrase to search\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent cid of parent\n * @return bool if match true, otherwise false\n */\n protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '')\n {\n if (!isset($data['comments'][$cid])) return false; // comment was removed\n\n $comment = $data['comments'][$cid];\n\n if (!is_array($comment)) return false; // corrupt datatype\n if ($comment['parent'] != $parent) return false; // reply to an other comment\n if (!$comment['show']) return false; // hidden comment\n\n $text = PhpString::strtolower($comment['raw']);\n if (strpos($text, $phrase) !== false) {\n return true;\n }\n\n if (is_array($comment['replies'])) { // and the replies\n foreach ($comment['replies'] as $rid) {\n if ($this->phraseMatchInComment($phrase, $rid, $data, $cid)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Saves the current comment status and title from metadata into the .comments file\n *\n * @param Doku_Event $event\n */\n public function updateCommentStatusFromMetadata(Doku_Event $event)\n {\n global $ID;\n\n $meta = $event->data['current'];\n\n $file = metaFN($ID, '.comments');\n $configurationStatus = ($this->isDiscussionEnabled() ? 1 : 0); // 0=off, 1=enabled\n $title = null;\n if (isset($meta['plugin_discussion'])) {\n $status = (int) $meta['plugin_discussion']['status']; // 0=off, 1=enabled or 2=closed\n $title = $meta['plugin_discussion']['title'];\n\n // do we have metadata that differs from general config?\n $saveNeededFromMetadata = $configurationStatus !== $status || ($status > 0 && $title);\n } else {\n $status = $configurationStatus;\n $saveNeededFromMetadata = false;\n }\n\n // if .comment file exists always update it with latest status\n if ($saveNeededFromMetadata || file_exists($file)) {\n\n $data = [];\n if (@file_exists($file)) {\n $data = unserialize(io_readFile($file, false));\n }\n\n if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) {\n //title can be only set from metadata\n $data['title'] = $title;\n $data['status'] = $status;\n if (!isset($data['number'])) {\n $data['number'] = 0;\n }\n io_saveFile($file, serialize($data));\n }\n }\n }\n\n /**\n * Return words of a given comment and its replies, suitable to be added to the index\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent cid of parent\n * @return string\n */\n protected function addCommentWords($cid, &$data, $parent = '')\n {\n\n if (!isset($data['comments'][$cid])) return ''; // comment was removed\n\n $comment = $data['comments'][$cid];\n\n if (!is_array($comment)) return ''; // corrupt datatype\n if ($comment['parent'] != $parent) return ''; // reply to an other comment\n if (!$comment['show']) return ''; // hidden comment\n\n $text = $comment['raw']; // we only add the raw comment text\n if (is_array($comment['replies'])) { // and the replies\n foreach ($comment['replies'] as $rid) {\n $text .= $this->addCommentWords($rid, $data, $cid);\n }\n }\n return ' ' . $text;\n }\n\n /**\n * Only allow http(s) URLs and append http:// to URLs if needed\n *\n * @param string $url\n * @return string\n */\n protected function checkURL($url)\n {\n if (preg_match(\"#^http://|^https://#\", $url)) {\n return hsc($url);\n } elseif (substr($url, 0, 4) == 'www.') {\n return hsc('https://' . $url);\n } else {\n return '';\n }\n }\n\n /**\n * Sort threads\n *\n * @param array $a array with comment properties\n * @param array $b array with comment properties\n * @return int\n */\n function sortThreadsOnCreation($a, $b)\n {\n if (is_array($a['date'])) {\n // new format\n $createdA = $a['date']['created'];\n } else {\n // old format\n $createdA = $a['date'];\n }\n\n if (is_array($b['date'])) {\n // new format\n $createdB = $b['date']['created'];\n } else {\n // old format\n $createdB = $b['date'];\n }\n\n if ($createdA == $createdB) {\n return 0;\n } else {\n return ($createdA < $createdB) ? -1 : 1;\n }\n }\n\n}\n\n\n", "file_after": "\n */\n\nuse dokuwiki\\Extension\\Event;\nuse dokuwiki\\Subscriptions\\SubscriberManager;\nuse dokuwiki\\Utf8\\PhpString;\n\n/**\n * Class action_plugin_discussion\n *\n * Data format of file metadir/.comments:\n * array = [\n * 'status' => int whether comments are 0=disabled/1=open/2=closed,\n * 'number' => int number of visible comments,\n * 'title' => string|null alternative title for discussion section\n * 'comments' => [\n * ''=> [\n * 'cid' => string comment id - long random string\n * 'raw' => string comment text,\n * 'xhtml' => string rendered html,\n * 'parent' => null|string null or empty string at highest level, otherwise comment id of parent\n * 'replies' => string[] array with comment ids\n * 'user' => [\n * 'id' => string,\n * 'name' => string,\n * 'mail' => string,\n * 'address' => string,\n * 'url' => string\n * ],\n * 'date' => [\n * 'created' => int timestamp,\n * 'modified' => int (not defined if not modified)\n * ],\n * 'show' => bool, whether shown (still be moderated, or hidden by moderator or user self)\n * ],\n * ...\n * ]\n * 'subscribers' => [\n * '' => [\n * 'hash' => string unique token,\n * 'active' => bool, true if confirmed\n * 'confirmsent' => bool, true if confirmation mail is sent\n * ],\n * ...\n * ]\n */\nclass action_plugin_discussion extends DokuWiki_Action_Plugin\n{\n\n /** @var helper_plugin_avatar */\n protected $avatar = null;\n /** @var null|string */\n protected $style = null;\n /** @var null|bool */\n protected $useAvatar = null;\n /** @var helper_plugin_discussion */\n protected $helper = null;\n\n /**\n * load helper\n */\n public function __construct()\n {\n $this->helper = plugin_load('helper', 'discussion');\n }\n\n /**\n * Register the handlers\n *\n * @param Doku_Event_Handler $controller DokuWiki's event controller object.\n */\n public function register(Doku_Event_Handler $controller)\n {\n $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleCommentActions');\n $controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, 'renderCommentsSection');\n $controller->register_hook('INDEXER_PAGE_ADD', 'AFTER', $this, 'addCommentsToIndex', ['id' => 'page', 'text' => 'body']);\n $controller->register_hook('FULLTEXT_SNIPPET_CREATE', 'BEFORE', $this, 'addCommentsToIndex', ['id' => 'id', 'text' => 'text']);\n $controller->register_hook('INDEXER_VERSION_GET', 'BEFORE', $this, 'addIndexVersion', []);\n $controller->register_hook('FULLTEXT_PHRASE_MATCH', 'AFTER', $this, 'fulltextPhraseMatchInComments', []);\n $controller->register_hook('PARSER_METADATA_RENDER', 'AFTER', $this, 'updateCommentStatusFromMetadata', []);\n $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'addToolbarToCommentfield', []);\n $controller->register_hook('TOOLBAR_DEFINE', 'AFTER', $this, 'modifyToolbar', []);\n $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajaxPreviewComments', []);\n $controller->register_hook('TPL_TOC_RENDER', 'BEFORE', $this, 'addDiscussionToTOC', []);\n }\n\n /**\n * Preview Comments\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function ajaxPreviewComments(Doku_Event $event)\n {\n global $INPUT;\n if ($event->data != 'discussion_preview') return;\n\n $event->preventDefault();\n $event->stopPropagation();\n print p_locale_xhtml('preview');\n print '
      ';\n if (!$INPUT->server->str('REMOTE_USER') && !$this->getConf('allowguests')) {\n print p_locale_xhtml('denied');\n } else {\n print $this->renderComment($INPUT->post->str('comment'));\n }\n print '
      ';\n }\n\n /**\n * Adds a TOC item if a discussion exists\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function addDiscussionToTOC(Doku_Event $event)\n {\n global $ACT;\n if ($this->hasDiscussion($title) && $event->data && $ACT != 'admin') {\n $tocitem = [\n 'hid' => 'discussion__section',\n 'title' => $title ?: $this->getLang('discussion'),\n 'type' => 'ul',\n 'level' => 1\n ];\n\n $event->data[] = $tocitem;\n }\n }\n\n /**\n * Modify Toolbar for use with discussion plugin\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function modifyToolbar(Doku_Event $event)\n {\n global $ACT;\n if ($ACT != 'show') return;\n\n if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) {\n $toolbar = [];\n foreach ($event->data as $btn) {\n if ($btn['type'] == 'mediapopup') continue;\n if ($btn['type'] == 'signature') continue;\n if ($btn['type'] == 'linkwiz') continue;\n if ($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin\n //FIXME does nothing. Checks for '=' on toplevel, but today it are special buttons and a picker with subarray\n if (isset($btn['open']) && preg_match(\"/=+?/\", $btn['open'])) continue;\n\n $toolbar[] = $btn;\n }\n $event->data = $toolbar;\n }\n }\n\n /**\n * Dirty workaround to add a toolbar to the discussion plugin\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function addToolbarToCommentfield(Doku_Event $event)\n {\n global $ACT;\n global $ID;\n if ($ACT != 'show') return;\n\n if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) {\n // FIXME ugly workaround, replace this once DW the toolbar code is more flexible\n @require_once(DOKU_INC . 'inc/toolbar.php');\n ob_start();\n print 'NS = \"' . getNS($ID) . '\";'; // we have to define NS, otherwise we get get JS errors\n toolbar_JSdefines('toolbar');\n $script = ob_get_clean();\n $event->data['script'][] = ['type' => 'text/javascript', 'charset' => \"utf-8\", '_data' => $script];\n }\n }\n\n /**\n * Handles comment actions, dispatches data processing routines\n *\n * @param Doku_Event $event\n */\n public function handleCommentActions(Doku_Event $event)\n {\n global $ID, $INFO, $lang, $INPUT;\n\n // handle newthread ACTs\n if ($event->data == 'newthread') {\n // we can handle it -> prevent others\n $event->data = $this->newThread();\n }\n\n // enable captchas\n if (in_array($INPUT->str('comment'), ['add', 'save'])) {\n $this->captchaCheck();\n $this->recaptchaCheck();\n }\n\n // if we are not in show mode or someone wants to unsubscribe, that was all for now\n if ($event->data != 'show'\n && $event->data != 'discussion_unsubscribe'\n && $event->data != 'discussion_confirmsubscribe') {\n return;\n }\n\n if ($event->data == 'discussion_unsubscribe' or $event->data == 'discussion_confirmsubscribe') {\n if ($INPUT->has('hash')) {\n $file = metaFN($ID, '.comments');\n $data = unserialize(io_readFile($file));\n $matchedMail = '';\n foreach ($data['subscribers'] as $mail => $info) {\n // convert old style subscribers just in case\n if (!is_array($info)) {\n $hash = $data['subscribers'][$mail];\n $data['subscribers'][$mail]['hash'] = $hash;\n $data['subscribers'][$mail]['active'] = true;\n $data['subscribers'][$mail]['confirmsent'] = true;\n }\n\n if ($data['subscribers'][$mail]['hash'] == $INPUT->str('hash')) {\n $matchedMail = $mail;\n }\n }\n\n if ($matchedMail != '') {\n if ($event->data == 'discussion_unsubscribe') {\n unset($data['subscribers'][$matchedMail]);\n msg(sprintf($lang['subscr_unsubscribe_success'], $matchedMail, $ID), 1);\n } else { //$event->data == 'discussion_confirmsubscribe'\n $data['subscribers'][$matchedMail]['active'] = true;\n msg(sprintf($lang['subscr_subscribe_success'], $matchedMail, $ID), 1);\n }\n io_saveFile($file, serialize($data));\n $event->data = 'show';\n }\n\n }\n return;\n }\n\n // do the data processing for comments\n $cid = $INPUT->str('cid');\n switch ($INPUT->str('comment')) {\n case 'add':\n if (empty($INPUT->str('text'))) return; // don't add empty comments\n\n if ($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) {\n $comment['user']['id'] = $INPUT->server->str('REMOTE_USER');\n $comment['user']['name'] = $INFO['userinfo']['name'];\n $comment['user']['mail'] = $INFO['userinfo']['mail'];\n } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionModerator())\n || !$INPUT->server->has('REMOTE_USER')) {\n // don't add anonymous comments\n if (empty($INPUT->str('name')) or empty($INPUT->str('mail'))) {\n return;\n }\n\n if (!mail_isvalid($INPUT->str('mail'))) {\n msg($lang['regbadmail'], -1);\n return;\n } else {\n $comment['user']['id'] = ''; //prevent overlap with loggedin users, before: 'test'\n $comment['user']['name'] = hsc($INPUT->str('name'));\n $comment['user']['mail'] = hsc($INPUT->str('mail'));\n }\n }\n $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($INPUT->str('address')) : '';\n $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->checkURL($INPUT->str('url')) : '';\n $comment['subscribe'] = ($this->getConf('subscribe')) ? $INPUT->has('subscribe') : '';\n $comment['date'] = ['created' => $INPUT->str('date')];\n $comment['raw'] = cleanText($INPUT->str('text'));\n $reply = $INPUT->str('reply');\n if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) {\n $comment['show'] = false;\n } else {\n $comment['show'] = true;\n }\n $this->add($comment, $reply);\n break;\n\n case 'save':\n $raw = cleanText($INPUT->str('text'));\n $this->save([$cid], $raw);\n break;\n\n case 'delete':\n $this->save([$cid], '');\n break;\n\n case 'toogle':\n $this->save([$cid], '', 'toogle');\n break;\n }\n }\n\n /**\n * Main function; dispatches the visual comment actions\n *\n * @param Doku_Event $event\n */\n public function renderCommentsSection(Doku_Event $event)\n {\n global $INPUT;\n if ($event->data != 'show') return; // nothing to do for us\n\n $cid = $INPUT->str('cid');\n\n if (!$cid) {\n $cid = $INPUT->str('reply');\n }\n\n switch ($INPUT->str('comment')) {\n case 'edit':\n $this->showDiscussionSection(null, $cid);\n break;\n default: //'reply' or no action specified\n $this->showDiscussionSection($cid);\n break;\n }\n }\n\n /**\n * Redirects browser to given comment anchor\n *\n * @param string $cid comment id\n */\n protected function redirect($cid)\n {\n global $ID;\n global $ACT;\n\n if ($ACT !== 'show') return;\n\n if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) {\n msg($this->getLang('moderation'), 1);\n @session_start();\n global $MSG;\n $_SESSION[DOKU_COOKIE]['msg'] = $MSG;\n session_write_close();\n $url = wl($ID);\n } else {\n $url = wl($ID) . '#comment_' . $cid;\n }\n\n if (function_exists('send_redirect')) {\n send_redirect($url);\n } else {\n header('Location: ' . $url);\n }\n exit();\n }\n\n /**\n * Checks config settings to enable/disable discussions\n *\n * @return bool true if enabled\n */\n public function isDiscussionEnabled()\n {\n global $ID;\n\n if ($this->getConf('excluded_ns') == '') {\n $isNamespaceExcluded = false;\n } else {\n $ns = getNS($ID); // $INFO['namespace'] is not yet available, if used in update_comment_status()\n $isNamespaceExcluded = preg_match($this->getConf('excluded_ns'), $ns);\n }\n\n if ($this->getConf('automatic')) {\n if ($isNamespaceExcluded) {\n return false;\n } else {\n return true;\n }\n } else {\n if ($isNamespaceExcluded) {\n return true;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Shows all comments of the current page, if no reply or edit requested, then comment form is shown on the end\n *\n * @param null|string $reply comment id on which the user requested a reply\n * @param null|string $edit comment id which the user requested for editing\n */\n protected function showDiscussionSection($reply = null, $edit = null)\n {\n global $ID, $INFO, $INPUT;\n\n // get .comments meta file name\n $file = metaFN($ID, '.comments');\n\n if (!$INFO['exists']) return;\n if (!@file_exists($file) && !$this->isDiscussionEnabled()) return;\n if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('showguests')) return;\n\n // load data\n $data = [];\n if (@file_exists($file)) {\n $data = unserialize(io_readFile($file, false));\n // comments are turned off\n if (!$data['status']) {\n return;\n }\n } elseif (!@file_exists($file) && $this->isDiscussionEnabled()) {\n // set status to show the comment form\n $data['status'] = 1;\n $data['number'] = 0;\n $data['title'] = null;\n }\n\n // show discussion wrapper only on certain circumstances\n if (empty($data['comments']) || !is_array($data['comments'])) {\n $cnt = 0;\n $cids = [];\n } else {\n $cnt = count($data['comments']);\n $cids = array_keys($data['comments']);\n }\n\n $show = false;\n if ($cnt > 1 || ($cnt == 1 && $data['comments'][$cids[0]]['show'] == 1)\n || $this->getConf('allowguests')\n || $INPUT->server->has('REMOTE_USER')) {\n $show = true;\n // section title\n $title = (!empty($data['title']) ? hsc($data['title']) : $this->getLang('discussion'));\n ptln('
      '); // the id value is used for visibility toggling the section\n ptln('

      ', 2);\n ptln($title, 4);\n ptln('

      ', 2);\n ptln('
      ', 2);\n }\n\n // now display the comments\n if (isset($data['comments'])) {\n if (!$this->getConf('usethreading')) {\n $data['comments'] = $this->flattenThreads($data['comments']);\n uasort($data['comments'], [$this, 'sortThreadsOnCreation']);\n }\n if ($this->getConf('newestfirst')) {\n $data['comments'] = array_reverse($data['comments']);\n }\n foreach ($data['comments'] as $cid => $value) {\n if ($cid == $edit) { // edit form\n $this->showCommentForm($value['raw'], 'save', $edit);\n } else {\n $this->showCommentWithReplies($cid, $data, '', $reply);\n }\n }\n }\n\n // comment form shown on the end, if no comment form of $reply or $edit is requested before\n if ($data['status'] == 1 && (!$reply || !$this->getConf('usethreading')) && !$edit) {\n $this->showCommentForm('', 'add');\n }\n\n if ($show) {\n ptln('
      ', 2); // level2 hfeed\n ptln('
      '); // comment_wrapper\n }\n\n // check for toggle print configuration\n if ($this->getConf('visibilityButton')) {\n // print the hide/show discussion section button\n $this->showDiscussionToggleButton();\n }\n }\n\n /**\n * Remove the parent-child relation, such that the comment structure becomes flat\n *\n * @param array $comments array with all comments\n * @param null|array $cids comment ids of replies, which should be flatten\n * @return array returned array with flattened comment structure\n */\n protected function flattenThreads($comments, $cids = null)\n {\n if (is_null($cids)) {\n $cids = array_keys($comments);\n }\n\n foreach ($cids as $cid) {\n if (!empty($comments[$cid]['replies'])) {\n $rids = $comments[$cid]['replies'];\n $comments = $this->flattenThreads($comments, $rids);\n $comments[$cid]['replies'] = [];\n }\n $comments[$cid]['parent'] = '';\n }\n return $comments;\n }\n\n /**\n * Adds a new comment and then displays all comments\n *\n * @param array $comment with\n * 'raw' => string comment text,\n * 'user' => [\n * 'id' => string,\n * 'name' => string,\n * 'mail' => string\n * ],\n * 'date' => [\n * 'created' => int timestamp\n * ]\n * 'show' => bool\n * 'subscribe' => bool\n * @param string $parent comment id of parent\n * @return bool\n */\n protected function add($comment, $parent)\n {\n global $ID, $TEXT, $INPUT;\n\n $originalTxt = $TEXT; // set $TEXT to comment text for wordblock check\n $TEXT = $comment['raw'];\n\n // spamcheck against the DokuWiki blacklist\n if (checkwordblock()) {\n msg($this->getLang('wordblock'), -1);\n return false;\n }\n\n if (!$this->getConf('allowguests')\n && $comment['user']['id'] != $INPUT->server->str('REMOTE_USER')\n ) {\n return false; // guest comments not allowed\n }\n\n $TEXT = $originalTxt; // restore global $TEXT\n\n // get discussion meta file name\n $file = metaFN($ID, '.comments');\n\n // create comments file if it doesn't exist yet\n if (!@file_exists($file)) {\n $data = [\n 'status' => 1,\n 'number' => 0,\n 'title' => null\n ];\n io_saveFile($file, serialize($data));\n } else {\n $data = unserialize(io_readFile($file, false));\n // comments off or closed\n if ($data['status'] != 1) {\n return false;\n }\n }\n\n if ($comment['date']['created']) {\n $date = strtotime($comment['date']['created']);\n } else {\n $date = time();\n }\n\n if ($date == -1) {\n $date = time();\n }\n\n $cid = md5($comment['user']['id'] . $date); // create a unique id\n\n if (!isset($data['comments'][$parent]) || !is_array($data['comments'][$parent])) {\n $parent = null; // invalid parent comment\n }\n\n // render the comment\n $xhtml = $this->renderComment($comment['raw']);\n\n // fill in the new comment\n $data['comments'][$cid] = [\n 'user' => $comment['user'],\n 'date' => ['created' => $date],\n 'raw' => $comment['raw'],\n 'xhtml' => $xhtml,\n 'parent' => $parent,\n 'replies' => [],\n 'show' => $comment['show']\n ];\n\n if ($comment['subscribe']) {\n $mail = $comment['user']['mail'];\n if (isset($data['subscribers'])) {\n if (!$data['subscribers'][$mail]) {\n $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());\n $data['subscribers'][$mail]['active'] = false;\n $data['subscribers'][$mail]['confirmsent'] = false;\n } else {\n // convert old style subscribers and set them active\n if (!is_array($data['subscribers'][$mail])) {\n $hash = $data['subscribers'][$mail];\n $data['subscribers'][$mail]['hash'] = $hash;\n $data['subscribers'][$mail]['active'] = true;\n $data['subscribers'][$mail]['confirmsent'] = true;\n }\n }\n } else {\n $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());\n $data['subscribers'][$mail]['active'] = false;\n $data['subscribers'][$mail]['confirmsent'] = false;\n }\n }\n\n // update parent comment\n if ($parent) {\n $data['comments'][$parent]['replies'][] = $cid;\n }\n\n // update the number of comments\n $data['number']++;\n\n // notify subscribers of the page\n $data['comments'][$cid]['cid'] = $cid;\n $this->notify($data['comments'][$cid], $data['subscribers']);\n\n // save the comment metadata file\n io_saveFile($file, serialize($data));\n $this->addLogEntry($date, $ID, 'cc', '', $cid);\n\n $this->redirect($cid);\n return true;\n }\n\n /**\n * Saves the comment with the given ID and then displays all comments\n *\n * @param array|string $cids array with comment ids to save, or a single string comment id\n * @param string $raw if empty comment is deleted, otherwise edited text is stored (note: storing is per one cid!)\n * @param string|null $act 'toogle', 'show', 'hide', null. If null, it depends on $raw\n * @return bool succeed?\n */\n public function save($cids, $raw, $act = null)\n {\n global $ID, $INPUT;\n\n if (empty($cids)) return false; // do nothing if we get no comment id\n\n if ($raw) {\n global $TEXT;\n\n $otxt = $TEXT; // set $TEXT to comment text for wordblock check\n $TEXT = $raw;\n\n // spamcheck against the DokuWiki blacklist\n if (checkwordblock()) {\n msg($this->getLang('wordblock'), -1);\n return false;\n }\n\n $TEXT = $otxt; // restore global $TEXT\n }\n\n // get discussion meta file name\n $file = metaFN($ID, '.comments');\n $data = unserialize(io_readFile($file, false));\n\n if (!is_array($cids)) {\n $cids = [$cids];\n }\n foreach ($cids as $cid) {\n\n if (is_array($data['comments'][$cid]['user'])) {\n $user = $data['comments'][$cid]['user']['id'];\n $convert = false;\n } else {\n $user = $data['comments'][$cid]['user'];\n $convert = true;\n }\n\n // someone else was trying to edit our comment -> abort\n if ($user != $INPUT->server->str('REMOTE_USER') && !$this->helper->isDiscussionModerator()) {\n return false;\n }\n\n $date = time();\n\n // need to convert to new format?\n if ($convert) {\n $data['comments'][$cid]['user'] = [\n 'id' => $user,\n 'name' => $data['comments'][$cid]['name'],\n 'mail' => $data['comments'][$cid]['mail'],\n 'url' => $data['comments'][$cid]['url'],\n 'address' => $data['comments'][$cid]['address'],\n ];\n $data['comments'][$cid]['date'] = [\n 'created' => $data['comments'][$cid]['date']\n ];\n }\n\n if ($act == 'toogle') { // toogle visibility\n $now = $data['comments'][$cid]['show'];\n $data['comments'][$cid]['show'] = !$now;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');\n\n } elseif ($act == 'show') { // show comment\n $data['comments'][$cid]['show'] = true;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'sc'; // show comment\n\n } elseif ($act == 'hide') { // hide comment\n $data['comments'][$cid]['show'] = false;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'hc'; // hide comment\n\n } elseif (!$raw) { // remove the comment\n $data['comments'] = $this->removeComment($cid, $data['comments']);\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'dc'; // delete comment\n\n } else { // save changed comment\n $xhtml = $this->renderComment($raw);\n\n // now change the comment's content\n $data['comments'][$cid]['date']['modified'] = $date;\n $data['comments'][$cid]['raw'] = $raw;\n $data['comments'][$cid]['xhtml'] = $xhtml;\n\n $type = 'ec'; // edit comment\n }\n }\n\n // save the comment metadata file\n io_saveFile($file, serialize($data));\n $this->addLogEntry($date, $ID, $type, '', $cid);\n\n $this->redirect($cid);\n return true;\n }\n\n /**\n * Recursive function to remove a comment from the data array\n *\n * @param string $cid comment id to be removed\n * @param array $comments array with all comments\n * @return array returns modified array with all remaining comments\n */\n protected function removeComment($cid, $comments)\n {\n if (is_array($comments[$cid]['replies'])) {\n foreach ($comments[$cid]['replies'] as $rid) {\n $comments = $this->removeComment($rid, $comments);\n }\n }\n unset($comments[$cid]);\n return $comments;\n }\n\n /**\n * Prints an individual comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent comment id of parent\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible is marked as visible\n */\n protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = '', $isVisible = true)\n {\n // comment was removed\n if (!isset($data['comments'][$cid])) {\n return;\n }\n $comment = $data['comments'][$cid];\n\n // corrupt datatype\n if (!is_array($comment)) {\n return;\n }\n\n // handle only replies to given parent comment\n if ($comment['parent'] != $parent) {\n return;\n }\n\n // comment hidden, only shown for moderators\n if (!$comment['show'] && !$this->helper->isDiscussionModerator()) {\n return;\n }\n\n // print the actual comment\n $this->showComment($cid, $data, $reply, $isVisible);\n // replies to this comment entry?\n $this->showReplies($cid, $data, $reply, $isVisible);\n // reply form\n $this->showReplyForm($cid, $reply);\n }\n\n /**\n * Print the comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible (grand)parent is marked as visible\n */\n protected function showComment($cid, $data, $reply, $isVisible)\n {\n global $conf, $lang, $HIGH, $INPUT;\n $comment = $data['comments'][$cid];\n\n //only moderators can arrive here if hidden\n $class = '';\n if (!$comment['show'] || !$isVisible) {\n $class = ' comment_hidden';\n }\n if($cid === $reply) {\n $class .= ' reply';\n }\n // comment head with date and user data\n ptln('
      ', 4);\n ptln('
      ', 6);\n ptln('', 8);\n $head = '';\n\n // prepare variables\n if (is_array($comment['user'])) { // new format\n $user = $comment['user']['id'];\n $name = $comment['user']['name'];\n $mail = $comment['user']['mail'];\n $url = $comment['user']['url'];\n $address = $comment['user']['address'];\n } else { // old format\n $user = $comment['user'];\n $name = $comment['name'];\n $mail = $comment['mail'];\n $url = $comment['url'];\n $address = $comment['address'];\n }\n if (is_array($comment['date'])) { // new format\n $created = $comment['date']['created'];\n $modified = $comment['date']['modified'] ?? null;\n } else { // old format\n $created = $comment['date'];\n $modified = $comment['edited'];\n }\n\n // show username or real name?\n if (!$this->getConf('userealname') && $user) {\n //not logged-in users have currently username set to '', but before 'test'\n if(substr($user, 0,4) === 'test'\n && (strpos($user, ':', 4) !== false || strpos($user, '.', 4) !== false)) {\n $showname = $name;\n } else {\n $showname = $user;\n }\n } else {\n $showname = $name;\n }\n\n // show avatar image?\n if ($this->useAvatar()) {\n $user_data['name'] = $name;\n $user_data['user'] = $user;\n $user_data['mail'] = $mail;\n $align = $lang['direction'] === 'ltr' ? 'left' : 'right';\n $avatar = $this->avatar->getXHTML($user_data, $name, $align);\n if ($avatar) {\n $head .= $avatar;\n }\n }\n\n if ($this->getConf('linkemail') && $mail) {\n $head .= $this->email($mail, $showname, 'email fn');\n } elseif ($url) {\n $head .= $this->external_link($this->checkURL($url), $showname, 'urlextern url fn');\n } else {\n $head .= '' . $showname . '';\n }\n\n if ($address) {\n $head .= ', ' . $address . '';\n }\n $head .= ', ' .\n '' .\n dformat($created, $conf['dformat']) . '';\n if ($modified) {\n $head .= ', ' . dformat($modified, $conf['dformat']) .\n '';\n }\n ptln($head, 8);\n ptln('
      ', 6); // class=\"comment_head\"\n\n // main comment content\n ptln('
      useAvatar() ? $this->getWidthStyle() : '') . '>', 6);\n echo ($HIGH ? html_hilight($comment['xhtml'], $HIGH) : $comment['xhtml']) . DOKU_LF;\n ptln('
      ', 6); // class=\"comment_body\"\n\n if ($isVisible) {\n ptln('
      ', 6);\n\n // show reply button?\n if ($data['status'] == 1 && !$reply && $comment['show']\n && ($this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER'))\n && $this->getConf('usethreading')\n ) {\n $this->showButton($cid, $this->getLang('btn_reply'), 'reply', true);\n }\n\n // show edit, show/hide and delete button?\n if (($user == $INPUT->server->str('REMOTE_USER') && $user != '') || $this->helper->isDiscussionModerator()) {\n $this->showButton($cid, $lang['btn_secedit'], 'edit', true);\n $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));\n $this->showButton($cid, $label, 'toogle');\n $this->showButton($cid, $lang['btn_delete'], 'delete');\n }\n ptln('
      ', 6); // class=\"comment_buttons\"\n }\n ptln('
      ', 4); // class=\"hentry\"\n }\n\n /**\n * If requested by user, show comment form to write a reply\n *\n * @param string $cid current comment id\n * @param string $reply comment id on which the user requested a reply\n */\n protected function showReplyForm($cid, $reply)\n {\n if ($this->getConf('usethreading') && $reply == $cid) {\n ptln('
      ', 4);\n $this->showCommentForm('', 'add', $cid);\n ptln('
      ', 4); // class=\"comment_replies\"\n }\n }\n\n /**\n * Show the replies to the given comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible is marked as visible by reference\n */\n protected function showReplies($cid, &$data, $reply, &$isVisible)\n {\n $comment = $data['comments'][$cid];\n if (!empty($comment['replies'])) {\n return;\n }\n ptln('
      getWidthStyle() . '>', 4);\n $isVisible = ($comment['show'] && $isVisible);\n foreach ($comment['replies'] as $rid) {\n $this->showCommentWithReplies($rid, $data, $cid, $reply, $isVisible);\n }\n ptln('
      ', 4);\n }\n\n /**\n * Is an avatar displayed?\n *\n * @return bool\n */\n protected function useAvatar()\n {\n if (is_null($this->useAvatar)) {\n $this->useAvatar = $this->getConf('useavatar')\n && ($this->avatar = $this->loadHelper('avatar', false));\n }\n return $this->useAvatar;\n }\n\n /**\n * Calculate width of indent\n *\n * @return string\n */\n protected function getWidthStyle()\n {\n global $lang;\n\n if (is_null($this->style)) {\n $side = $lang['direction'] === 'ltr' ? 'left' : 'right';\n\n if ($this->useAvatar()) {\n $this->style = ' style=\"margin-' . $side . ': ' . ($this->avatar->getConf('size') + 14) . 'px;\"';\n } else {\n $this->style = ' style=\"margin-' . $side . ': 20px;\"';\n }\n }\n return $this->style;\n }\n\n /**\n * Show the button which toggles between show/hide of the entire discussion section\n */\n protected function showDiscussionToggleButton()\n {\n ptln('
      ');\n ptln('getLang('toggle_display') . '\">');\n ptln('
      ');\n }\n\n /**\n * Outputs the comment form\n *\n * @param string $raw the existing comment text in case of edit\n * @param string $act action 'add' or 'save'\n * @param string|null $cid comment id to be responded to or null\n */\n protected function showCommentForm($raw, $act, $cid = null)\n {\n global $lang, $conf, $ID, $INPUT;\n\n // not for unregistered users when guest comments aren't allowed\n if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('allowguests')) {\n ?>\n
      \n getLang('noguests'); ?>\n
      \n str('text') if it's empty (for failed CAPTCHA check)\n if (!$raw && $INPUT->str('comment') == 'show') {\n $raw = $INPUT->str('text');\n }\n ?>\n\n
      \n
      \"\n accept-charset=\"\">\n
      \n \"/>\n \n \"/>\n \n \"/>\n server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionModerator())) {\n ?>\n \n
      \n \n
      \n
      \n \n
      \n getConf('urlfield')) {\n ?>\n
      \n \n
      \n getConf('addressfield')) {\n ?>\n
      \n \n
      \n getConf('adminimport') && ($this->helper->isDiscussionModerator())) {\n ?>\n
      \n \n
      \n \n \"/>\n \n
      \n getLang('entercomment');\n echo($this->getConf('wikisyntaxok') ? \"\" : \":\");\n if ($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?>\n\n \n getConf('wikisyntaxok')) { ?>\n
      \n \n
      \n \n
      \n str('comment') == 'add' && empty($INPUT->str('text'))) echo ' error' ?>\"\n name=\"text\" cols=\"80\" rows=\"10\" id=\"discussion__comment_text\" tabindex=\"5\">str('text'));\n }\n ?>\n
      \n\n loadHelper('captcha', false);\n if ($captcha && $captcha->isEnabled()) {\n echo $captcha->getHTML();\n }\n\n /** @var helper_plugin_recaptcha $recaptcha */\n $recaptcha = $this->loadHelper('recaptcha', false);\n if ($recaptcha && $recaptcha->isEnabled()) {\n echo $recaptcha->getHTML();\n }\n ?>\n\n \"\n title=\" [S]\" tabindex=\"7\"/>\n server->has('REMOTE_USER')\n || $INPUT->server->has('REMOTE_USER') && !$conf['subscribers'])\n && $this->getConf('subscribe')) { ?>\n \n \n \"\n title=\" [P]\"/>\n \n \" >\n \n\n
      \n
       
      \n
      \n \n
      \n \n
      \" method=\"get\" action=\"\">\n
      \n \"/>\n \n \"/>\n \"/>\n \" class=\"button\" title=\"\"/>\n
      \n
      \n \n *\n * @author Esther Brunner \n */\n protected function addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '')\n {\n global $conf, $INPUT;\n\n $changelog = $conf['metadir'] . '/_comments.changes';\n\n //use current time if none supplied\n if (!$date) {\n $date = time();\n }\n $remote = $INPUT->server->str('REMOTE_ADDR');\n $user = $INPUT->server->str('REMOTE_USER');\n\n $strip = [\"\\t\", \"\\n\"];\n $logline = [\n 'date' => $date,\n 'ip' => $remote,\n 'type' => str_replace($strip, '', $type),\n 'id' => $id,\n 'user' => $user,\n 'sum' => str_replace($strip, '', $summary),\n 'extra' => str_replace($strip, '', $extra)\n ];\n\n // add changelog line\n $logline = implode(\"\\t\", $logline) . \"\\n\";\n io_saveFile($changelog, $logline, true); //global changelog cache\n $this->trimRecentCommentsLog($changelog);\n\n // tell the indexer to re-index the page\n @unlink(metaFN($id, '.indexed'));\n }\n\n /**\n * Trims the recent comments cache to the last $conf['changes_days'] recent\n * changes or $conf['recent'] items, which ever is larger.\n * The trimming is only done once a day.\n *\n * @param string $changelog file path\n * @return bool\n * @author Ben Coburn \n *\n */\n protected function trimRecentCommentsLog($changelog)\n {\n global $conf;\n\n if (@file_exists($changelog)\n && (filectime($changelog) + 86400) < time()\n && !@file_exists($changelog . '_tmp')\n ) {\n\n io_lock($changelog);\n $lines = file($changelog);\n if (count($lines) < $conf['recent']) {\n // nothing to trim\n io_unlock($changelog);\n return true;\n }\n\n // presave tmp as 2nd lock\n io_saveFile($changelog . '_tmp', '');\n $trim_time = time() - $conf['recent_days'] * 86400;\n $out_lines = [];\n\n $num = count($lines);\n for ($i = 0; $i < $num; $i++) {\n $log = parseChangelogLine($lines[$i]);\n if ($log === false) continue; // discard junk\n if ($log['date'] < $trim_time) {\n $old_lines[$log['date'] . \".$i\"] = $lines[$i]; // keep old lines for now (append .$i to prevent key collisions)\n } else {\n $out_lines[$log['date'] . \".$i\"] = $lines[$i]; // definitely keep these lines\n }\n }\n\n // sort the final result, it shouldn't be necessary,\n // however the extra robustness in making the changelog cache self-correcting is worth it\n ksort($out_lines);\n $extra = $conf['recent'] - count($out_lines); // do we need extra lines do bring us up to minimum\n if ($extra > 0) {\n ksort($old_lines);\n $out_lines = array_merge(array_slice($old_lines, -$extra), $out_lines);\n }\n\n // save trimmed changelog\n io_saveFile($changelog . '_tmp', implode('', $out_lines));\n @unlink($changelog);\n if (!rename($changelog . '_tmp', $changelog)) {\n // rename failed so try another way...\n io_unlock($changelog);\n io_saveFile($changelog, implode('', $out_lines));\n @unlink($changelog . '_tmp');\n } else {\n io_unlock($changelog);\n }\n return true;\n }\n return true;\n }\n\n /**\n * Sends a notify mail on new comment\n *\n * @param array $comment data array of the new comment\n * @param array $subscribers data of the subscribers by reference\n *\n * @author Andreas Gohr \n * @author Esther Brunner \n */\n protected function notify($comment, &$subscribers)\n {\n global $conf, $ID, $INPUT, $auth;\n\n $notify_text = io_readfile($this->localfn('subscribermail'));\n $confirm_text = io_readfile($this->localfn('confirmsubscribe'));\n $subject_notify = '[' . $conf['title'] . '] ' . $this->getLang('mail_newcomment');\n $subject_subscribe = '[' . $conf['title'] . '] ' . $this->getLang('subscribe');\n\n $mailer = new Mailer();\n if (!$INPUT->server->has('REMOTE_USER')) {\n $mailer->from($conf['mailfromnobody']);\n }\n\n $replace = [\n 'PAGE' => $ID,\n 'TITLE' => $conf['title'],\n 'DATE' => dformat($comment['date']['created'], $conf['dformat']),\n 'NAME' => $comment['user']['name'],\n 'TEXT' => $comment['raw'],\n 'COMMENTURL' => wl($ID, '', true) . '#comment_' . $comment['cid'],\n 'UNSUBSCRIBE' => wl($ID, 'do=subscribe', true, '&'),\n 'DOKUWIKIURL' => DOKU_URL\n ];\n\n $confirm_replace = [\n 'PAGE' => $ID,\n 'TITLE' => $conf['title'],\n 'DOKUWIKIURL' => DOKU_URL\n ];\n\n\n $mailer->subject($subject_notify);\n $mailer->setBody($notify_text, $replace);\n\n // send mail to notify address\n if ($conf['notify']) {\n $mailer->bcc($conf['notify']);\n $mailer->send();\n }\n\n // send email to moderators\n if ($this->getConf('moderatorsnotify')) {\n $moderatorgrpsString = trim($this->getConf('moderatorgroups'));\n if (!empty($moderatorgrpsString)) {\n // create a clean mods list\n $moderatorgroups = explode(',', $moderatorgrpsString);\n $moderatorgroups = array_map('trim', $moderatorgroups);\n $moderatorgroups = array_unique($moderatorgroups);\n $moderatorgroups = array_filter($moderatorgroups);\n // search for moderators users\n foreach ($moderatorgroups as $moderatorgroup) {\n if (!$auth->isCaseSensitive()) {\n $moderatorgroup = PhpString::strtolower($moderatorgroup);\n }\n // create a clean mailing list\n $bccs = [];\n if ($moderatorgroup[0] == '@') {\n foreach ($auth->retrieveUsers(0, 0, ['grps' => $auth->cleanGroup(substr($moderatorgroup, 1))]) as $user) {\n if (!empty($user['mail'])) {\n $bccs[] = $user['mail'];\n }\n }\n } else {\n //it is an user\n $userdata = $auth->getUserData($auth->cleanUser($moderatorgroup));\n if (!empty($userdata['mail'])) {\n $bccs[] = $userdata['mail'];\n }\n }\n $bccs = array_unique($bccs);\n // notify the users\n $mailer->bcc(implode(',', $bccs));\n $mailer->send();\n }\n }\n }\n\n // notify page subscribers\n if (actionOK('subscribe')) {\n $data = ['id' => $ID, 'addresslist' => '', 'self' => false];\n //FIXME default callback, needed to mentioned it again?\n Event::createAndTrigger(\n 'COMMON_NOTIFY_ADDRESSLIST', $data,\n [new SubscriberManager(), 'notifyAddresses']\n );\n\n $to = $data['addresslist'];\n if (!empty($to)) {\n $mailer->bcc($to);\n $mailer->send();\n }\n }\n\n // notify comment subscribers\n if (!empty($subscribers)) {\n\n foreach ($subscribers as $mail => $data) {\n $mailer->bcc($mail);\n if ($data['active']) {\n $replace['UNSUBSCRIBE'] = wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&');\n\n $mailer->subject($subject_notify);\n $mailer->setBody($notify_text, $replace);\n $mailer->send();\n } elseif (!$data['confirmsent']) {\n $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&');\n\n $mailer->subject($subject_subscribe);\n $mailer->setBody($confirm_text, $confirm_replace);\n $mailer->send();\n $subscribers[$mail]['confirmsent'] = true;\n }\n }\n }\n }\n\n /**\n * Counts the number of visible comments\n *\n * @param array $data array with all comments\n * @return int\n */\n protected function countVisibleComments($data)\n {\n $number = 0;\n foreach ($data['comments'] as $comment) {\n if ($comment['parent']) continue;\n if (!$comment['show']) continue;\n\n $number++;\n $rids = $comment['replies'];\n if (count($rids)) {\n $number = $number + $this->countVisibleReplies($data, $rids);\n }\n }\n return $number;\n }\n\n /**\n * Count visible replies on the comments\n *\n * @param array $data\n * @param array $rids\n * @return int counted replies\n */\n protected function countVisibleReplies(&$data, $rids)\n {\n $number = 0;\n foreach ($rids as $rid) {\n if (!isset($data['comments'][$rid])) continue; // reply was removed\n if (!$data['comments'][$rid]['show']) continue;\n\n $number++;\n $rids = $data['comments'][$rid]['replies'];\n if (count($rids)) {\n $number = $number + $this->countVisibleReplies($data, $rids);\n }\n }\n return $number;\n }\n\n /**\n * Renders the raw comment (wiki)text to html\n *\n * @param string $raw comment text\n * @return null|string\n */\n protected function renderComment($raw)\n {\n if ($this->getConf('wikisyntaxok')) {\n // Note the warning for render_text:\n // \"very ineffecient for small pieces of data - try not to use\"\n // in dokuwiki/inc/plugin.php\n $xhtml = $this->render_text($raw);\n } else { // wiki syntax not allowed -> just encode special chars\n $xhtml = hsc(trim($raw));\n $xhtml = str_replace(\"\\n\", '
      ', $xhtml);\n }\n return $xhtml;\n }\n\n /**\n * Finds out whether there is a discussion section for the current page\n *\n * @param string $title set to title from metadata or empty string\n * @return bool discussion section is shown?\n */\n protected function hasDiscussion(&$title)\n {\n global $ID;\n\n $file = metaFN($ID, '.comments');\n\n if (!@file_exists($file)) {\n if ($this->isDiscussionEnabled()) {\n return true;\n } else {\n return false;\n }\n }\n\n $data = unserialize(io_readFile($file, false));\n\n $title = $data['title'] ?? '';\n\n $num = $data['number'] ?? 0;\n if (!$data['status'] || ($data['status'] == 2 && $num == 0)) {\n //disabled, or closed and no comments\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Creates a new thread page\n *\n * @return string\n */\n protected function newThread()\n {\n global $ID, $INFO, $INPUT;\n\n $ns = cleanID($INPUT->str('ns'));\n $title = str_replace(':', '', $INPUT->str('title'));\n $back = $ID;\n $ID = ($ns ? $ns . ':' : '') . cleanID($title);\n $INFO = pageinfo();\n\n // check if we are allowed to create this file\n if ($INFO['perm'] >= AUTH_CREATE) {\n\n //check if locked by anyone - if not lock for my self\n if ($INFO['locked']) {\n return 'locked';\n } else {\n lock($ID);\n }\n\n // prepare the new thread file with default stuff\n if (!@file_exists($INFO['filepath'])) {\n global $TEXT;\n\n $TEXT = pageTemplate(($ns ? $ns . ':' : '') . $title);\n if (!$TEXT) {\n $data = ['id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back];\n $TEXT = $this->pageTemplate($data);\n }\n return 'preview';\n } else {\n return 'edit';\n }\n } else {\n return 'show';\n }\n }\n\n /**\n * Adapted version of pageTemplate() function\n *\n * @param array $data\n * @return string\n */\n protected function pageTemplate($data)\n {\n global $conf, $INFO, $INPUT;\n\n $id = $data['id'];\n $user = $INPUT->server->str('REMOTE_USER');\n $tpl = io_readFile(DOKU_PLUGIN . 'discussion/_template.txt');\n\n // standard replacements\n $replace = [\n '@NS@' => $data['ns'],\n '@PAGE@' => strtr(noNS($id), '_', ' '),\n '@USER@' => $user,\n '@NAME@' => $INFO['userinfo']['name'],\n '@MAIL@' => $INFO['userinfo']['mail'],\n '@DATE@' => dformat(time(), $conf['dformat']),\n ];\n\n // additional replacements\n $replace['@BACK@'] = $data['back'];\n $replace['@TITLE@'] = $data['title'];\n\n // avatar if useavatar and avatar plugin available\n if ($this->getConf('useavatar') && !plugin_isdisabled('avatar')) {\n $replace['@AVATAR@'] = '{{avatar>' . $user . ' }} ';\n } else {\n $replace['@AVATAR@'] = '';\n }\n\n // tag if tag plugin is available\n if (!plugin_isdisabled('tag')) {\n $replace['@TAG@'] = \"\\n\\n{{tag>}}\";\n } else {\n $replace['@TAG@'] = '';\n }\n\n // perform the replacements in tpl\n return str_replace(array_keys($replace), array_values($replace), $tpl);\n }\n\n /**\n * Checks if the CAPTCHA string submitted is valid, modifies action if needed\n */\n protected function captchaCheck()\n {\n global $INPUT;\n /** @var helper_plugin_captcha $captcha */\n if (!$captcha = $this->loadHelper('captcha', false)) {\n // CAPTCHA is disabled or not available\n return;\n }\n\n if ($captcha->isEnabled() && !$captcha->check()) {\n if ($INPUT->str('comment') == 'save') {\n $INPUT->set('comment', 'edit');\n } elseif ($INPUT->str('comment') == 'add') {\n $INPUT->set('comment', 'show');\n }\n }\n }\n\n /**\n * checks if the submitted reCAPTCHA string is valid, modifies action if needed\n *\n * @author Adrian Schlegel \n */\n protected function recaptchaCheck()\n {\n global $INPUT;\n /** @var helper_plugin_recaptcha $recaptcha */\n if (!$recaptcha = plugin_load('helper', 'recaptcha'))\n return; // reCAPTCHA is disabled or not available\n\n // do nothing if logged in user and no reCAPTCHA required\n if (!$recaptcha->getConf('forusers') && $INPUT->server->has('REMOTE_USER')) return;\n\n $response = $recaptcha->check();\n if (!$response->is_valid) {\n msg($recaptcha->getLang('testfailed'), -1);\n if ($INPUT->str('comment') == 'save') {\n $INPUT->str('comment', 'edit');\n } elseif ($INPUT->str('comment') == 'add') {\n $INPUT->str('comment', 'show');\n }\n }\n }\n\n /**\n * Add discussion plugin version to the indexer version\n * This means that all pages will be indexed again in order to add the comments\n * to the index whenever there has been a change that concerns the index content.\n *\n * @param Doku_Event $event\n */\n public function addIndexVersion(Doku_Event $event)\n {\n $event->data['discussion'] = '0.1';\n }\n\n /**\n * Adds the comments to the index\n *\n * @param Doku_Event $event\n * @param array $param with\n * 'id' => string 'page'/'id' for respectively INDEXER_PAGE_ADD and FULLTEXT_SNIPPET_CREATE event\n * 'text' => string 'body'/'text'\n */\n public function addCommentsToIndex(Doku_Event $event, $param)\n {\n // get .comments meta file name\n $file = metaFN($event->data[$param['id']], '.comments');\n\n if (!@file_exists($file)) return;\n $data = unserialize(io_readFile($file, false));\n\n // comments are turned off or no comments available to index\n if (!$data['status'] || $data['number'] == 0) return;\n\n // now add the comments\n if (isset($data['comments'])) {\n foreach ($data['comments'] as $key => $value) {\n $event->data[$param['text']] .= DOKU_LF . $this->addCommentWords($key, $data);\n }\n }\n }\n\n /**\n * Checks if the phrase occurs in the comments and return event result true if matching\n *\n * @param Doku_Event $event\n */\n public function fulltextPhraseMatchInComments(Doku_Event $event)\n {\n if ($event->result === true) return;\n\n // get .comments meta file name\n $file = metaFN($event->data['id'], '.comments');\n\n if (!@file_exists($file)) return;\n $data = unserialize(io_readFile($file, false));\n\n // comments are turned off or no comments available to match\n if (!$data['status'] || $data['number'] == 0) return;\n\n $matched = false;\n\n // now add the comments\n if (isset($data['comments'])) {\n foreach ($data['comments'] as $cid => $value) {\n $matched = $this->phraseMatchInComment($event->data['phrase'], $cid, $data);\n if ($matched) break;\n }\n }\n\n if ($matched) {\n $event->result = true;\n }\n }\n\n /**\n * Match the phrase in the comment and its replies\n *\n * @param string $phrase phrase to search\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent cid of parent\n * @return bool if match true, otherwise false\n */\n protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '')\n {\n if (!isset($data['comments'][$cid])) return false; // comment was removed\n\n $comment = $data['comments'][$cid];\n\n if (!is_array($comment)) return false; // corrupt datatype\n if ($comment['parent'] != $parent) return false; // reply to an other comment\n if (!$comment['show']) return false; // hidden comment\n\n $text = PhpString::strtolower($comment['raw']);\n if (strpos($text, $phrase) !== false) {\n return true;\n }\n\n if (is_array($comment['replies'])) { // and the replies\n foreach ($comment['replies'] as $rid) {\n if ($this->phraseMatchInComment($phrase, $rid, $data, $cid)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Saves the current comment status and title from metadata into the .comments file\n *\n * @param Doku_Event $event\n */\n public function updateCommentStatusFromMetadata(Doku_Event $event)\n {\n global $ID;\n\n $meta = $event->data['current'];\n\n $file = metaFN($ID, '.comments');\n $configurationStatus = ($this->isDiscussionEnabled() ? 1 : 0); // 0=off, 1=enabled\n $title = null;\n if (isset($meta['plugin_discussion'])) {\n $status = (int) $meta['plugin_discussion']['status']; // 0=off, 1=enabled or 2=closed\n $title = $meta['plugin_discussion']['title'];\n\n // do we have metadata that differs from general config?\n $saveNeededFromMetadata = $configurationStatus !== $status || ($status > 0 && $title);\n } else {\n $status = $configurationStatus;\n $saveNeededFromMetadata = false;\n }\n\n // if .comment file exists always update it with latest status\n if ($saveNeededFromMetadata || file_exists($file)) {\n\n $data = [];\n if (@file_exists($file)) {\n $data = unserialize(io_readFile($file, false));\n }\n\n if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) {\n //title can be only set from metadata\n $data['title'] = $title;\n $data['status'] = $status;\n if (!isset($data['number'])) {\n $data['number'] = 0;\n }\n io_saveFile($file, serialize($data));\n }\n }\n }\n\n /**\n * Return words of a given comment and its replies, suitable to be added to the index\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent cid of parent\n * @return string\n */\n protected function addCommentWords($cid, &$data, $parent = '')\n {\n\n if (!isset($data['comments'][$cid])) return ''; // comment was removed\n\n $comment = $data['comments'][$cid];\n\n if (!is_array($comment)) return ''; // corrupt datatype\n if ($comment['parent'] != $parent) return ''; // reply to an other comment\n if (!$comment['show']) return ''; // hidden comment\n\n $text = $comment['raw']; // we only add the raw comment text\n if (is_array($comment['replies'])) { // and the replies\n foreach ($comment['replies'] as $rid) {\n $text .= $this->addCommentWords($rid, $data, $cid);\n }\n }\n return ' ' . $text;\n }\n\n /**\n * Only allow http(s) URLs and append http:// to URLs if needed\n *\n * @param string $url\n * @return string\n */\n protected function checkURL($url)\n {\n if (preg_match(\"#^http://|^https://#\", $url)) {\n return hsc($url);\n } elseif (substr($url, 0, 4) == 'www.') {\n return hsc('https://' . $url);\n } else {\n return '';\n }\n }\n\n /**\n * Sort threads\n *\n * @param array $a array with comment properties\n * @param array $b array with comment properties\n * @return int\n */\n function sortThreadsOnCreation($a, $b)\n {\n if (is_array($a['date'])) {\n // new format\n $createdA = $a['date']['created'];\n } else {\n // old format\n $createdA = $a['date'];\n }\n\n if (is_array($b['date'])) {\n // new format\n $createdB = $b['date']['created'];\n } else {\n // old format\n $createdB = $b['date'];\n }\n\n if ($createdA == $createdB) {\n return 0;\n } else {\n return ($createdA < $createdB) ? -1 : 1;\n }\n }\n\n}\n\n\n"} +{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/autoload.rb", "file_before": "require \"#{Rails.root}/config/initializers/inflections\"\n\nmodule HasManyPolymorphs\n\n=begin rdoc \nSearches for models that use has_many_polymorphs or acts_as_double_polymorphic_join and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes. \n\nNote that you can override DEFAULT_OPTIONS via Rails::Configuration#has_many_polymorphs_options. For example, if you need an application extension to be required before has_many_polymorphs loads your models, add an after_initialize block in config/environment.rb that appends to the 'requirements' key:\n Rails::Initializer.run do |config| \n # your other configuration here\n \n config.after_initialize do\n config.has_many_polymorphs.options['requirements'] << 'lib/my_extension'\n end \n end\n \n=end\n \n MODELS_ROOT = Rails.root.join('app', 'models')\n \n DEFAULT_OPTIONS = {\n :file_pattern => \"#{MODELS_ROOT}/**/*.rb\",\n :file_exclusions => ['svn', 'CVS', 'bzr'],\n :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],\n :requirements => []}\n \n mattr_accessor :options\n @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS) \n\n # Dispatcher callback to load polymorphic relationships from the top down.\n def self.setup\n\n _logger_debug \"autoload hook invoked\"\n \n options[:requirements].each do |requirement|\n _logger_warn \"forcing requirement load of #{requirement}\"\n require requirement\n end\n \n Dir.glob(options[:file_pattern]).each do |filename|\n next if filename =~ /#{options[:file_exclusions].join(\"|\")}/\n open(filename) do |file|\n if file.grep(/#{options[:methods].join(\"|\")}/).any?\n begin\n # determines the modelname by the directory - this allows the autoload of namespaced models\n modelname = filename[0..-4].gsub(\"#{MODELS_ROOT.to_s}/\", \"\")\n model = modelname.camelize\n _logger_warn \"preloading parent model #{model}\"\n model.constantize\n rescue Object => e\n _logger_warn \"#{model} could not be preloaded: #{e.inspect} #{e.backtrace}\"\n end\n end\n end\n end\n end \n \nend\n", "file_after": "require \"#{Rails.root}/config/initializers/inflections\"\n\nmodule HasManyPolymorphs\n\n=begin rdoc\nSearches for models that use has_many_polymorphs or acts_as_double_polymorphic_join and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes.\n\nNote that you can override DEFAULT_OPTIONS via Rails::Configuration#has_many_polymorphs_options. For example, if you need an application extension to be required before has_many_polymorphs loads your models, add an after_initialize block in config/environment.rb that appends to the 'requirements' key:\n Rails::Initializer.run do |config|\n # your other configuration here\n\n config.after_initialize do\n config.has_many_polymorphs.options['requirements'] << 'lib/my_extension'\n end\n end\n\n=end\n\n MODELS_ROOT = Rails.root.join('app', 'models')\n\n DEFAULT_OPTIONS = {\n :file_pattern => \"#{MODELS_ROOT}/**/*.rb\",\n :file_exclusions => ['svn', 'CVS', 'bzr'],\n :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],\n :requirements => []}\n\n mattr_accessor :options\n @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS)\n\n # Dispatcher callback to load polymorphic relationships from the top down.\n def self.setup\n\n _logger_debug \"autoload hook invoked\"\n\n options[:requirements].each do |requirement|\n _logger_warn \"forcing requirement load of #{requirement}\"\n require requirement\n end\n\n Dir.glob(options[:file_pattern]).each do |filename|\n next if filename =~ /#{options[:file_exclusions].join(\"|\")}/\n open(filename) do |file|\n if file.grep(/#{options[:methods].join(\"|\")}/).any?\n begin\n # determines the modelname by the directory - this allows the autoload of namespaced models\n modelname = filename[0..-4].gsub(\"#{MODELS_ROOT.to_s}/\", \"\")\n model = modelname.camelize\n _logger_warn \"preloading parent model #{model}\"\n model.constantize\n rescue Object => e\n _logger_warn \"#{model} could not be preloaded: #{e.inspect} #{e.backtrace}\"\n end\n end\n end\n end\n end\n\nend\n"} +{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/debugging_tools.rb", "file_before": "\n=begin rdoc\n\nDebugging tools for Has_many_polymorphs. \n\nEnable the different tools by setting the environment variable HMP_DEBUG. Settings with special meaning are \"ruby-debug\", \"trace\", and \"dependencies\".\n\n== Code generation\n\nEnabled by default when HMP_DEBUG is set.\n\nOuputs a folder generated_models/ in RAILS_ROOT containing valid Ruby files explaining all the ActiveRecord relationships set up by the plugin, as well as listing the line in the plugin that called each particular association method.\n\n== Ruby-debug\n\nEnable by setting HMP_DEBUG to \"ruby-debug\".\n\nStarts ruby-debug for the life of the process.\n\n== Trace\n\nEnable by setting HMP_DEBUG to \"ruby-debug\".\n\nOutputs an indented trace of relevant method calls as they occur.\n\n== Dependencies\n\nEnable by setting HMP_DEBUG to \"dependencies\".\n\nTurns on Rails' default dependency logging.\n\n=end\n\n_logger_warn \"debug mode enabled\"\n\nclass << ActiveRecord::Base\n COLLECTION_METHODS = [:belongs_to, :has_many, :has_and_belongs_to_many, :has_one, \n :has_many_polymorphs, :acts_as_double_polymorphic_join].each do |method_name|\n alias_method \"original_#{method_name}\".to_sym, method_name\n undef_method method_name\n end \n\n unless defined? GENERATED_CODE_DIR\n GENERATED_CODE_DIR = \"#{RAILS_ROOT}/generated_models\"\n \n begin\n system \"rm -rf #{GENERATED_CODE_DIR}\" \n Dir.mkdir GENERATED_CODE_DIR\n rescue Errno::EACCES\n _logger_warn \"no permissions for generated code dir: #{GENERATED_CODE_DIR}\"\n end\n\n if File.exist? GENERATED_CODE_DIR\n alias :original_method_missing :method_missing\n def method_missing(method_name, *args, &block)\n if COLLECTION_METHODS.include? method_name.to_sym\n Dir.chdir GENERATED_CODE_DIR do\n filename = \"#{demodulate(self.name.underscore)}.rb\"\n contents = File.open(filename).read rescue \"\\nclass #{self.name}\\n\\nend\\n\"\n line = caller[1][/\\:(\\d+)\\:/, 1]\n contents[-5..-5] = \"\\n #{method_name} #{args[0..-2].inspect[1..-2]},\\n #{args[-1].inspect[1..-2].gsub(\" :\", \"\\n :\").gsub(\"=>\", \" => \")}\\n#{ block ? \" #{block.inspect.sub(/\\@.*\\//, '@')}\\n\" : \"\"} # called from line #{line}\\n\\n\"\n File.open(filename, \"w\") do |file| \n file.puts contents \n end\n end\n # doesn't actually display block contents\n self.send(\"original_#{method_name}\", *args, &block)\n else\n self.send(:original_method_missing, method_name, *args, &block)\n end\n end\n end \n \n end\nend\n\ncase ENV['HMP_DEBUG']\n\n when \"ruby-debug\"\n require 'rubygems'\n require 'ruby-debug'\n Debugger.start\n _logger_warn \"ruby-debug enabled.\"\n\n when \"trace\"\n _logger_warn \"method tracing enabled\" \n $debug_trace_indent = 0\n set_trace_func (proc do |event, file, line, id, binding, classname|\n if id.to_s =~ /instantiate/ #/IRB|Wirble|RubyLex|RubyToken|Logger|ConnectionAdapters|SQLite3|MonitorMixin|Benchmark|Inflector|Inflections/ \n if event == 'call'\n puts (\" \" * $debug_trace_indent) + \"#{event}ed #{classname}\\##{id} from #{file.split('/').last}::#{line}\"\n $debug_trace_indent += 1\n elsif event == 'return'\n $debug_trace_indent -= 1 unless $debug_trace_indent == 0\n puts (\" \" * $debug_trace_indent) + \"#{event}ed #{classname}\\##{id}\"\n end\n end\n end)\n \n when \"dependencies\"\n _logger_warn \"dependency activity being logged\"\n (::Dependencies.log_activity = true) rescue nil\nend\n", "file_after": "\n=begin rdoc\n\nDebugging tools for Has_many_polymorphs.\n\nEnable the different tools by setting the environment variable HMP_DEBUG. Settings with special meaning are \"ruby-debug\", \"trace\", and \"dependencies\".\n\n== Code generation\n\nEnabled by default when HMP_DEBUG is set.\n\nOuputs a folder generated_models/ in Rails.root containing valid Ruby files explaining all the ActiveRecord relationships set up by the plugin, as well as listing the line in the plugin that called each particular association method.\n\n== Ruby-debug\n\nEnable by setting HMP_DEBUG to \"ruby-debug\".\n\nStarts ruby-debug for the life of the process.\n\n== Trace\n\nEnable by setting HMP_DEBUG to \"trace\".\n\nOutputs an indented trace of relevant method calls as they occur.\n\n== Dependencies\n\nEnable by setting HMP_DEBUG to \"dependencies\".\n\nTurns on Rails' default dependency logging.\n\n=end\n\n_logger_warn \"debug mode enabled\"\n\nclass << ActiveRecord::Base\n COLLECTION_METHODS = [:belongs_to, :has_many, :has_and_belongs_to_many, :has_one,\n :has_many_polymorphs, :acts_as_double_polymorphic_join].each do |method_name|\n alias_method \"original_#{method_name}\".to_sym, method_name\n undef_method method_name\n end\n\n unless defined? GENERATED_CODE_DIR\n base_dir = defined?(Rails) ? Rails.root.expand_path : '/tmp'\n GENERATED_CODE_DIR = \"#{base_dir}/generated_models\"\n\n begin\n system \"rm -rf #{GENERATED_CODE_DIR}\"\n Dir.mkdir GENERATED_CODE_DIR\n rescue Errno::EACCES\n _logger_warn \"no permissions for generated code dir: #{GENERATED_CODE_DIR}\"\n end\n\n if File.exist? GENERATED_CODE_DIR\n alias :original_method_missing :method_missing\n def method_missing(method_name, *args, &block)\n if COLLECTION_METHODS.include? method_name.to_sym\n Dir.chdir GENERATED_CODE_DIR do\n filename = \"#{demodulate(self.name.underscore)}.rb\"\n contents = File.open(filename).read rescue \"\\nclass #{self.name}\\n\\nend\\n\"\n callfile, callline = caller[2][%r!/.*/(.*?:\\d+)!, 1].split(':')\n contents[-5..-5] = \"\\n #{method_name} #{args[0..-2].inspect[1..-2]},\\n #{args[-1].inspect[1..-2].gsub(\" :\", \"\\n :\").gsub(\"=>\", \" => \")}\\n#{ block ? \" #{block.inspect.sub(/\\@.*\\//, '@')}\\n\" : \"\"} # called from #{callfile}, line #{callline}\\n\\n\"\n File.open(filename, \"w\") do |file|\n file.puts contents\n end\n end\n # doesn't actually display block contents\n self.send(\"original_#{method_name}\", *args, &block)\n else\n self.send(:original_method_missing, method_name, *args, &block)\n end\n end\n end\n\n end\nend\n\ncase ENV['HMP_DEBUG']\n\n when \"ruby-debug\"\n require 'rubygems'\n require 'ruby-debug'\n Debugger.start\n _logger_warn \"ruby-debug enabled.\"\n\n when \"trace\"\n _logger_warn \"method tracing enabled\"\n $debug_trace_indent = 0\n set_trace_func (proc do |event, file, line, id, binding, classname|\n if id.to_s =~ /instantiate/ #/IRB|Wirble|RubyLex|RubyToken|Logger|ConnectionAdapters|SQLite3|MonitorMixin|Benchmark|Inflector|Inflections/\n if event == 'call'\n puts (\" \" * $debug_trace_indent) + \"#{event}ed #{classname}\\##{id} from #{file.split('/').last}::#{line}\"\n $debug_trace_indent += 1\n elsif event == 'return'\n $debug_trace_indent -= 1 unless $debug_trace_indent == 0\n puts (\" \" * $debug_trace_indent) + \"#{event}ed #{classname}\\##{id}\"\n end\n end\n end)\n\n when \"dependencies\"\n _logger_warn \"dependency activity being logged\"\n (::Dependencies.log_activity = true) rescue nil\nend\n"} +{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/base.rb", "file_before": "\nmodule ActiveRecord\n class Base\n \n class << self\n \n # Interprets a polymorphic row from a unified SELECT, returning the appropriate ActiveRecord instance. Overrides ActiveRecord::Base.instantiate_without_callbacks.\n def instantiate_with_polymorphic_checks(record)\n if record['polymorphic_parent_class']\n reflection = record['polymorphic_parent_class'].constantize.reflect_on_association(record['polymorphic_association_id'].to_sym)\n# _logger_debug \"Instantiating a polymorphic row for #{record['polymorphic_parent_class']}.reflect_on_association(:#{record['polymorphic_association_id']})\"\n\n # rewrite the record with the right column names\n table_aliases = reflection.options[:table_aliases].dup\n record = Hash[*table_aliases.keys.map {|key| [key, record[table_aliases[key]]] }.flatten] \n \n # find the real child class\n klass = record[\"#{self.table_name}.#{reflection.options[:polymorphic_type_key]}\"].constantize\n if sti_klass = record[\"#{klass.table_name}.#{klass.inheritance_column}\"]\n klass = klass.class_eval do compute_type(sti_klass) end # in case of namespaced STI models\n end\n \n # check that the join actually joined to something\n unless (child_id = record[\"#{self.table_name}.#{reflection.options[:polymorphic_key]}\"]) == record[\"#{klass.table_name}.#{klass.primary_key}\"]\n raise ActiveRecord::Associations::PolymorphicError, \n \"Referential integrity violation; child <#{klass.name}:#{child_id}> was not found for #{reflection.name.inspect}\" \n end\n \n # eject the join keys\n # XXX not very readable\n record = Hash[*record._select do |column, value| \n column[/^#{klass.table_name}/]\n end.map do |column, value|\n [column[/\\.(.*)/, 1], value]\n end.flatten]\n \n # allocate and assign values\n returning(klass.allocate) do |obj|\n obj.instance_variable_set(\"@attributes\", record)\n obj.instance_variable_set(\"@attributes_cache\", Hash.new)\n \n if obj.respond_to_without_attributes?(:after_find)\n obj.send(:callback, :after_find)\n end\n \n if obj.respond_to_without_attributes?(:after_initialize)\n obj.send(:callback, :after_initialize)\n end\n \n end\n else \n instantiate_without_polymorphic_checks(record)\n end\n end\n \n alias_method_chain :instantiate, :polymorphic_checks \n end\n \n end\nend\n", "file_after": "\nmodule ActiveRecord\n class Base\n\n class << self\n\n # Interprets a polymorphic row from a unified SELECT, returning the appropriate ActiveRecord instance. Overrides ActiveRecord::Base.instantiate_without_callbacks.\n def instantiate_with_polymorphic_checks(record)\n if record['polymorphic_parent_class']\n reflection = record['polymorphic_parent_class'].constantize.reflect_on_association(record['polymorphic_association_id'].to_sym)\n# _logger_debug \"Instantiating a polymorphic row for #{record['polymorphic_parent_class']}.reflect_on_association(:#{record['polymorphic_association_id']})\"\n\n # rewrite the record with the right column names\n table_aliases = reflection.options[:table_aliases].dup\n record = Hash[*table_aliases.keys.map {|key| [key, record[table_aliases[key]]] }.flatten]\n\n # find the real child class\n klass = record[\"#{self.table_name}.#{reflection.options[:polymorphic_type_key]}\"].constantize\n if sti_klass = record[\"#{klass.table_name}.#{klass.inheritance_column}\"]\n klass = klass.class_eval do compute_type(sti_klass) end # in case of namespaced STI models\n\n # copy the data over to the right structure\n klass.columns.map(&:name).each do |col|\n record[\"#{klass.table_name}.#{col}\"] = record[\"#{klass.base_class.table_name}.#{col}\"]\n end\n end\n\n # check that the join actually joined to something\n unless (child_id = record[\"#{self.table_name}.#{reflection.options[:polymorphic_key]}\"]) == record[\"#{klass.table_name}.#{klass.primary_key}\"]\n raise ActiveRecord::Associations::PolymorphicError,\n \"Referential integrity violation; child <#{klass.name}:#{child_id}> was not found for #{reflection.name.inspect}\"\n end\n\n # eject the join keys\n # XXX not very readable\n record = Hash[*record._select do |column, value|\n column[/^#{klass.table_name}/]\n end.map do |column, value|\n [column[/\\.(.*)/, 1], value]\n end.flatten]\n\n # allocate and assign values\n klass.allocate.tap do |obj|\n obj.instance_variable_set(\"@attributes\", record)\n obj.instance_variable_set(\"@attributes_cache\", Hash.new)\n\n if obj.respond_to_without_attributes?(:after_find)\n obj.send(:callback, :after_find)\n end\n\n if obj.respond_to_without_attributes?(:after_initialize)\n obj.send(:callback, :after_initialize)\n end\n\n end\n else\n instantiate_without_polymorphic_checks(record)\n end\n end\n\n alias_method_chain :instantiate, :polymorphic_checks\n end\n\n end\nend\n"} +{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/class_methods.rb", "file_before": "\nmodule ActiveRecord #:nodoc:\n module Associations #:nodoc:\n\n=begin rdoc\n\nClass methods added to ActiveRecord::Base for setting up polymorphic associations.\n\n== Notes\n \nSTI association targets must enumerated and named. For example, if Dog and Cat both inherit from Animal, you still need to say [:dogs, :cats], and not [:animals].\n\nNamespaced models follow the Rails underscore convention. ZooAnimal::Lion becomes :'zoo_animal/lion'.\n\nYou do not need to set up any other associations other than for either the regular method or the double. The join associations and all individual and reverse associations are generated for you. However, a join model and table are required. \n\nThere is a tentative report that you can make the parent model be its own join model, but this is untested.\n\n=end\n\n module PolymorphicClassMethods\n \n RESERVED_DOUBLES_KEYS = [:conditions, :order, :limit, :offset, :extend, :skip_duplicates, \n :join_extend, :dependent, :rename_individual_collections,\n :namespace] #:nodoc:\n \n=begin rdoc\n\nThis method creates a doubled-sided polymorphic relationship. It must be called on the join model:\n\n class Devouring < ActiveRecord::Base\n belongs_to :eater, :polymorphic => true\n belongs_to :eaten, :polymorphic => true\n \n acts_as_double_polymorphic_join(\n :eaters => [:dogs, :cats], \n :eatens => [:cats, :birds]\n ) \n end\n\nThe method works by defining one or more special has_many_polymorphs association on every model in the target lists, depending on which side of the association it is on. Double self-references will work.\n\nThe two association names and their value arrays are the only required parameters.\n\n== Available options\n\nThese options are passed through to targets on both sides of the association. If you want to affect only one side, prepend the key with the name of that side. For example, :eaters_extend.\n\n:dependent:: Accepts :destroy, :nullify, or :delete_all. Controls how the join record gets treated on any association delete (whether from the polymorph or from an individual collection); defaults to :destroy.\n:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true.\n:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with \"\\_of_#{association_name}\".\n:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).\n:join_extend:: One or an array of mixed modules and procs, which are applied to the join association.\n:conditions:: An array or string of conditions for the SQL WHERE clause. \n:order:: A string for the SQL ORDER BY clause.\n:limit:: An integer. Affects the polymorphic and individual associations.\n:offset:: An integer. Only affects the polymorphic association.\n:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default.\n\n=end\n\n def acts_as_double_polymorphic_join options={}, &extension \n \n collections, options = extract_double_collections(options)\n \n # handle the block\n options[:extend] = (if options[:extend]\n Array(options[:extend]) + [extension]\n else \n extension\n end) if extension \n \n collection_option_keys = make_general_option_keys_specific!(options, collections)\n \n join_name = self.name.tableize.to_sym\n collections.each do |association_id, children|\n parent_hash_key = (collections.keys - [association_id]).first # parents are the entries in the _other_ children array\n \n begin\n parent_foreign_key = self.reflect_on_association(parent_hash_key._singularize).primary_key_name\n rescue NoMethodError\n raise PolymorphicError, \"Couldn't find 'belongs_to' association for :#{parent_hash_key._singularize} in #{self.name}.\" unless parent_foreign_key\n end\n\n parents = collections[parent_hash_key]\n conflicts = (children & parents) # set intersection \n parents.each do |plural_parent_name| \n \n parent_class = plural_parent_name._as_class\n singular_reverse_association_id = parent_hash_key._singularize \n \n internal_options = {\n :is_double => true,\n :from => children, \n :as => singular_reverse_association_id,\n :through => join_name.to_sym, \n :foreign_key => parent_foreign_key, \n :foreign_type_key => parent_foreign_key.to_s.sub(/_id$/, '_type'),\n :singular_reverse_association_id => singular_reverse_association_id,\n :conflicts => conflicts\n }\n \n general_options = Hash[*options._select do |key, value|\n collection_option_keys[association_id].include? key and !value.nil?\n end.map do |key, value|\n [key.to_s[association_id.to_s.length+1..-1].to_sym, value]\n end._flatten_once] # rename side-specific options to general names\n \n general_options.each do |key, value|\n # avoid clobbering keys that appear in both option sets\n if internal_options[key]\n general_options[key] = Array(value) + Array(internal_options[key])\n end\n end\n\n parent_class.send(:has_many_polymorphs, association_id, internal_options.merge(general_options))\n \n if conflicts.include? plural_parent_name \n # unify the alternate sides of the conflicting children\n (conflicts).each do |method_name|\n unless parent_class.instance_methods.include?(method_name)\n parent_class.send(:define_method, method_name) do\n (self.send(\"#{singular_reverse_association_id}_#{method_name}\") + \n self.send(\"#{association_id._singularize}_#{method_name}\")).freeze\n end\n end \n end \n \n # unify the join model... join model is always renamed for doubles, unlike child associations\n unless parent_class.instance_methods.include?(join_name)\n parent_class.send(:define_method, join_name) do\n (self.send(\"#{join_name}_as_#{singular_reverse_association_id}\") + \n self.send(\"#{join_name}_as_#{association_id._singularize}\")).freeze\n end \n end \n else\n unless parent_class.instance_methods.include?(join_name)\n # ensure there are no forward slashes in the aliased join_name_method (occurs when namespaces are used)\n join_name_method = join_name.to_s.gsub('/', '_').to_sym\n parent_class.send(:alias_method, join_name_method, \"#{join_name_method}_as_#{singular_reverse_association_id}\")\n end\n end \n \n end\n end\n end\n \n private\n \n def extract_double_collections(options)\n collections = options._select do |key, value| \n value.is_a? Array and key.to_s !~ /(#{RESERVED_DOUBLES_KEYS.map(&:to_s).join('|')})$/\n end\n \n raise PolymorphicError, \"Couldn't understand options in acts_as_double_polymorphic_join. Valid parameters are your two class collections, and then #{RESERVED_DOUBLES_KEYS.inspect[1..-2]}, with optionally your collection names prepended and joined with an underscore.\" unless collections.size == 2\n \n options = options._select do |key, value| \n !collections[key]\n end\n \n [collections, options]\n end\n \n def make_general_option_keys_specific!(options, collections)\n collection_option_keys = Hash[*collections.keys.map do |key|\n [key, RESERVED_DOUBLES_KEYS.map{|option| \"#{key}_#{option}\".to_sym}] \n end._flatten_once] \n \n collections.keys.each do |collection| \n options.each do |key, value|\n next if collection_option_keys.values.flatten.include? key\n # shift the general options to the individual sides\n collection_key = \"#{collection}_#{key}\".to_sym\n collection_value = options[collection_key]\n case key\n when :conditions\n collection_value, value = sanitize_sql(collection_value), sanitize_sql(value)\n options[collection_key] = (collection_value ? \"(#{collection_value}) AND (#{value})\" : value)\n when :order\n options[collection_key] = (collection_value ? \"#{collection_value}, #{value}\" : value)\n when :extend, :join_extend\n options[collection_key] = Array(collection_value) + Array(value)\n else\n options[collection_key] ||= value\n end \n end\n end\n \n collection_option_keys\n end\n \n \n \n public\n\n=begin rdoc\n\nThis method createds a single-sided polymorphic relationship. \n\n class Petfood < ActiveRecord::Base\n has_many_polymorphs :eaters, :from => [:dogs, :cats, :birds]\n end\n\nThe only required parameter, aside from the association name, is :from. \n\nThe method generates a number of associations aside from the polymorphic one. In this example Petfood also gets dogs, cats, and birds, and Dog, Cat, and Bird get petfoods. (The reverse association to the parents is always plural.)\n\n== Available options\n\n:from:: An array of symbols representing the target models. Required.\n:as:: A symbol for the parent's interface in the join--what the parent 'acts as'.\n:through:: A symbol representing the class of the join model. Follows Rails defaults if not supplied (the parent and the association names, alphabetized, concatenated with an underscore, and singularized).\n:dependent:: Accepts :destroy, :nullify, :delete_all. Controls how the join record gets treated on any associate delete (whether from the polymorph or from an individual collection); defaults to :destroy.\n:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true.\n:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with \"_of_#{association_name}\". For example, zoos becomes zoos_of_animals. This is to help avoid method name collisions in crowded classes.\n:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).\n:join_extend:: One or an array of mixed modules and procs, which are applied to the join association.\n:parent_extend:: One or an array of mixed modules and procs, which are applied to the target models' association to the parents.\n:conditions:: An array or string of conditions for the SQL WHERE clause. \n:parent_conditions:: An array or string of conditions which are applied to the target models' association to the parents.\n:order:: A string for the SQL ORDER BY clause.\n:parent_order:: A string for the SQL ORDER BY which is applied to the target models' association to the parents.\n:group:: An array or string of conditions for the SQL GROUP BY clause. Affects the polymorphic and individual associations.\n:limit:: An integer. Affects the polymorphic and individual associations.\n:offset:: An integer. Only affects the polymorphic association.\n:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default.\n:uniq:: If true, the records returned are passed through a pure-Ruby uniq before they are returned. Rarely needed.\n:foreign_key:: The column name for the parent's id in the join. \n:foreign_type_key:: The column name for the parent's class name in the join, if the parent itself is polymorphic. Rarely needed--if you're thinking about using this, you almost certainly want to use acts_as_double_polymorphic_join() instead.\n:polymorphic_key:: The column name for the child's id in the join.\n:polymorphic_type_key:: The column name for the child's class name in the join.\n\nIf you pass a block, it gets converted to a Proc and added to :extend. \n\n== On condition nullification\n\nWhen you request an individual association, non-applicable but fully-qualified fields in the polymorphic association's :conditions, :order, and :group options get changed to NULL. For example, if you set :conditions => \"dogs.name != 'Spot'\", when you request .cats, the conditions string is changed to NULL != 'Spot'. \n\nBe aware, however, that NULL != 'Spot' returns false due to SQL's 3-value logic. Instead, you need to use the :conditions string \"dogs.name IS NULL OR dogs.name != 'Spot'\" to get the behavior you probably expect for negative matches.\n\n=end\n\n def has_many_polymorphs (association_id, options = {}, &extension)\n _logger_debug \"associating #{self}.#{association_id}\"\n reflection = create_has_many_polymorphs_reflection(association_id, options, &extension)\n # puts \"Created reflection #{reflection.inspect}\"\n # configure_dependency_for_has_many(reflection)\n collection_reader_method(reflection, PolymorphicAssociation)\n end\n \n # Composed method that assigns option defaults, builds the reflection object, and sets up all the related associations on the parent, join, and targets.\n def create_has_many_polymorphs_reflection(association_id, options, &extension) #:nodoc:\n options.assert_valid_keys(\n :from,\n :as,\n :through,\n :foreign_key,\n :foreign_type_key,\n :polymorphic_key, # same as :association_foreign_key\n :polymorphic_type_key,\n :dependent, # default :destroy, only affects the join table\n :skip_duplicates, # default true, only affects the polymorphic collection\n :ignore_duplicates, # deprecated\n :is_double,\n :rename_individual_collections,\n :reverse_association_id, # not used\n :singular_reverse_association_id,\n :conflicts,\n :extend,\n :join_class_name,\n :join_extend,\n :parent_extend,\n :table_aliases,\n :select, # applies to the polymorphic relationship\n :conditions, # applies to the polymorphic relationship, the children, and the join\n # :include,\n :parent_conditions,\n :parent_order,\n :order, # applies to the polymorphic relationship, the children, and the join\n :group, # only applies to the polymorphic relationship and the children\n :limit, # only applies to the polymorphic relationship and the children\n :offset, # only applies to the polymorphic relationship\n :parent_order,\n :parent_group,\n :parent_limit,\n :parent_offset,\n # :source,\n :namespace,\n :uniq, # XXX untested, only applies to the polymorphic relationship\n # :finder_sql,\n # :counter_sql,\n # :before_add,\n # :after_add,\n # :before_remove,\n # :after_remove\n :dummy)\n \n # validate against the most frequent configuration mistakes\n verify_pluralization_of(association_id) \n raise PolymorphicError, \":from option must be an array\" unless options[:from].is_a? Array \n options[:from].each{|plural| verify_pluralization_of(plural)}\n \n options[:as] ||= self.name.demodulize.underscore.to_sym\n options[:conflicts] = Array(options[:conflicts]) \n options[:foreign_key] ||= \"#{options[:as]}_id\"\n \n options[:association_foreign_key] = \n options[:polymorphic_key] ||= \"#{association_id._singularize}_id\"\n options[:polymorphic_type_key] ||= \"#{association_id._singularize}_type\"\n \n if options.has_key? :ignore_duplicates\n _logger_warn \"DEPRECATION WARNING: please use :skip_duplicates instead of :ignore_duplicates\"\n options[:skip_duplicates] = options[:ignore_duplicates]\n end\n options[:skip_duplicates] = true unless options.has_key? :skip_duplicates\n options[:dependent] = :destroy unless options.has_key? :dependent\n options[:conditions] = sanitize_sql(options[:conditions])\n \n # options[:finder_sql] ||= \"(options[:polymorphic_key]\n \n options[:through] ||= build_join_table_symbol(association_id, (options[:as]._pluralize or self.table_name))\n \n # set up namespaces if we have a namespace key\n # XXX needs test coverage\n if options[:namespace]\n namespace = options[:namespace].to_s.chomp(\"/\") + \"/\"\n options[:from].map! do |child|\n \"#{namespace}#{child}\".to_sym\n end\n options[:through] = \"#{namespace}#{options[:through]}\".to_sym\n end\n \n options[:join_class_name] ||= options[:through]._classify \n options[:table_aliases] ||= build_table_aliases([options[:through]] + options[:from])\n options[:select] ||= build_select(association_id, options[:table_aliases]) \n \n options[:through] = \"#{options[:through]}_as_#{options[:singular_reverse_association_id]}\" if options[:singular_reverse_association_id]\n options[:through] = demodulate(options[:through]).to_sym\n \n options[:extend] = spiked_create_extension_module(association_id, Array(options[:extend]) + Array(extension)) \n options[:join_extend] = spiked_create_extension_module(association_id, Array(options[:join_extend]), \"Join\") \n options[:parent_extend] = spiked_create_extension_module(association_id, Array(options[:parent_extend]), \"Parent\") \n \n # create the reflection object \n returning(create_reflection(:has_many_polymorphs, association_id, options, self)) do |reflection| \n # set up the other related associations \n create_join_association(association_id, reflection)\n create_has_many_through_associations_for_parent_to_children(association_id, reflection)\n create_has_many_through_associations_for_children_to_parent(association_id, reflection) \n end \n end\n \n private\n \n\n # table mapping for use at the instantiation point \n \n def build_table_aliases(from)\n # for the targets\n returning({}) do |aliases|\n from.map(&:to_s).sort.map(&:to_sym).each_with_index do |plural, t_index|\n begin\n table = plural._as_class.table_name\n rescue NameError => e\n raise PolymorphicError, \"Could not find a valid class for #{plural.inspect} (tried #{plural.to_s._classify}). If it's namespaced, be sure to specify it as :\\\"module/#{plural}\\\" instead.\"\n end\n begin\n plural._as_class.columns.map(&:name).each_with_index do |field, f_index|\n aliases[\"#{table}.#{field}\"] = \"t#{t_index}_r#{f_index}\"\n end\n rescue ActiveRecord::StatementInvalid => e\n _logger_warn \"Looks like your table doesn't exist for #{plural.to_s._classify}.\\nError #{e}\\nSkipping...\"\n end\n end\n end\n end\n \n def build_select(association_id, aliases)\n # instantiate has to know which reflection the results are coming from\n ([\"\\'#{self.name}\\' AS polymorphic_parent_class\", \n \"\\'#{association_id}\\' AS polymorphic_association_id\"] + \n aliases.map do |table, _alias|\n \"#{table} AS #{_alias}\"\n end.sort).join(\", \")\n end\n \n # method sub-builders\n \n def create_join_association(association_id, reflection)\n \n options = {\n :foreign_key => reflection.options[:foreign_key], \n :dependent => reflection.options[:dependent], \n :class_name => reflection.klass.name, \n :extend => reflection.options[:join_extend]\n # :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n # :order => devolve(association_id, reflection, reflection.options[:order], reflection.klass, true),\n # :conditions => devolve(association_id, reflection, reflection.options[:conditions], reflection.klass, true)\n }\n \n if reflection.options[:foreign_type_key] \n type_check = \"#{reflection.options[:join_class_name].constantize.quoted_table_name}.#{reflection.options[:foreign_type_key]} = #{quote_value(self.base_class.name)}\"\n conjunction = options[:conditions] ? \" AND \" : nil\n options[:conditions] = \"#{options[:conditions]}#{conjunction}#{type_check}\"\n options[:as] = reflection.options[:as]\n end\n \n has_many(reflection.options[:through], options)\n \n inject_before_save_into_join_table(association_id, reflection) \n end\n \n def inject_before_save_into_join_table(association_id, reflection)\n sti_hook = \"sti_class_rewrite\"\n rewrite_procedure = %[self.send(:#{reflection.options[:polymorphic_type_key]}=, self.#{reflection.options[:polymorphic_type_key]}.constantize.base_class.name)]\n \n # XXX should be abstracted?\n reflection.klass.class_eval %[ \n unless instance_methods.include? \"before_save_with_#{sti_hook}\"\n if instance_methods.include? \"before_save\" \n alias_method :before_save_without_#{sti_hook}, :before_save \n def before_save_with_#{sti_hook}\n before_save_without_#{sti_hook}\n #{rewrite_procedure}\n end\n else\n def before_save_with_#{sti_hook}\n #{rewrite_procedure}\n end \n end\n alias_method :before_save, :before_save_with_#{sti_hook}\n end\n ] \n end\n \n def create_has_many_through_associations_for_children_to_parent(association_id, reflection)\n \n child_pluralization_map(association_id, reflection).each do |plural, singular|\n if singular == reflection.options[:as]\n raise PolymorphicError, if reflection.options[:is_double]\n \"You can't give either of the sides in a double-polymorphic join the same name as any of the individual target classes.\"\n else\n \"You can't have a self-referential polymorphic has_many :through without renaming the non-polymorphic foreign key in the join model.\" \n end\n end\n \n parent = self\n plural._as_class.instance_eval do \n # this shouldn't be called at all during doubles; there is no way to traverse to a double polymorphic parent (XXX is that right?)\n unless reflection.options[:is_double] or reflection.options[:conflicts].include? self.name.tableize.to_sym \n \n # the join table\n through = \"#{reflection.options[:through]}#{'_as_child' if parent == self}\".to_sym\n has_many(through,\n :as => association_id._singularize, \n# :source => association_id._singularize, \n# :source_type => reflection.options[:polymorphic_type_key], \n :class_name => reflection.klass.name,\n :dependent => reflection.options[:dependent], \n :extend => reflection.options[:join_extend],\n # :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n :order => devolve(association_id, reflection, reflection.options[:parent_order], reflection.klass),\n :conditions => devolve(association_id, reflection, reflection.options[:parent_conditions], reflection.klass)\n )\n \n # the association to the target's parents\n association = \"#{reflection.options[:as]._pluralize}#{\"_of_#{association_id}\" if reflection.options[:rename_individual_collections]}\".to_sym \n has_many(association, \n :through => through, \n :class_name => parent.name,\n :source => reflection.options[:as], \n :foreign_key => reflection.options[:foreign_key],\n :extend => reflection.options[:parent_extend],\n :conditions => reflection.options[:parent_conditions],\n :order => reflection.options[:parent_order],\n :offset => reflection.options[:parent_offset],\n :limit => reflection.options[:parent_limit],\n :group => reflection.options[:parent_group])\n \n# debugger if association == :parents\n# \n# nil\n \n end \n end\n end\n end\n \n def create_has_many_through_associations_for_parent_to_children(association_id, reflection)\n child_pluralization_map(association_id, reflection).each do |plural, singular|\n #puts \":source => #{child}\"\n current_association = demodulate(child_association_map(association_id, reflection)[plural])\n source = demodulate(singular)\n \n if reflection.options[:conflicts].include? plural\n # XXX check this\n current_association = \"#{association_id._singularize}_#{current_association}\" if reflection.options[:conflicts].include? self.name.tableize.to_sym\n source = \"#{source}_as_#{association_id._singularize}\".to_sym\n end \n \n # make push/delete accessible from the individual collections but still operate via the general collection\n extension_module = self.class_eval %[\n module #{self.name + current_association._classify + \"PolymorphicChildAssociationExtension\"}\n def push *args; proxy_owner.send(:#{association_id}).send(:push, *args); self; end \n alias :<< :push\n def delete *args; proxy_owner.send(:#{association_id}).send(:delete, *args); end\n def clear; proxy_owner.send(:#{association_id}).send(:clear, #{singular._classify}); end\n self\n end] \n \n has_many(current_association.to_sym, \n :through => reflection.options[:through], \n :source => association_id._singularize,\n :source_type => plural._as_class.base_class.name,\n :class_name => plural._as_class.name, # make STI not conflate subtypes\n :extend => (Array(extension_module) + reflection.options[:extend]),\n :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n :order => devolve(association_id, reflection, reflection.options[:order], plural._as_class),\n :conditions => devolve(association_id, reflection, reflection.options[:conditions], plural._as_class),\n :group => devolve(association_id, reflection, reflection.options[:group], plural._as_class)\n )\n \n end\n end\n \n # some support methods\n \n def child_pluralization_map(association_id, reflection)\n Hash[*reflection.options[:from].map do |plural|\n [plural, plural._singularize]\n end.flatten]\n end\n \n def child_association_map(association_id, reflection) \n Hash[*reflection.options[:from].map do |plural|\n [plural, \"#{association_id._singularize.to_s + \"_\" if reflection.options[:rename_individual_collections]}#{plural}\".to_sym]\n end.flatten]\n end \n \n def demodulate(s)\n s.to_s.gsub('/', '_').to_sym\n end\n \n def build_join_table_symbol(association_id, name)\n [name.to_s, association_id.to_s].sort.join(\"_\").to_sym\n end\n \n def all_classes_for(association_id, reflection)\n klasses = [self, reflection.klass, *child_pluralization_map(association_id, reflection).keys.map(&:_as_class)]\n klasses += klasses.map(&:base_class)\n klasses.uniq\n end\n \n def devolve(association_id, reflection, string, klass, remove_inappropriate_clauses = false) \n # XXX remove_inappropriate_clauses is not implemented; we'll wait until someone actually needs it\n return unless string\n string = string.dup\n # _logger_debug \"devolving #{string} for #{klass}\"\n inappropriate_classes = (all_classes_for(association_id, reflection) - # the join class must always be preserved\n [klass, klass.base_class, reflection.klass, reflection.klass.base_class])\n inappropriate_classes.map do |klass|\n klass.columns.map do |column| \n [klass.table_name, column.name]\n end.map do |table, column|\n [\"#{table}.#{column}\", \"`#{table}`.#{column}\", \"#{table}.`#{column}`\", \"`#{table}`.`#{column}`\"]\n end\n end.flatten.sort_by(&:size).reverse.each do |quoted_reference| \n # _logger_debug \"devolved #{quoted_reference} to NULL\"\n # XXX clause removal would go here \n string.gsub!(quoted_reference, \"NULL\")\n end\n # _logger_debug \"altered to #{string}\"\n string\n end\n \n def verify_pluralization_of(sym)\n sym = sym.to_s\n singular = sym.singularize\n plural = singular.pluralize\n raise PolymorphicError, \"Pluralization rules not set up correctly. You passed :#{sym}, which singularizes to :#{singular}, but that pluralizes to :#{plural}, which is different. Maybe you meant :#{plural} to begin with?\" unless sym == plural\n end \n \n def spiked_create_extension_module(association_id, extensions, identifier = nil) \n module_extensions = extensions.select{|e| e.is_a? Module}\n proc_extensions = extensions.select{|e| e.is_a? Proc }\n \n # support namespaced anonymous blocks as well as multiple procs\n proc_extensions.each_with_index do |proc_extension, index|\n module_name = \"#{self.to_s}#{association_id._classify}Polymorphic#{identifier}AssociationExtension#{index}\"\n the_module = self.class_eval \"module #{module_name}; self; end\" # XXX hrm\n the_module.class_eval &proc_extension\n module_extensions << the_module\n end\n module_extensions\n end\n \n end\n end\nend\n", "file_after": "module ActiveRecord #:nodoc:\n module Associations #:nodoc:\n\n=begin rdoc\n\nClass methods added to ActiveRecord::Base for setting up polymorphic associations.\n\n== Notes\n\nSTI association targets must enumerated and named. For example, if Dog and Cat both inherit from Animal, you still need to say [:dogs, :cats], and not [:animals].\n\nNamespaced models follow the Rails underscore convention. ZooAnimal::Lion becomes :'zoo_animal/lion'.\n\nYou do not need to set up any other associations other than for either the regular method or the double. The join associations and all individual and reverse associations are generated for you. However, a join model and table are required.\n\nThere is a tentative report that you can make the parent model be its own join model, but this is untested.\n\n=end\n module PolymorphicClassMethods\n\n RESERVED_DOUBLES_KEYS = [:conditions, :order, :limit, :offset, :extend, :skip_duplicates,\n :join_extend, :dependent, :rename_individual_collections,\n :namespace] #:nodoc:\n\n=begin rdoc\n\nThis method creates a doubled-sided polymorphic relationship. It must be called on the join model:\n\n class Devouring < ActiveRecord::Base\n belongs_to :eater, :polymorphic => true\n belongs_to :eaten, :polymorphic => true\n\n acts_as_double_polymorphic_join(\n :eaters => [:dogs, :cats],\n :eatens => [:cats, :birds]\n )\n end\n\nThe method works by defining one or more special has_many_polymorphs association on every model in the target lists, depending on which side of the association it is on. Double self-references will work.\n\nThe two association names and their value arrays are the only required parameters.\n\n== Available options\n\nThese options are passed through to targets on both sides of the association. If you want to affect only one side, prepend the key with the name of that side. For example, :eaters_extend.\n\n:dependent:: Accepts :destroy, :nullify, or :delete_all. Controls how the join record gets treated on any association delete (whether from the polymorph or from an individual collection); defaults to :destroy.\n:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true.\n:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with \"\\_of_#{association_name}\".\n:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).\n:join_extend:: One or an array of mixed modules and procs, which are applied to the join association.\n:conditions:: An array or string of conditions for the SQL WHERE clause.\n:order:: A string for the SQL ORDER BY clause.\n:limit:: An integer. Affects the polymorphic and individual associations.\n:offset:: An integer. Only affects the polymorphic association.\n:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default.\n\n=end\n def acts_as_double_polymorphic_join options={}, &extension\n\n collections, options = extract_double_collections(options)\n\n # handle the block\n options[:extend] = (if options[:extend]\n Array(options[:extend]) + [extension]\n else\n extension\n end) if extension\n\n collection_option_keys = make_general_option_keys_specific!(options, collections)\n\n join_name = self.name.tableize.to_sym\n collections.each do |association_id, children|\n parent_hash_key = (collections.keys - [association_id]).first # parents are the entries in the _other_ children array\n\n begin\n parent_foreign_key = self.reflect_on_association(parent_hash_key._singularize).primary_key_name\n rescue NoMethodError\n raise PolymorphicError, \"Couldn't find 'belongs_to' association for :#{parent_hash_key._singularize} in #{self.name}.\" unless parent_foreign_key\n end\n\n parents = collections[parent_hash_key]\n conflicts = (children & parents) # set intersection\n parents.each do |plural_parent_name|\n\n parent_class = plural_parent_name._as_class\n singular_reverse_association_id = parent_hash_key._singularize\n\n internal_options = {\n :is_double => true,\n :from => children,\n :as => singular_reverse_association_id,\n :through => join_name.to_sym,\n :foreign_key => parent_foreign_key,\n :foreign_type_key => parent_foreign_key.to_s.sub(/_id$/, '_type'),\n :singular_reverse_association_id => singular_reverse_association_id,\n :conflicts => conflicts\n }\n\n general_options = Hash[*options._select do |key, value|\n collection_option_keys[association_id].include? key and !value.nil?\n end.map do |key, value|\n [key.to_s[association_id.to_s.length+1..-1].to_sym, value]\n end._flatten_once] # rename side-specific options to general names\n\n general_options.each do |key, value|\n # avoid clobbering keys that appear in both option sets\n if internal_options[key]\n general_options[key] = Array(value) + Array(internal_options[key])\n end\n end\n\n parent_class.send(:has_many_polymorphs, association_id, internal_options.merge(general_options))\n\n if conflicts.include? plural_parent_name\n # unify the alternate sides of the conflicting children\n (conflicts).each do |method_name|\n unless parent_class.instance_methods.include?(method_name)\n parent_class.send(:define_method, method_name) do\n (self.send(\"#{singular_reverse_association_id}_#{method_name}\") +\n self.send(\"#{association_id._singularize}_#{method_name}\")).freeze\n end\n end\n end\n\n # unify the join model... join model is always renamed for doubles, unlike child associations\n unless parent_class.instance_methods.include?(join_name)\n parent_class.send(:define_method, join_name) do\n (self.send(\"#{join_name}_as_#{singular_reverse_association_id}\") +\n self.send(\"#{join_name}_as_#{association_id._singularize}\")).freeze\n end\n end\n else\n unless parent_class.instance_methods.include?(join_name)\n # ensure there are no forward slashes in the aliased join_name_method (occurs when namespaces are used)\n join_name_method = join_name.to_s.gsub('/', '_').to_sym\n parent_class.send(:alias_method, join_name_method, \"#{join_name_method}_as_#{singular_reverse_association_id}\")\n end\n end\n\n end\n end\n end\n\n=begin rdoc\n\nThis method createds a single-sided polymorphic relationship.\n\n class Petfood < ActiveRecord::Base\n has_many_polymorphs :eaters, :from => [:dogs, :cats, :birds]\n end\n\nThe only required parameter, aside from the association name, is :from.\n\nThe method generates a number of associations aside from the polymorphic one. In this example Petfood also gets dogs, cats, and birds, and Dog, Cat, and Bird get petfoods. (The reverse association to the parents is always plural.)\n\n== Available options\n\n:from:: An array of symbols representing the target models. Required.\n:as:: A symbol for the parent's interface in the join--what the parent 'acts as'.\n:through:: A symbol representing the class of the join model. Follows Rails defaults if not supplied (the parent and the association names, alphabetized, concatenated with an underscore, and singularized).\n:dependent:: Accepts :destroy, :nullify, :delete_all. Controls how the join record gets treated on any associate delete (whether from the polymorph or from an individual collection); defaults to :destroy.\n:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true.\n:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with \"_of_#{association_name}\". For example, zoos becomes zoos_of_animals. This is to help avoid method name collisions in crowded classes.\n:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).\n:join_extend:: One or an array of mixed modules and procs, which are applied to the join association.\n:parent_extend:: One or an array of mixed modules and procs, which are applied to the target models' association to the parents.\n:conditions:: An array or string of conditions for the SQL WHERE clause.\n:parent_conditions:: An array or string of conditions which are applied to the target models' association to the parents.\n:order:: A string for the SQL ORDER BY clause.\n:parent_order:: A string for the SQL ORDER BY which is applied to the target models' association to the parents.\n:group:: An array or string of conditions for the SQL GROUP BY clause. Affects the polymorphic and individual associations.\n:limit:: An integer. Affects the polymorphic and individual associations.\n:offset:: An integer. Only affects the polymorphic association.\n:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default.\n:uniq:: If true, the records returned are passed through a pure-Ruby uniq before they are returned. Rarely needed.\n:foreign_key:: The column name for the parent's id in the join.\n:foreign_type_key:: The column name for the parent's class name in the join, if the parent itself is polymorphic. Rarely needed--if you're thinking about using this, you almost certainly want to use acts_as_double_polymorphic_join() instead.\n:polymorphic_key:: The column name for the child's id in the join.\n:polymorphic_type_key:: The column name for the child's class name in the join.\n\nIf you pass a block, it gets converted to a Proc and added to :extend.\n\n== On condition nullification\n\nWhen you request an individual association, non-applicable but fully-qualified fields in the polymorphic association's :conditions, :order, and :group options get changed to NULL. For example, if you set :conditions => \"dogs.name != 'Spot'\", when you request .cats, the conditions string is changed to NULL != 'Spot'.\n\nBe aware, however, that NULL != 'Spot' returns false due to SQL's 3-value logic. Instead, you need to use the :conditions string \"dogs.name IS NULL OR dogs.name != 'Spot'\" to get the behavior you probably expect for negative matches.\n\n=end\n def has_many_polymorphs(association_id, options = {}, &extension)\n _logger_debug \"associating #{self}.#{association_id}\"\n reflection = create_has_many_polymorphs_reflection(association_id, options, &extension)\n # puts \"Created reflection #{reflection.inspect}\"\n # configure_dependency_for_has_many(reflection)\n collection_reader_method(reflection, PolymorphicAssociation)\n end\n\n # Composed method that assigns option defaults, builds the reflection\n # object, and sets up all the related associations on the parent, join,\n # and targets.\n def create_has_many_polymorphs_reflection(association_id, options, &extension) #:nodoc:\n options.assert_valid_keys(\n :from,\n :as,\n :through,\n :foreign_key,\n :foreign_type_key,\n :polymorphic_key, # same as :association_foreign_key\n :polymorphic_type_key,\n :dependent, # default :destroy, only affects the join table\n :skip_duplicates, # default true, only affects the polymorphic collection\n :ignore_duplicates, # deprecated\n :is_double,\n :rename_individual_collections,\n :reverse_association_id, # not used\n :singular_reverse_association_id,\n :conflicts,\n :extend,\n :join_class_name,\n :join_extend,\n :parent_extend,\n :table_aliases,\n :select, # applies to the polymorphic relationship\n :conditions, # applies to the polymorphic relationship, the children, and the join\n # :include,\n :parent_conditions,\n :parent_order,\n :order, # applies to the polymorphic relationship, the children, and the join\n :group, # only applies to the polymorphic relationship and the children\n :limit, # only applies to the polymorphic relationship and the children\n :offset, # only applies to the polymorphic relationship\n :parent_order,\n :parent_group,\n :parent_limit,\n :parent_offset,\n # :source,\n :namespace,\n :uniq, # XXX untested, only applies to the polymorphic relationship\n # :finder_sql,\n # :counter_sql,\n # :before_add,\n # :after_add,\n # :before_remove,\n # :after_remove\n :dummy\n )\n\n # validate against the most frequent configuration mistakes\n verify_pluralization_of(association_id)\n raise PolymorphicError, \":from option must be an array\" unless options[:from].is_a? Array\n options[:from].each{|plural| verify_pluralization_of(plural)}\n\n options[:as] ||= self.name.demodulize.underscore.to_sym\n options[:conflicts] = Array(options[:conflicts])\n options[:foreign_key] ||= \"#{options[:as]}_id\"\n\n options[:association_foreign_key] =\n options[:polymorphic_key] ||= \"#{association_id._singularize}_id\"\n options[:polymorphic_type_key] ||= \"#{association_id._singularize}_type\"\n\n if options.has_key? :ignore_duplicates\n _logger_warn \"DEPRECATION WARNING: please use :skip_duplicates instead of :ignore_duplicates\"\n options[:skip_duplicates] = options[:ignore_duplicates]\n end\n options[:skip_duplicates] = true unless options.has_key? :skip_duplicates\n options[:dependent] = :destroy unless options.has_key? :dependent\n options[:conditions] = sanitize_sql(options[:conditions])\n\n # options[:finder_sql] ||= \"(options[:polymorphic_key]\n\n options[:through] ||= build_join_table_symbol(association_id, (options[:as]._pluralize or self.table_name))\n\n # set up namespaces if we have a namespace key\n # XXX needs test coverage\n if options[:namespace]\n namespace = options[:namespace].to_s.chomp(\"/\") + \"/\"\n options[:from].map! do |child|\n \"#{namespace}#{child}\".to_sym\n end\n options[:through] = \"#{namespace}#{options[:through]}\".to_sym\n end\n\n options[:join_class_name] ||= options[:through]._classify\n options[:table_aliases] ||= build_table_aliases([options[:through]] + options[:from])\n options[:select] ||= build_select(association_id, options[:table_aliases])\n\n options[:through] = \"#{options[:through]}_as_#{options[:singular_reverse_association_id]}\" if options[:singular_reverse_association_id]\n options[:through] = demodulate(options[:through]).to_sym\n\n options[:extend] = spiked_create_extension_module(association_id, Array(options[:extend]) + Array(extension))\n options[:join_extend] = spiked_create_extension_module(association_id, Array(options[:join_extend]), \"Join\")\n options[:parent_extend] = spiked_create_extension_module(association_id, Array(options[:parent_extend]), \"Parent\")\n\n # create the reflection object\n create_reflection(:has_many_polymorphs, association_id, options, self).tap do |reflection|\n # set up the other related associations\n create_join_association(association_id, reflection)\n create_has_many_through_associations_for_parent_to_children(association_id, reflection)\n create_has_many_through_associations_for_children_to_parent(association_id, reflection)\n end\n end\n\n private\n\n def extract_double_collections(options)\n collections = options._select do |key, value|\n value.is_a? Array and key.to_s !~ /(#{RESERVED_DOUBLES_KEYS.map(&:to_s).join('|')})$/\n end\n\n raise PolymorphicError, \"Couldn't understand options in acts_as_double_polymorphic_join. Valid parameters are your two class collections, and then #{RESERVED_DOUBLES_KEYS.inspect[1..-2]}, with optionally your collection names prepended and joined with an underscore.\" unless collections.size == 2\n\n options = options._select do |key, value|\n !collections[key]\n end\n\n [collections, options]\n end\n\n def make_general_option_keys_specific!(options, collections)\n collection_option_keys = Hash[*collections.keys.map do |key|\n [key, RESERVED_DOUBLES_KEYS.map{|option| \"#{key}_#{option}\".to_sym}]\n end._flatten_once]\n\n collections.keys.each do |collection|\n options.each do |key, value|\n next if collection_option_keys.values.flatten.include? key\n # shift the general options to the individual sides\n collection_key = \"#{collection}_#{key}\".to_sym\n collection_value = options[collection_key]\n case key\n when :conditions\n collection_value, value = sanitize_sql(collection_value), sanitize_sql(value)\n options[collection_key] = (collection_value ? \"(#{collection_value}) AND (#{value})\" : value)\n when :order\n options[collection_key] = (collection_value ? \"#{collection_value}, #{value}\" : value)\n when :extend, :join_extend\n options[collection_key] = Array(collection_value) + Array(value)\n else\n options[collection_key] ||= value\n end\n end\n end\n\n collection_option_keys\n end\n\n # table mapping for use at the instantiation point\n\n def build_table_aliases(from)\n # for the targets\n {}.tap do |aliases|\n from.map(&:to_s).sort.map(&:to_sym).each_with_index do |plural, t_index|\n begin\n table = plural._as_class.table_name\n rescue NameError => e\n raise PolymorphicError, \"Could not find a valid class for #{plural.inspect} (tried #{plural.to_s._classify}). If it's namespaced, be sure to specify it as :\\\"module/#{plural}\\\" instead.\"\n end\n begin\n plural._as_class.columns.map(&:name).each_with_index do |field, f_index|\n aliases[\"#{table}.#{field}\"] = \"t#{t_index}_r#{f_index}\"\n end\n rescue ActiveRecord::StatementInvalid => e\n _logger_warn \"Looks like your table doesn't exist for #{plural.to_s._classify}.\\nError #{e}\\nSkipping...\"\n end\n end\n end\n end\n\n def build_select(association_id, aliases)\n # instantiate has to know which reflection the results are coming from\n ([\"\\'#{self.name}\\' AS polymorphic_parent_class\",\n \"\\'#{association_id}\\' AS polymorphic_association_id\"] +\n aliases.map do |table, _alias|\n \"#{table} AS #{_alias}\"\n end.sort).join(\", \")\n end\n\n # method sub-builders\n\n def create_join_association(association_id, reflection)\n\n options = {\n :foreign_key => reflection.options[:foreign_key],\n :dependent => reflection.options[:dependent],\n :class_name => reflection.klass.name,\n :extend => reflection.options[:join_extend]\n # :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n # :order => devolve(association_id, reflection, reflection.options[:order], reflection.klass, true),\n # :conditions => devolve(association_id, reflection, reflection.options[:conditions], reflection.klass, true)\n }\n\n if reflection.options[:foreign_type_key]\n type_check = \"#{reflection.options[:join_class_name].constantize.quoted_table_name}.#{reflection.options[:foreign_type_key]} = #{quote_value(self.base_class.name)}\"\n conjunction = options[:conditions] ? \" AND \" : nil\n options[:conditions] = \"#{options[:conditions]}#{conjunction}#{type_check}\"\n options[:as] = reflection.options[:as]\n end\n\n has_many(reflection.options[:through], options)\n\n inject_before_save_into_join_table(association_id, reflection)\n end\n\n def inject_before_save_into_join_table(association_id, reflection)\n sti_hook = \"sti_class_rewrite\"\n polymorphic_type_key = reflection.options[:polymorphic_type_key]\n\n reflection.klass.class_eval %{\n unless [self._save_callbacks.map(&:raw_filter)].flatten.include?(:#{sti_hook})\n before_save :#{sti_hook}\n\n def #{sti_hook}\n self.send(:#{polymorphic_type_key}=, self.#{polymorphic_type_key}.constantize.base_class.name)\n end\n end\n }\n end\n\n def create_has_many_through_associations_for_children_to_parent(association_id, reflection)\n\n child_pluralization_map(association_id, reflection).each do |plural, singular|\n if singular == reflection.options[:as]\n raise PolymorphicError, if reflection.options[:is_double]\n \"You can't give either of the sides in a double-polymorphic join the same name as any of the individual target classes.\"\n else\n \"You can't have a self-referential polymorphic has_many :through without renaming the non-polymorphic foreign key in the join model.\"\n end\n end\n\n parent = self\n plural._as_class.instance_eval do\n # this shouldn't be called at all during doubles; there is no way to traverse to a double polymorphic parent (XXX is that right?)\n unless reflection.options[:is_double] or reflection.options[:conflicts].include? self.name.tableize.to_sym\n\n # the join table\n through = \"#{reflection.options[:through]}#{'_as_child' if parent == self}\".to_sym\n has_many(through,\n :as => association_id._singularize,\n# :source => association_id._singularize,\n # :source_type => reflection.options[:polymorphic_type_key],\n :class_name => reflection.klass.name,\n :dependent => reflection.options[:dependent],\n :extend => reflection.options[:join_extend],\n # :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n :order => devolve(association_id, reflection, reflection.options[:parent_order], reflection.klass),\n :conditions => devolve(association_id, reflection, reflection.options[:parent_conditions], reflection.klass)\n )\n\n # the association to the target's parents\n association = \"#{reflection.options[:as]._pluralize}#{\"_of_#{association_id}\" if reflection.options[:rename_individual_collections]}\".to_sym\n has_many(association,\n :through => through,\n :class_name => parent.name,\n :source => reflection.options[:as],\n :foreign_key => reflection.options[:foreign_key],\n :extend => reflection.options[:parent_extend],\n :conditions => reflection.options[:parent_conditions],\n :order => reflection.options[:parent_order],\n :offset => reflection.options[:parent_offset],\n :limit => reflection.options[:parent_limit],\n :group => reflection.options[:parent_group])\n\n# debugger if association == :parents\n#\n# nil\n\n end\n end\n end\n end\n\n def create_has_many_through_associations_for_parent_to_children(association_id, reflection)\n child_pluralization_map(association_id, reflection).each do |plural, singular|\n #puts \":source => #{child}\"\n current_association = demodulate(child_association_map(association_id, reflection)[plural])\n source = demodulate(singular)\n\n if reflection.options[:conflicts].include? plural\n # XXX check this\n current_association = \"#{association_id._singularize}_#{current_association}\" if reflection.options[:conflicts].include? self.name.tableize.to_sym\n source = \"#{source}_as_#{association_id._singularize}\".to_sym\n end\n\n # make push/delete accessible from the individual collections but still operate via the general collection\n extension_module = self.class_eval %[\n module #{self.name + current_association._classify + \"PolymorphicChildAssociationExtension\"}\n def push *args; proxy_owner.send(:#{association_id}).send(:push, *args); self; end\n alias :<< :push\n def delete *args; proxy_owner.send(:#{association_id}).send(:delete, *args); end\n def clear; proxy_owner.send(:#{association_id}).send(:clear, #{singular._classify}); end\n self\n end]\n\n has_many(current_association.to_sym,\n :through => reflection.options[:through],\n :source => association_id._singularize,\n :source_type => plural._as_class.base_class.name,\n :class_name => plural._as_class.name, # make STI not conflate subtypes\n :extend => (Array(extension_module) + reflection.options[:extend]),\n :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n :order => devolve(association_id, reflection, reflection.options[:order], plural._as_class),\n :conditions => devolve(association_id, reflection, reflection.options[:conditions], plural._as_class),\n :group => devolve(association_id, reflection, reflection.options[:group], plural._as_class)\n )\n\n end\n end\n\n # some support methods\n\n def child_pluralization_map(association_id, reflection)\n Hash[*reflection.options[:from].map do |plural|\n [plural, plural._singularize]\n end.flatten]\n end\n\n def child_association_map(association_id, reflection)\n Hash[*reflection.options[:from].map do |plural|\n [plural, \"#{association_id._singularize.to_s + \"_\" if reflection.options[:rename_individual_collections]}#{plural}\".to_sym]\n end.flatten]\n end\n\n def demodulate(s)\n s.to_s.gsub('/', '_').to_sym\n end\n\n def build_join_table_symbol(association_id, name)\n [name.to_s, association_id.to_s].sort.join(\"_\").to_sym\n end\n\n def all_classes_for(association_id, reflection)\n klasses = [self, reflection.klass, *child_pluralization_map(association_id, reflection).keys.map(&:_as_class)]\n klasses += klasses.map(&:base_class)\n klasses.uniq\n end\n\n def devolve(association_id, reflection, string, klass, remove_inappropriate_clauses = false)\n # XXX remove_inappropriate_clauses is not implemented; we'll wait until someone actually needs it\n return unless string\n string = string.dup\n # _logger_debug \"devolving #{string} for #{klass}\"\n inappropriate_classes = (all_classes_for(association_id, reflection) - # the join class must always be preserved\n [klass, klass.base_class, reflection.klass, reflection.klass.base_class])\n inappropriate_classes.map do |klass|\n klass.columns.map do |column|\n [klass.table_name, column.name]\n end.map do |table, column|\n [\"#{table}.#{column}\", \"`#{table}`.#{column}\", \"#{table}.`#{column}`\", \"`#{table}`.`#{column}`\"]\n end\n end.flatten.sort_by(&:size).reverse.each do |quoted_reference|\n # _logger_debug \"devolved #{quoted_reference} to NULL\"\n # XXX clause removal would go here\n string.gsub!(quoted_reference, \"NULL\")\n end\n # _logger_debug \"altered to #{string}\"\n string\n end\n\n def verify_pluralization_of(sym)\n sym = sym.to_s\n singular = sym.singularize\n plural = singular.pluralize\n raise PolymorphicError, \"Pluralization rules not set up correctly. You passed :#{sym}, which singularizes to :#{singular}, but that pluralizes to :#{plural}, which is different. Maybe you meant :#{plural} to begin with?\" unless sym == plural\n end\n\n def spiked_create_extension_module(association_id, extensions, identifier = nil)\n module_extensions = extensions.select{|e| e.is_a? Module}\n proc_extensions = extensions.select{|e| e.is_a? Proc }\n\n # support namespaced anonymous blocks as well as multiple procs\n proc_extensions.each_with_index do |proc_extension, index|\n module_name = \"#{self.to_s}#{association_id._classify}Polymorphic#{identifier}AssociationExtension#{index}\"\n the_module = self.class_eval \"module #{module_name}; self; end\" # XXX hrm\n the_module.class_eval &proc_extension\n module_extensions << the_module\n end\n module_extensions\n end\n end\n end\nend\n"} +{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/reflection.rb", "file_before": "module ActiveRecord #:nodoc:\n module Reflection #:nodoc:\n \n module ClassMethods #:nodoc:\n \n # Update the default reflection switch so that :has_many_polymorphs types get instantiated. \n # It's not a composed method so we have to override the whole thing.\n def create_reflection(macro, name, options, active_record)\n case macro\n when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many\n klass = options[:through] ? ThroughReflection : AssociationReflection\n reflection = klass.new(macro, name, options, active_record)\n when :composed_of\n reflection = AggregateReflection.new(macro, name, options, active_record)\n # added by has_many_polymorphs #\n when :has_many_polymorphs\n reflection = PolymorphicReflection.new(macro, name, options, active_record)\n end\n write_inheritable_hash :reflections, name => reflection\n reflection\n end\n \n end\n\n class PolymorphicError < ActiveRecordError #:nodoc:\n end\n \n=begin rdoc\n\nThe reflection built by the has_many_polymorphs method. \n\nInherits from ActiveRecord::Reflection::AssociationReflection.\n\n=end\n\n class PolymorphicReflection < ThroughReflection\n # Stub out the validity check. Has_many_polymorphs checks validity on macro creation, not on reflection.\n def check_validity! \n # nothing\n end \n\n # Return the source reflection.\n def source_reflection\n # normally is the has_many to the through model, but we return ourselves, \n # since there isn't a real source class for a polymorphic target\n self\n end \n \n # Set the classname of the target. Uses the join class name.\n def class_name\n # normally is the classname of the association target\n @class_name ||= options[:join_class_name]\n end\n \n end\n \n end\nend\n", "file_after": "module ActiveRecord #:nodoc:\n module Reflection #:nodoc:\n\n module ClassMethods #:nodoc:\n\n # Update the default reflection switch so that :has_many_polymorphs types get instantiated.\n # It's not a composed method so we have to override the whole thing.\n def create_reflection(macro, name, options, active_record)\n case macro\n when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many\n klass = options[:through] ? ThroughReflection : AssociationReflection\n reflection = klass.new(macro, name, options, active_record)\n when :composed_of\n reflection = AggregateReflection.new(macro, name, options, active_record)\n # added by has_many_polymorphs #\n when :has_many_polymorphs\n reflection = PolymorphicReflection.new(macro, name, options, active_record)\n end\n write_inheritable_hash :reflections, name => reflection\n reflection\n end\n\n end\n\n class PolymorphicError < ActiveRecordError #:nodoc:\n end\n\n=begin rdoc\n\nThe reflection built by the has_many_polymorphs method.\n\nInherits from ActiveRecord::Reflection::AssociationReflection.\n\n=end\n\n class PolymorphicReflection < ThroughReflection\n # Stub out the validity check. Has_many_polymorphs checks validity on macro creation, not on reflection.\n def check_validity!\n # nothing\n end\n\n # Return the source reflection.\n def source_reflection\n # normally is the has_many to the through model, but we return ourselves,\n # since there isn't a real source class for a polymorphic target\n self\n end\n\n # Set the classname of the target. Uses the join class name.\n def class_name\n # normally is the classname of the association target\n @class_name ||= options[:join_class_name]\n end\n\n end\n\n end\nend\n"} +{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/association.rb", "file_before": "module ActiveRecord #:nodoc:\n module Associations #:nodoc:\n \n class PolymorphicError < ActiveRecordError #:nodoc:\n end \n \n class PolymorphicMethodNotSupportedError < ActiveRecordError #:nodoc:\n end\n \n # The association class for a has_many_polymorphs association.\n class PolymorphicAssociation < HasManyThroughAssociation\n\n # Push a record onto the association. Triggers a database load for a uniqueness check only if :skip_duplicates is true. Return value is undefined.\n def <<(*records)\n return if records.empty?\n\n if @reflection.options[:skip_duplicates]\n _logger_debug \"Loading instances for polymorphic duplicate push check; use :skip_duplicates => false and perhaps a database constraint to avoid this possible performance issue\"\n load_target\n end\n \n @reflection.klass.transaction do\n flatten_deeper(records).each do |record|\n if @owner.new_record? or not record.respond_to?(:new_record?) or record.new_record?\n raise PolymorphicError, \"You can't associate unsaved records.\" \n end\n next if @reflection.options[:skip_duplicates] and @target.include? record\n @owner.send(@reflection.through_reflection.name).proxy_target << @reflection.klass.create!(construct_join_attributes(record))\n @target << record if loaded?\n end\n end\n \n self\n end\n \n alias :push :<<\n alias :concat :<< \n \n # Runs a find against the association contents, returning the matched records. All regular find options except :include are supported.\n def find(*args)\n opts = args._extract_options!\n opts.delete :include\n super(*(args + [opts]))\n end \n \n def construct_scope\n _logger_warn \"Warning; not all usage scenarios for polymorphic scopes are supported yet.\"\n super\n end\n \n # Deletes a record from the association. Return value is undefined.\n def delete(*records)\n records = flatten_deeper(records)\n records.reject! {|record| @target.delete(record) if record.new_record?}\n return if records.empty?\n \n @reflection.klass.transaction do\n records.each do |record|\n joins = @reflection.through_reflection.name\n @owner.send(joins).delete(@owner.send(joins).select do |join|\n join.send(@reflection.options[:polymorphic_key]) == record.id and \n join.send(@reflection.options[:polymorphic_type_key]) == \"#{record.class.base_class}\"\n end)\n @target.delete(record)\n end\n end\n end\n \n # Clears all records from the association. Returns an empty array.\n def clear(klass = nil)\n load_target\n return if @target.empty?\n \n if klass\n delete(@target.select {|r| r.is_a? klass })\n else\n @owner.send(@reflection.through_reflection.name).clear\n @target.clear\n end\n []\n end\n \n protected\n\n# undef :sum\n# undef :create!\n\n def construct_quoted_owner_attributes(*args) #:nodoc:\n # no access to returning() here? why not?\n type_key = @reflection.options[:foreign_type_key]\n h = {@reflection.primary_key_name => @owner.id}\n h[type_key] = @owner.class.base_class.name if type_key\n h\n end\n\n def construct_from #:nodoc:\n # build the FROM part of the query, in this case, the polymorphic join table\n @reflection.klass.quoted_table_name\n end\n\n def construct_owner #:nodoc:\n # the table name for the owner object's class\n @owner.class.quoted_table_name\n end\n \n def construct_owner_key #:nodoc:\n # the primary key field for the owner object\n @owner.class.primary_key\n end\n\n def construct_select(custom_select = nil) #:nodoc:\n # build the select query\n selected = custom_select || @reflection.options[:select]\n end\n\n def construct_joins(custom_joins = nil) #:nodoc:\n # build the string of default joins\n \"JOIN #{construct_owner} AS polymorphic_parent ON #{construct_from}.#{@reflection.options[:foreign_key]} = polymorphic_parent.#{construct_owner_key} \" + \n @reflection.options[:from].map do |plural|\n klass = plural._as_class\n \"LEFT JOIN #{klass.quoted_table_name} ON #{construct_from}.#{@reflection.options[:polymorphic_key]} = #{klass.quoted_table_name}.#{klass.primary_key} AND #{construct_from}.#{@reflection.options[:polymorphic_type_key]} = #{@reflection.klass.quote_value(klass.base_class.name)}\"\n end.uniq.join(\" \") + \" #{custom_joins}\"\n end\n\n def construct_conditions #:nodoc:\n # build the fully realized condition string\n conditions = construct_quoted_owner_attributes.map do |field, value|\n \"#{construct_from}.#{field} = #{@reflection.klass.quote_value(value)}\" if value\n end\n conditions << custom_conditions if custom_conditions\n \"(\" + conditions.compact.join(') AND (') + \")\"\n end\n\n def custom_conditions #:nodoc:\n # custom conditions... not as messy as has_many :through because our joins are a little smarter\n if @reflection.options[:conditions]\n \"(\" + interpolate_sql(@reflection.klass.send(:sanitize_sql, @reflection.options[:conditions])) + \")\"\n end\n end\n\n alias :construct_owner_attributes :construct_quoted_owner_attributes\n alias :conditions :custom_conditions # XXX possibly not necessary\n alias :sql_conditions :custom_conditions # XXX ditto \n\n # construct attributes for join for a particular record\n def construct_join_attributes(record) #:nodoc:\n {@reflection.options[:polymorphic_key] => record.id, \n @reflection.options[:polymorphic_type_key] => \"#{record.class.base_class}\", \n @reflection.options[:foreign_key] => @owner.id}.merge(@reflection.options[:foreign_type_key] ? \n {@reflection.options[:foreign_type_key] => \"#{@owner.class.base_class}\"} : {}) # for double-sided relationships\n end\n \n def build(attrs = nil) #:nodoc:\n raise PolymorphicMethodNotSupportedError, \"You can't associate new records.\"\n end \n\n end \n \n end\nend\n", "file_after": "module ActiveRecord #:nodoc:\n module Associations #:nodoc:\n\n class PolymorphicError < ActiveRecordError #:nodoc:\n end\n\n class PolymorphicMethodNotSupportedError < ActiveRecordError #:nodoc:\n end\n\n # The association class for a has_many_polymorphs association.\n class PolymorphicAssociation < HasManyThroughAssociation\n\n # Push a record onto the association. Triggers a database load for a uniqueness check only if :skip_duplicates is true. Return value is undefined.\n def <<(*records)\n return if records.empty?\n\n if @reflection.options[:skip_duplicates]\n _logger_debug \"Loading instances for polymorphic duplicate push check; use :skip_duplicates => false and perhaps a database constraint to avoid this possible performance issue\"\n load_target\n end\n\n @reflection.klass.transaction do\n flatten_deeper(records).each do |record|\n if @owner.new_record? or not record.respond_to?(:new_record?) or record.new_record?\n raise PolymorphicError, \"You can't associate unsaved records.\"\n end\n next if @reflection.options[:skip_duplicates] and @target.include? record\n @owner.send(@reflection.through_reflection.name).proxy_target << @reflection.klass.create!(construct_join_attributes(record))\n @target << record if loaded?\n end\n end\n\n self\n end\n\n alias :push :<<\n alias :concat :<<\n\n # Runs a find against the association contents, returning the matched records. All regular find options except :include are supported.\n def find(*args)\n opts = args._extract_options!\n opts.delete :include\n super(*(args + [opts]))\n end\n\n def construct_scope\n _logger_warn \"Warning; not all usage scenarios for polymorphic scopes are supported yet.\"\n super\n end\n\n # Deletes a record from the association. Return value is undefined.\n def delete(*records)\n records = flatten_deeper(records)\n records.reject! {|record| @target.delete(record) if record.new_record?}\n return if records.empty?\n\n @reflection.klass.transaction do\n records.each do |record|\n joins = @reflection.through_reflection.name\n @owner.send(joins).delete(@owner.send(joins).select do |join|\n join.send(@reflection.options[:polymorphic_key]) == record.id and\n join.send(@reflection.options[:polymorphic_type_key]) == \"#{record.class.base_class}\"\n end)\n @target.delete(record)\n end\n end\n end\n\n # Clears all records from the association. Returns an empty array.\n def clear(klass = nil)\n load_target\n return if @target.empty?\n\n if klass\n delete(@target.select {|r| r.is_a? klass })\n else\n @owner.send(@reflection.through_reflection.name).clear\n @target.clear\n end\n []\n end\n\n protected\n\n# undef :sum\n# undef :create!\n\n def construct_quoted_owner_attributes(*args) #:nodoc:\n # no access to returning() here? why not?\n type_key = @reflection.options[:foreign_type_key]\n h = {@reflection.primary_key_name => @owner.id}\n h[type_key] = @owner.class.base_class.name if type_key\n h\n end\n\n def construct_from #:nodoc:\n # build the FROM part of the query, in this case, the polymorphic join table\n @reflection.klass.quoted_table_name\n end\n\n def construct_owner #:nodoc:\n # the table name for the owner object's class\n @owner.class.quoted_table_name\n end\n\n def construct_owner_key #:nodoc:\n # the primary key field for the owner object\n @owner.class.primary_key\n end\n\n def construct_select(custom_select = nil) #:nodoc:\n # build the select query\n selected = custom_select || @reflection.options[:select]\n end\n\n def construct_joins(custom_joins = nil) #:nodoc:\n # build the string of default joins\n \"JOIN #{construct_owner} AS polymorphic_parent ON #{construct_from}.#{@reflection.options[:foreign_key]} = polymorphic_parent.#{construct_owner_key} \" +\n @reflection.options[:from].map do |plural|\n klass = plural._as_class\n \"LEFT JOIN #{klass.quoted_table_name} ON #{construct_from}.#{@reflection.options[:polymorphic_key]} = #{klass.quoted_table_name}.#{klass.primary_key} AND #{construct_from}.#{@reflection.options[:polymorphic_type_key]} = #{@reflection.klass.quote_value(klass.base_class.name)}\"\n end.uniq.join(\" \") + \" #{custom_joins}\"\n end\n\n def construct_conditions #:nodoc:\n # build the fully realized condition string\n conditions = construct_quoted_owner_attributes.map do |field, value|\n \"#{construct_from}.#{field} = #{@reflection.klass.quote_value(value)}\" if value\n end\n conditions << custom_conditions if custom_conditions\n \"(\" + conditions.compact.join(') AND (') + \")\"\n end\n\n def custom_conditions #:nodoc:\n # custom conditions... not as messy as has_many :through because our joins are a little smarter\n if @reflection.options[:conditions]\n \"(\" + interpolate_sql(@reflection.klass.send(:sanitize_sql, @reflection.options[:conditions])) + \")\"\n end\n end\n\n alias :construct_owner_attributes :construct_quoted_owner_attributes\n alias :conditions :custom_conditions # XXX possibly not necessary\n alias :sql_conditions :custom_conditions # XXX ditto\n\n # construct attributes for join for a particular record\n def construct_join_attributes(record) #:nodoc:\n {\n @reflection.options[:polymorphic_key] => record.id,\n @reflection.options[:polymorphic_type_key] => \"#{record.class.base_class}\",\n @reflection.options[:foreign_key] => @owner.id\n }.merge(\n @reflection.options[:foreign_type_key] ?\n { @reflection.options[:foreign_type_key] => \"#{@owner.class.base_class}\" } :\n {}\n ) # for double-sided relationships\n end\n\n def build(attrs = nil) #:nodoc:\n raise PolymorphicMethodNotSupportedError, \"You can't associate new records.\"\n end\n\n end\n\n end\nend\n"} +{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/support_methods.rb", "file_before": "\nclass String\n\n # Changes an underscored string into a class reference.\n def _as_class\n # classify expects self to be plural\n self.classify.constantize\n end\n\n # For compatibility with the Symbol extensions.\n alias :_singularize :singularize\n alias :_pluralize :pluralize\n alias :_classify :classify\nend\n\nclass Symbol\n \n # Changes an underscored symbol into a class reference.\n def _as_class; self.to_s._as_class; end\n \n # Changes a plural symbol into a singular symbol.\n def _singularize; self.to_s.singularize.to_sym; end\n\n # Changes a singular symbol into a plural symbol.\n def _pluralize; self.to_s.pluralize.to_sym; end\n\n # Changes a symbol into a class name string.\n def _classify; self.to_s.classify; end\nend\n\nclass Array\n\n # Flattens the first level of self.\n def _flatten_once\n self.inject([]){|r, el| r + Array(el)}\n end\n\n # Rails 1.2.3 compatibility method. Copied from http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/array/extract_options.rb?rev=7217 \n def _extract_options!\n last.is_a?(::Hash) ? pop : {}\n end\nend\n\nclass Hash\n\n # An implementation of select that returns a Hash.\n def _select\n if RUBY_VERSION >= \"1.9\"\n Hash[*self.select {|k, v| yield k, v }.flatten]\n else\n Hash[*self.select do |key, value|\n yield key, value\n end._flatten_once]\n end\n end\nend\n\nclass Object\n\n # Returns the metaclass of self.\n def _metaclass; (class << self; self; end); end\n\n # Logger shortcut.\n def _logger_debug s\n s = \"** has_many_polymorphs: #{s}\"\n Rails.logger.debug(s) if Rails and Rails.logger\n end \n\n # Logger shortcut. \n def _logger_warn s\n s = \"** has_many_polymorphs: #{s}\"\n if Rails and Rails.logger\n Rails.logger.warn(s) \n else\n $stderr.puts(s)\n end \n end\n \nend\n\nclass ActiveRecord::Base\n\n # Return the base class name as a string.\n def _base_class_name\n self.class.base_class.name.to_s\n end\n \nend\n", "file_after": "\nclass String\n\n # Changes an underscored string into a class reference.\n def _as_class\n # classify expects self to be plural\n self.classify.constantize\n end\n\n # For compatibility with the Symbol extensions.\n alias :_singularize :singularize\n alias :_pluralize :pluralize\n alias :_classify :classify\nend\n\nclass Symbol\n\n # Changes an underscored symbol into a class reference.\n def _as_class; self.to_s._as_class; end\n\n # Changes a plural symbol into a singular symbol.\n def _singularize; self.to_s.singularize.to_sym; end\n\n # Changes a singular symbol into a plural symbol.\n def _pluralize; self.to_s.pluralize.to_sym; end\n\n # Changes a symbol into a class name string.\n def _classify; self.to_s.classify; end\nend\n\nclass Array\n\n # Flattens the first level of self.\n def _flatten_once\n self.inject([]){|r, el| r + Array(el)}\n end\n\n # Rails 1.2.3 compatibility method. Copied from http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/array/extract_options.rb?rev=7217\n def _extract_options!\n last.is_a?(::Hash) ? pop : {}\n end\nend\n\nclass Hash\n\n # An implementation of select that returns a Hash.\n def _select\n if RUBY_VERSION >= \"1.9\"\n Hash[*self.select {|k, v| yield k, v }.flatten]\n else\n Hash[*self.select do |key, value|\n yield key, value\n end._flatten_once]\n end\n end\nend\n\nclass Object\n\n # Returns the metaclass of self.\n def _metaclass; (class << self; self; end); end\n\n # Logger shortcut.\n def _logger_debug s\n s = \"** has_many_polymorphs: #{s}\"\n Rails.logger.debug(s) if Rails and Rails.logger\n end\n\n # Logger shortcut.\n def _logger_warn s\n s = \"** has_many_polymorphs: #{s}\"\n if Rails and Rails.logger\n Rails.logger.warn(s)\n else\n $stderr.puts(s)\n end\n end\n\nend\n\nclass ActiveRecord::Base\n\n # Return the base class name as a string.\n def _base_class_name\n self.class.base_class.name.to_s\n end\n\nend\n"} +{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs.rb", "file_before": "require 'active_record'\nrequire 'has_many_polymorphs/reflection'\nrequire 'has_many_polymorphs/association'\nrequire 'has_many_polymorphs/class_methods'\n\nrequire 'has_many_polymorphs/support_methods'\nrequire 'has_many_polymorphs/base'\n\nclass ActiveRecord::Base\n extend ActiveRecord::Associations::PolymorphicClassMethods \nend\n\nif ENV['HMP_DEBUG'] || (Rails.env.development? || Rails.env.test?) && ENV['USER'] == 'eweaver'\n require 'has_many_polymorphs/debugging_tools' \nend\n\nrequire 'has_many_polymorphs/railtie'\n\n_logger_debug \"loaded ok\"\n", "file_after": "require 'active_record'\nrequire 'has_many_polymorphs/reflection'\nrequire 'has_many_polymorphs/association'\nrequire 'has_many_polymorphs/class_methods'\n\nrequire 'has_many_polymorphs/support_methods'\nrequire 'has_many_polymorphs/base'\n\nclass ActiveRecord::Base\n extend ActiveRecord::Associations::PolymorphicClassMethods\nend\n\nif ENV['HMP_DEBUG'] && (Rails.env.development? || Rails.env.test?)\n require 'has_many_polymorphs/debugging_tools'\nend\n\nrequire 'has_many_polymorphs/railtie'\n\n_logger_debug \"loaded ok\"\n"} +{"repo": "colbygk/log4r", "pr_number": 57, "filename": "lib/log4r/yamlconfigurator.rb", "file_before": "# :include: rdoc/yamlconfigurator\n#\n# == Other Info\n#\n# Version: $Id$\n\nrequire \"log4r/logger\"\nrequire \"log4r/outputter/staticoutputter\"\nrequire \"log4r/logserver\"\nrequire \"log4r/outputter/remoteoutputter\"\n\nrequire 'yaml'\n\nmodule Log4r\n # Gets raised when Configurator encounters bad YAML.\n class ConfigError < Exception\n end\n\n # See log4r/yamlconfigurator.rb\n class YamlConfigurator\n @@params = Hash.new\n\n # Get a parameter's value\n def self.[](param); @@params[param] end\n # Define a parameter with a value\n def self.[]=(param, value); @@params[param] = value end\n\n\n def self.custom_levels( levels)\n return Logger.root if levels.size == 0\n for i in 0...levels.size\n name = levels[i].to_s\n if name =~ /\\s/ or name !~ /^[A-Z]/\n raise TypeError, \"#{name} is not a valid Ruby Constant name\", caller\n end\n end\n Log4r.define_levels *levels\n end\n\n # Given a filename, loads the YAML configuration for Log4r.\n def self.load_yaml_file( filename)\n actual_load( File.open( filename))\n end\n\n # You can load a String YAML configuration instead of a file.\n def self.load_yaml_string( string)\n actual_load( string)\n end\n\n #######\n private\n #######\n\n def self.actual_load( yaml_docs)\n log4r_config = nil\n YAML.load_documents( yaml_docs){ |doc|\n doc.has_key?( 'log4r_config') and log4r_config = doc['log4r_config'] and break\n }\n if log4r_config.nil?\n raise ConfigError, \n \"Key 'log4r_config:' not defined in yaml documents\", caller[1..-1]\n end\n decode_yaml( log4r_config)\n end\n \n def self.decode_yaml( cfg)\n decode_pre_config( cfg['pre_config'])\n cfg['outputters'].each{ |op| decode_outputter( op)}\n cfg['loggers'].each{ |lo| decode_logger( lo)}\n cfg['logserver'].each{ |lo| decode_logserver( lo)} unless cfg['logserver'].nil?\n end\n\n def self.decode_pre_config( pre)\n return Logger.root if pre.nil?\n decode_custom_levels( pre['custom_levels'])\n global_config( pre['global'])\n global_config( pre['root'])\n decode_parameters( pre['parameters'])\n end\n\n def self.decode_custom_levels( levels)\n return Logger.root if levels.nil?\n begin custom_levels( levels)\n rescue TypeError => te\n raise ConfigError, te.message, caller[1..-4]\n end\n end\n \n def self.global_config( e)\n return if e.nil?\n globlev = e['level']\n return if globlev.nil?\n lev = LNAMES.index(globlev) # find value in LNAMES\n Log4rTools.validate_level(lev, 4) # choke on bad level\n Logger.global.level = lev\n end\n\n def self.decode_parameters( params)\n params.each{ |p| @@params[p['name']] = p['value']} unless params.nil?\n end\n\n def self.decode_outputter( op)\n # fields\n name = op['name']\n type = op['type']\n level = op['level']\n only_at = op['only_at']\n # validation\n raise ConfigError, \"Outputter missing name\", caller[1..-3] if name.nil?\n raise ConfigError, \"Outputter missing type\", caller[1..-3] if type.nil?\n Log4rTools.validate_level(LNAMES.index(level)) unless level.nil?\n only_levels = []\n unless only_at.nil?\n for lev in only_at\n alev = LNAMES.index(lev)\n Log4rTools.validate_level(alev, 3)\n only_levels.push alev\n end\n end\n\n formatter = decode_formatter( op['formatter'])\n\n opts = {}\n opts[:level] = LNAMES.index(level) unless level.nil?\n opts[:formatter] = formatter unless formatter.nil?\n opts.merge!(decode_hash_params(op))\n begin\n Outputter[name] = Log4r.const_get(type).new name, opts\n rescue Exception => ae\n raise ConfigError, \n \"Problem creating outputter: #{ae.message}\", caller[1..-3]\n end\n Outputter[name].only_at( *only_levels) if only_levels.size > 0\n Outputter[name]\n end\n\n def self.decode_formatter( fo)\n return nil if fo.nil?\n type = fo['type'] \n raise ConfigError, \"Formatter missing type\", caller[1..-4] if type.nil?\n begin\n return Log4r.const_get(type).new(decode_hash_params(fo))\n rescue Exception => ae\n raise ConfigError,\n \"Problem creating outputter: #{ae.message}\", caller[1..-4]\n end\n end\n\n ExcludeParams = %w{formatter level name type only_at}\n\n # Does the fancy parameter to hash argument transformation\n def self.decode_hash_params(ph)\n case ph\n when Hash\n ph.inject({}){|a,(k,v)| a[k] = self.decode_hash_params(v); a}\n when Array\n ph.map{|v| self.decode_hash_params(v)}\n when String\n self.paramsub(ph)\n else\n ph\n end\n end\n\n # Substitues any #{foo} in the YAML with Parameter['foo']\n def self.paramsub(str)\n @@params.each {|param, value|\n str = str.sub(\"\\#{#{param}}\", value)\n }\n str\n end\n\n def self.decode_logger( lo)\n l = Logger.new lo['name']\n decode_logger_common( l, lo)\n end\n\n def self.decode_logserver( lo)\n name = lo['name']\n uri = lo['uri']\n l = LogServer.new name, uri\n decode_logger_common(l, lo)\n end\n\n def self.decode_logger_common( l, lo)\n level = lo['level']\n additive = lo['additive']\n trace = lo['trace']\n l.level = LNAMES.index( level) unless level.nil?\n l.additive = additive unless additive.nil?\n l.trace = trace unless trace.nil?\n # and now for outputters\n outs = lo['outputters']\n outs.each {|n| l.add n.strip} unless outs.nil?\n end\n end\nend\n\n", "file_after": "# :include: rdoc/yamlconfigurator\n#\n# == Other Info\n#\n# Version: $Id$\n\nrequire \"log4r/logger\"\nrequire \"log4r/outputter/staticoutputter\"\nrequire \"log4r/logserver\"\nrequire \"log4r/outputter/remoteoutputter\"\n\nrequire 'yaml'\n\nmodule Log4r\n # Gets raised when Configurator encounters bad YAML.\n class ConfigError < Exception\n end\n\n # See log4r/yamlconfigurator.rb\n class YamlConfigurator\n @@params = Hash.new\n\n # Get a parameter's value\n def self.[](param); @@params[param] end\n # Define a parameter with a value\n def self.[]=(param, value); @@params[param] = value end\n\n\n def self.custom_levels( levels)\n return Logger.root if levels.size == 0\n for i in 0...levels.size\n name = levels[i].to_s\n if name =~ /\\s/ or name !~ /^[A-Z]/\n raise TypeError, \"#{name} is not a valid Ruby Constant name\", caller\n end\n end\n Log4r.define_levels *levels\n end\n\n # Given a filename, loads the YAML configuration for Log4r.\n def self.load_yaml_file( filename)\n actual_load( File.open( filename))\n end\n\n # You can load a String YAML configuration instead of a file.\n def self.load_yaml_string( string)\n actual_load( string)\n end\n\n #######\n private\n #######\n\n def self.actual_load( yaml_docs)\n log4r_config = nil\n YAML.load_stream( yaml_docs){ |doc|\n doc.has_key?( 'log4r_config') and log4r_config = doc['log4r_config'] and break\n }\n if log4r_config.nil?\n raise ConfigError, \n \"Key 'log4r_config:' not defined in yaml documents\", caller[1..-1]\n end\n decode_yaml( log4r_config)\n end\n \n def self.decode_yaml( cfg)\n decode_pre_config( cfg['pre_config'])\n cfg['outputters'].each{ |op| decode_outputter( op)}\n cfg['loggers'].each{ |lo| decode_logger( lo)}\n cfg['logserver'].each{ |lo| decode_logserver( lo)} unless cfg['logserver'].nil?\n end\n\n def self.decode_pre_config( pre)\n return Logger.root if pre.nil?\n decode_custom_levels( pre['custom_levels'])\n global_config( pre['global'])\n global_config( pre['root'])\n decode_parameters( pre['parameters'])\n end\n\n def self.decode_custom_levels( levels)\n return Logger.root if levels.nil?\n begin custom_levels( levels)\n rescue TypeError => te\n raise ConfigError, te.message, caller[1..-4]\n end\n end\n \n def self.global_config( e)\n return if e.nil?\n globlev = e['level']\n return if globlev.nil?\n lev = LNAMES.index(globlev) # find value in LNAMES\n Log4rTools.validate_level(lev, 4) # choke on bad level\n Logger.global.level = lev\n end\n\n def self.decode_parameters( params)\n params.each{ |p| @@params[p['name']] = p['value']} unless params.nil?\n end\n\n def self.decode_outputter( op)\n # fields\n name = op['name']\n type = op['type']\n level = op['level']\n only_at = op['only_at']\n # validation\n raise ConfigError, \"Outputter missing name\", caller[1..-3] if name.nil?\n raise ConfigError, \"Outputter missing type\", caller[1..-3] if type.nil?\n Log4rTools.validate_level(LNAMES.index(level)) unless level.nil?\n only_levels = []\n unless only_at.nil?\n for lev in only_at\n alev = LNAMES.index(lev)\n Log4rTools.validate_level(alev, 3)\n only_levels.push alev\n end\n end\n\n formatter = decode_formatter( op['formatter'])\n\n opts = {}\n opts[:level] = LNAMES.index(level) unless level.nil?\n opts[:formatter] = formatter unless formatter.nil?\n opts.merge!(decode_hash_params(op))\n begin\n Outputter[name] = Log4r.const_get(type).new name, opts\n rescue Exception => ae\n raise ConfigError, \n \"Problem creating outputter: #{ae.message}\", caller[1..-3]\n end\n Outputter[name].only_at( *only_levels) if only_levels.size > 0\n Outputter[name]\n end\n\n def self.decode_formatter( fo)\n return nil if fo.nil?\n type = fo['type'] \n raise ConfigError, \"Formatter missing type\", caller[1..-4] if type.nil?\n begin\n return Log4r.const_get(type).new(decode_hash_params(fo))\n rescue Exception => ae\n raise ConfigError,\n \"Problem creating outputter: #{ae.message}\", caller[1..-4]\n end\n end\n\n ExcludeParams = %w{formatter level name type only_at}\n\n # Does the fancy parameter to hash argument transformation\n def self.decode_hash_params(ph)\n case ph\n when Hash\n ph.inject({}){|a,(k,v)| a[k] = self.decode_hash_params(v); a}\n when Array\n ph.map{|v| self.decode_hash_params(v)}\n when String\n self.paramsub(ph)\n else\n ph\n end\n end\n\n # Substitues any #{foo} in the YAML with Parameter['foo']\n def self.paramsub(str)\n @@params.each {|param, value|\n str = str.sub(\"\\#{#{param}}\", value)\n }\n str\n end\n\n def self.decode_logger( lo)\n l = Logger.new lo['name']\n decode_logger_common( l, lo)\n end\n\n def self.decode_logserver( lo)\n name = lo['name']\n uri = lo['uri']\n l = LogServer.new name, uri\n decode_logger_common(l, lo)\n end\n\n def self.decode_logger_common( l, lo)\n level = lo['level']\n additive = lo['additive']\n trace = lo['trace']\n l.level = LNAMES.index( level) unless level.nil?\n l.additive = additive unless additive.nil?\n l.trace = trace unless trace.nil?\n # and now for outputters\n outs = lo['outputters']\n outs.each {|n| l.add n.strip} unless outs.nil?\n end\n end\nend\n\n"} +{"repo": "shokai/ImageResize-ruby", "pr_number": 2, "filename": "lib/ImageResize/Image.rb", "file_before": "module Image\n\n $VERBOSE = nil\n \n def Image.cmd\n jar_path = File.expand_path(File.dirname(__FILE__)).split(/\\//)\n jar_path.pop\n jar_path.pop\n resizer = \"#{jar_path.join('/')}/java/ImageResize.jar\"\n \"java -jar #{resizer}\"\n end\n \n def Image.resize(img_in, img_out, width, height)\n puts `#{Image.cmd} resize #{img_in} #{img_out} #{width} #{height}`\n end\n\n def Image.formats\n lines = `#{Image.cmd} formats`\n read_formats = nil\n write_formats = nil\n for line in lines.split(/[\\r\\n]/) do\n rw, format = line.split(/\\:/)\n formats = format.split(/,/).map{|f|f.downcase}.uniq.sort\n if rw == 'read'\n read_formats = formats\n elsif rw == 'write'\n write_formats = formats\n end\n end\n return read_formats, write_formats\n end\n\n def Image.read_formats\n r,w = Image.formats\n r\n end\n \n def Image.write_formats\n r,w = Image.formats\n w\n end\n \nend\n", "file_after": "module Image\n\n $VERBOSE = nil\n \n def Image.cmd\n jar_path = File.expand_path(File.dirname(__FILE__)).split(/\\//)\n jar_path.pop\n jar_path.pop\n resizer = \"#{jar_path.join('/')}/java/ImageResize.jar\"\n \"java -jar #{resizer}\"\n end\n \n def Image.resize(img_in, img_out, width, height)\n puts `#{Image.cmd} resize \"#{img_in}\" \"#{img_out}\" #{width} #{height}`\n end\n\n def Image.formats\n lines = `#{Image.cmd} formats`\n read_formats = nil\n write_formats = nil\n for line in lines.split(/[\\r\\n]/) do\n rw, format = line.split(/\\:/)\n formats = format.split(/,/).map{|f|f.downcase}.uniq.sort\n if rw == 'read'\n read_formats = formats\n elsif rw == 'write'\n write_formats = formats\n end\n end\n return read_formats, write_formats\n end\n\n def Image.read_formats\n r,w = Image.formats\n r\n end\n \n def Image.write_formats\n r,w = Image.formats\n w\n end\n \nend\n"} +{"repo": "defunkt/choice", "pr_number": 17, "filename": "lib/choice/lazyhash.rb", "file_before": "module Choice\n\n # This class lets us get away with really bad, horrible, lazy hash accessing.\n # Like so:\n # hash = LazyHash.new\n # hash[:someplace] = \"somewhere\"\n # puts hash[:someplace]\n # puts hash['someplace']\n # puts hash.someplace\n #\n # If you'd like, you can pass in a current hash when initializing to convert\n # it into a lazyhash. Or you can use the .to_lazyhash method attached to the\n # Hash object (evil!).\n class LazyHash < Hash\n\n # Keep the old methods around.\n alias_method :old_store, :store\n alias_method :old_fetch, :fetch\n\n # You can pass in a normal hash to convert it to a LazyHash.\n def initialize(hash = nil)\n hash.each { |key, value| self[key] = value } if !hash.nil? && hash.is_a?(Hash)\n end\n\n # Wrapper for []\n def store(key, value)\n self[key] = value\n end\n\n # Wrapper for []=\n def fetch(key)\n self[key]\n end\n\n # Store every key as a string.\n def []=(key, value)\n key = key.to_s if key.is_a? Symbol\n self.old_store(key, value)\n end\n\n # Every key is stored as a string. Like a normal hash, nil is returned if\n # the key does not exist.\n def [](key)\n key = key.to_s if key.is_a? Symbol\n self.old_fetch(key) rescue return nil\n end\n\n # You can use hash.something or hash.something = 'thing' since this is\n # truly a lazy hash.\n def method_missing(meth, *args)\n meth = meth.to_s\n if meth =~ /=/\n self[meth.sub('=','')] = args.first\n else\n self[meth]\n end\n end\n\n end\nend\n\n# Really ugly, horrible, extremely fun hack.\nclass Hash #:nodoc:\n def to_lazyhash\n return Choice::LazyHash.new(self)\n end\nend\n", "file_after": "module Choice\n\n # This class lets us get away with really bad, horrible, lazy hash accessing.\n # Like so:\n # hash = LazyHash.new\n # hash[:someplace] = \"somewhere\"\n # puts hash[:someplace]\n # puts hash['someplace']\n # puts hash.someplace\n #\n # If you'd like, you can pass in a current hash when initializing to convert\n # it into a lazyhash. Or you can use the .to_lazyhash method attached to the\n # Hash object (evil!).\n class LazyHash < Hash\n\n # Keep the old methods around.\n alias_method :old_store, :store\n alias_method :old_fetch, :fetch\n\n # You can pass in a normal hash to convert it to a LazyHash.\n def initialize(hash = nil)\n hash.each { |key, value| self[key] = value } if hash && hash.is_a?(Hash)\n end\n\n # Wrapper for []\n def store(key, value)\n self[key] = value\n end\n\n # Wrapper for []=\n def fetch(key)\n self[key]\n end\n\n # Store every key as a string.\n def []=(key, value)\n key = key.to_s if key.is_a?(Symbol)\n old_store(key, value)\n end\n\n # Every key is stored as a string. Like a normal hash, nil is returned if\n # the key does not exist.\n def [](key)\n key = key.to_s if key.is_a?(Symbol)\n old_fetch(key) rescue return nil\n end\n\n # You can use hash.something or hash.something = 'thing' since this is\n # truly a lazy hash.\n def method_missing(meth, *args)\n meth = meth.to_s\n if meth =~ /=/\n self[meth.sub('=', '')] = args.first\n else\n self[meth]\n end\n end\n\n end\nend\n\n# Really ugly, horrible, extremely fun hack.\nclass Hash #:nodoc:\n def to_lazyhash\n Choice::LazyHash.new(self)\n end\nend\n"}