\\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\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 \"
Disciplines
\".$disciplinecount.\"
\\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 \"
Schools
\".$schoolcount.\"
\\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 \"
Dissertations
\".$disscount.\"
\\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 \"
Advisorships
\".$advisorcount.\"
\\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 \"
Committeeships
\".$committeeshipscount.\"
\\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 \"
People
\".$peoplecount.\"
\\n\";\n echo \"
\\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 $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 if ($one%10==0)\n {\n echo $one;\n }\n echo \"
\\n\";\n }\n echo \"
\";\n echo \"
\\n\";\n\n break;\n\n\n ###############################################\n case \"show_logs\":\n\n if (is_admin())\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\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 if ($two != $lasttotal){echo $count.\".\";}\n echo \"
\";\n echo \"
\";\n echo get_person_link($one);\n echo \"
\";\n echo \"
\";\n echo $two;\n echo \"
\";\n echo \"
\\n\";\n $lasttotal = $two;\n }\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 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 }\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 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 }\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 else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin())\n {\n echo \"
\\n\";\n\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\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\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\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\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\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\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 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 \"
\\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 }\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\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
Name
\n
A
\n
C
\n
A+C
\n
G
\n
T
\n
TA
\n
TD
\n
W
\n
\\n\";\n foreach ($sortedprofs as $one)\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 \"
\\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\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 \"
Disciplines
\".$disciplinecount.\"
\\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 \"
Schools
\".$schoolcount.\"
\\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 \"
Dissertations
\".$disscount.\"
\\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 \"
Advisorships
\".$advisorcount.\"
\\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 \"
Committeeships
\".$committeeshipscount.\"
\\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 \"
People
\".$peoplecount.\"
\\n\";\n echo \"
\\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\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\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 if ($two != $lasttotal){echo $count.\".\";}\n echo \"
\";\n echo \"
\";\n echo get_person_link($one);\n echo \"
\";\n echo \"
\";\n echo $two;\n echo \"
\";\n echo \"
\\n\";\n $lasttotal = $two;\n }\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 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 }\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 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 }\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 else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin())\n {\n echo \"
\\n\";\n\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\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\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\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\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\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\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 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 \"
\\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 }\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 \"
\";\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": "\n\nclass knj_strings{\n\tstatic function substr($string, $len1, $len2){\n\t\t$string = utf8_decode($string);\n\t\t$string = substr($string, $len1, $len2);\n\t\t$string = utf8_encode($string);\n\t\treturn $string;\n\t}\n\t\n\tstatic function utf8wrapper($func, $arg1){\n\t\treturn utf8_encode(call_user_func($func, utf8_decode($arg1)));\n\t}\n\t\n\tstatic function utf8force($string){\n\t\t$values = array();\n\t\t$special = array(\"\u00f8\", \"\u00e6\", \"\u00e5\", \"\u00d8\", \"\u00c6\", \"\u00c5\");\n\t\tforeach($special AS $value){\n\t\t\t$values[utf8_decode($value)] = $value;\n\t\t}\n\t\t\n\t\t$string = str_replace(\"\u00c3\u00a6\", \"\u00e6\", $string);\n\t\t\n\t\treturn strtr($string, $values);\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": "\n\nclass epay{\n\tprivate $payments = array();\n\t\n\tfunction __construct($args){\n\t\t$this->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": "\n\nclass wfpayment{\n\tprivate $payments = array();\n\t\n\tfunction __construct($args){\n\t\t$this->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": "\n\nclass knj_strings{\n\tstatic function substr($string, $len1, $len2){\n\t\t$string = utf8_decode($string);\n\t\t$string = substr($string, $len1, $len2);\n\t\t$string = utf8_encode($string);\n\t\treturn $string;\n\t}\n\t\n\tstatic function utf8wrapper($func, $arg1){\n\t\treturn utf8_encode(call_user_func($func, utf8_decode($arg1)));\n\t}\n\t\n\tstatic function utf8force($string){\n\t\tif (is_array($string)){\n\t\t\tforeach($string as $key => $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": "\n\nclass epay{\n\tprivate $payments = array();\n\t\n\tfunction __construct($args){\n\t\t$this->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
The most up-to-date book to learn Ember.js
\n
\n Trusted by:\n \n \n \n \n
\n
\n
\n\n
\n
\n
\n \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
\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 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
\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
\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
\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
\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 \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
\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 — 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 \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
\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
\n — Steven Kane\n
\n
\n
\n
\n
\n
\n \n \n \n
\n
\n
\n
\n
\n
\n \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 \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 \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.
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.
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
\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.
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
\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.
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
\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 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
\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
\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
\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
\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 \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
\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 — 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 \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
\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
\n — Steven Kane\n
\n
\n
\n
\n
\n
\n \n \n \n
\n
\n
\n
\n
\n
\n \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 \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 \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.
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.
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
\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.
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
\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
\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 *
setOptions: set Options
\n *
buildWrapper: setup the \"decorator\"
\n *
setupOriginal: procede the \"original\" element (add Events...)
\n *
addLabel: add and procede the label
\n *
initializeAdv: last chance for subclasses to do initialization
\n *
build: various specific dom handling and \"decorator\" building
\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 *
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 *
setOptions: set Options
\n *
buildWrapper: setup the \"decorator\"
\n *
setupOriginal: procede the \"original\" element (add Events...)
\n *
addLabel: add and procede the label
\n *
initializeAdv: last chance for subclasses to do initialization
\n *
build: various specific dom handling and \"decorator\" building
\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 *
', 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); // 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('
');\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
', 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); // 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('
');\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 \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"}
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