/** * mm_hideFields * @version 1.1.2 (2014-05-07) * * @desc A widget for ManagerManager plugin that allows one or more of the default document fields or template variables to be hidden within the manager. * * @uses ManagerManager plugin 0.4. * * @param $fields {comma separated string} - The name(s) of the document fields (or TVs) this should apply to. @required * @param $roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). Default: ''. * @param $templates {comma separated string} - Id of the templates to which this widget is applied (when this parameter is empty then widget is applied to the all templates). Default: ''. * * @link http://code.divandesign.biz/modx/mm_hidefields/1.1.2 * * @copyright 2014 */ function mm_hideFields($fields, $roles = '', $templates = '') { global $modx; $e =& $modx->Event; // if we've been supplied with a string, convert it into an array $fields = makeArray($fields); // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { global $mm_fields; $output = "//---------- mm_hideFields :: Begin -----\n"; foreach ($fields as $field) { switch ($field) { // Exceptions case 'keywords': $output .= '$j("select[name*=\'keywords\']").parent("td").hide();' . "\n"; break; case 'metatags': $output .= '$j("select[name*\'=metatags\']").parent("td").hide()' . "\n"; break; case 'hidemenu': case 'hide_menu': case 'show_in_menu': $output .= '$j("input[name=\'hidemenucheck\']").parent("td").hide();' . "\n"; break; case 'menuindex': $output .= '$j("input[name=\'menuindex\']").parents("table").parent("td").prev("td").children("span.warning").hide();' . "\n"; $output .= '$j("input[name=\'menuindex\']").parent("td").hide();' . "\n"; break; case 'which_editor': $output .= '$j("select#which_editor").prev("span.warning").hide();' . "\n"; $output .= '$j("select#which_editor").hide();' . "\n"; break; case 'content': $output .= '$j("#sectionContentHeader, #sectionContentBody").hide();' . "\n"; // For 1.0.0 $output .= '$j("#ta").parent("div").parent("div").hide().prev("div").hide();' . "\n"; // For 1.0.1 break; case 'pub_date': $output .= '$j("input[name=\'pub_date\']").parents("tr").next("tr").hide();' . "\n"; $output .= '$j("input[name=\'pub_date\']").parents("tr").hide();' . "\n"; break; case 'unpub_date': $output .= '$j("input[name=\'unpub_date\']").parents("tr").next("tr").hide();' . "\n"; $output .= '$j("input[name=\'unpub_date\']").parents("tr").hide();' . "\n"; break; // Ones that follow the regular pattern // Ones that follow the regular pattern default: if (isset($mm_fields[$field])) { // Check the fields exist, so we're not writing JS for elements that don't exist $output .= '$j("' . $mm_fields[$field]['fieldtype'] . '[name=\'' . $mm_fields[$field]['fieldname'] . '\']").parents("tr").hide().next("tr").find("td[colspan=2]").parent("tr").hide();' . "\n"; } break; } $output .= "//---------- mm_hideFields :: End -----\n"; $e->output($output); } } }
function mm_minimizablesections($sections, $roles = '', $templates = '', $minimized = '') { if (!useThisRule($roles, $templates)) { return; } global $modx; $e =& $modx->Event; $site = $modx->config['site_url']; $widgetDir = $site . 'assets/plugins/managermanager/widgets/mm_minimizablesections/'; $output = ''; if ($e->name == 'OnDocFormPrerender') { $output .= includeJsCss($widgetDir . 'minimizablesections.css', 'html'); $e->output($output); } else { if ($e->name == 'OnDocFormRender') { $sections = makeArray($sections); $minimized = makeArray($minimized); $sections = array_map("prepareSection", $sections); $minimized = array_map("prepareSection", $minimized); $output .= "//---------- mm_minimizablesections :: Begin -----\n"; $output .= '$j("' . implode(",", $sections) . '","#documentPane").addClass("minimizable").on("click",function(){ var _t = $j(this); _t.next().slideToggle(400,function(){_t.toggleClass("minimized");}) }); $j(".minimizable").filter("' . implode(",", $minimized) . '").addClass("minimized").next().hide(); '; $output .= "//---------- mm_minimizablesections :: End -----\n"; $e->output($output); } } }
/** * mm_widget_template * @version 1.0 (2013-01-01) * * A template for creating new widgets * * @uses ManagerManager plugin 0.4. * * @link http:// * * @copyright 2013 */ function mm_widget_template($fields, $other_param = 'defaultValue', $roles = '', $templates = '') { global $modx, $mm_fields, $mm_current_page; $e =& $modx->event; if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { // Your output should be stored in a string, which is outputted at the end // It will be inserted as a Javascript block (with jQuery), which is executed on document ready // We always put a JS comment, which makes debugging much easier $output = "// -------------- mm_widget_template :: Begin ------------- \n"; // if we've been supplied with a string, convert it into an array $fields = makeArray($fields); // You might want to check whether the current page's template uses the TVs that have been // supplied, to save processing page which don't contain them $count = tplUseTvs($mm_current_page['template'], $fields); if ($count == false) { return; } // We have functions to include JS or CSS external files you might need // The standard ModX API methods don't work here $output .= includeJs('assets/plugins/managermanager/widgets/template/javascript.js'); $output .= includeCss('assets/plugins/managermanager/widgets/template/styles.css'); // Do something for each of the fields supplied foreach ($fields as $targetTv) { // If it's a TV, we may need to map the field name, to what it's ID is. // This can be obtained from the mm_fields array $tv_id = $mm_fields[$targetTv]['fieldname']; } //JS comment for end of widget $output .= "// -------------- mm_widget_template :: End ------------- \n"; // Send the output to the browser $e->output($output . "\n"); } }
/** * mm_hideSections * @version 1.2.1 (2014-05-25) * * @desc A widget for ManagerManager plugin that allows one or a few sections to be hidden on the document edit page. * * @uses ManagerManager plugin 0.6.2. * * @param $sections {comma separated string} - The id(s) of the sections this should apply to. @required * @param $roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). Default: ''. * @param $templates {comma separated string} - Id of the templates to which this widget is applied (when this parameter is empty then widget is applied to the all templates). Default: ''. * * @link http://code.divandesign.biz/modx/mm_hidesections/1.2.1 * * @copyright 2014 */ function mm_hideSections($sections, $roles = '', $templates = '') { global $modx; $e =& $modx->Event; // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { // if we've been supplied with a string, convert it into an array $sections = makeArray($sections); $output = "//---------- mm_hideSections :: Begin -----\n"; foreach ($sections as $section) { switch ($section) { case 'access': // These have moved to tabs in 1.0.1 $output .= '$j("#sectionAccessHeader, #sectionAccessBody").hide();' . "\n"; break; default: $section = prepareSectionId($section); $output .= '$j("#' . $section . '_header, #' . $section . '_body").hide();' . "\n"; break; } } $output .= "//---------- mm_hideSections :: End -----\n"; $e->output($output); } }
/** * mm_hideSections * @version 1.1 (2012-11-13) * * Hides sections. * * @uses ManagerManager plugin 0.4. * * @link http://code.divandesign.biz/modx/mm_hidesections/1.1 * * @copyright 2012 */ function mm_hideSections($sections, $roles = '', $templates = '') { global $modx; $e =& $modx->event; // if we've been supplied with a string, convert it into an array $sections = makeArray($sections); // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if (useThisRule($roles, $templates)) { $output = "// -------------- mm_hideSections :: Begin ------------- \n"; foreach ($sections as $section) { switch ($section) { case 'content': $output .= ' $j("#content_header").hide(); $j("#content_body").hide(); '; break; case 'tvs': $output .= ' $j("#tv_header").hide(); $j("#tv_body").hide(); '; break; case 'access': // These have moved to tabs in 1.0.1 $output .= ' $j("#sectionAccessHeader").hide(); $j("#sectionAccessBody").hide();'; break; } $output .= "// -------------- mm_hideSections :: End ------------- \n"; $e->output($output . "\n"); } } }
function mm_hideTabs($tabs, $roles = '', $templates = '') { global $modx; $e =& $modx->Event; // if we've been supplied with a string, convert it into an array $tabs = makeArray($tabs); // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if (useThisRule($roles, $templates)) { $output = " // ----------- Hide tabs -------------- \n"; foreach ($tabs as $tab) { switch ($tab) { case 'general': $output .= 'if (tpSettings.getSelectedIndex() == 0) { tpSettings.setSelectedIndex(1); } ' . "\n"; // if we are hiding the currently active tab, make another visible $output .= '$j("div#documentPane h2:nth-child(1)").hide(); ' . "\n"; $output .= '$j("#tabGeneral").hide();'; break; case 'settings': $output .= 'if (tpSettings.getSelectedIndex() == 1) { tpSettings.setSelectedIndex(0); } ' . "\n"; $output .= '$j("div#documentPane h2:nth-child(2)").hide(); ' . "\n"; $output .= '$j("#tabSettings").hide();'; break; // =< v1.0.0 only // =< v1.0.0 only case 'meta': if ($modx->hasPermission('edit_doc_metatags') && $modx->config['show_meta'] != "0") { $output .= 'if (tpSettings.getSelectedIndex() == 2) { tpSettings.setSelectedIndex(0); } ' . "\n"; $output .= '$j("div#documentPane h2:nth-child(3)").hide(); ' . "\n"; $output .= '$j("#tabMeta").hide(); '; } break; // Meta tags tab is removed by default in version 1.0.1+ but can still be enabled via a preference. // Access tab was only added in 1.0.1 // Since counting the tabs is the only way of determining this, we need to know if this has been activated // If meta tabs are active, the "access" tab is index 4 in the HTML; otherwise index 3. // If config['show_meta'] is NULL, this is a version before this option existed, e.g. < 1.0.1 // For versions => 1.0.1, 0 is the default value to not show them, 1 is the option to show them. // Meta tags tab is removed by default in version 1.0.1+ but can still be enabled via a preference. // Access tab was only added in 1.0.1 // Since counting the tabs is the only way of determining this, we need to know if this has been activated // If meta tabs are active, the "access" tab is index 4 in the HTML; otherwise index 3. // If config['show_meta'] is NULL, this is a version before this option existed, e.g. < 1.0.1 // For versions => 1.0.1, 0 is the default value to not show them, 1 is the option to show them. case 'access': $access_index = $modx->config['show_meta'] == "0" ? 3 : 4; $output .= 'if (tpSettings.getSelectedIndex() == ' . ($access_index - 1) . ') { tpSettings.setSelectedIndex(0); } ' . "\n"; $output .= '$j("div#documentPane h2:nth-child(' . $access_index . ')").hide(); ' . "\n"; $output .= '$j("#tabAccess").hide();'; break; } // end switch $e->output($output . "\n"); } // end foreach } // end if }
/** * mm_renameField * @version 1.2 (2013-05-16) * * Change the label for an element. * * @uses ManagerManager plugin 0.4. * * @param fields {comma separated string} - The name(s) of the document fields (or TVs) this should apply to. @required * @param newlabel {string} - The new text for the label. @required * @param roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). * @param templates {comma separated string} - Id of the templates to which this widget is applied (when this parameter is empty then widget is applied to the all templates). * @param newhelp {string} - New text for the help icon with this field or for comment with TV. The same restriction apply as when using mm_changeFieldHelp directly. * * @link http://code.divandesign.biz/modx/mm_renamefield/1.2 * * @copyright 2013 */ function mm_renameField($fields, $newlabel, $roles = '', $templates = '', $newhelp = '') { global $mm_fields, $modx; $e =& $modx->Event; // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { $fields = makeArray($fields); if (count($fields) == 0) { return; } $output = "// -------------- mm_renameField :: Begin ------------- \n"; foreach ($fields as $field) { $element = ''; switch ($field) { // Exceptions case 'keywords': $element = '$j("select[name*=keywords]").siblings("span.warning")'; break; case 'metatags': $element = '$j("select[name*=metatags]").siblings("span.warning")'; break; case 'hidemenu': case 'show_in_menu': $element = '$j("input[name=\'hidemenucheck\']").siblings("span.warning")'; break; case 'which_editor': $element = '$j("#which_editor").prev("span.warning")'; break; case 'content': $element = '$j("#content_header")'; break; case 'menuindex': $element = '$j("input[name=\'menuindex\']").parents("table:first").parents("td:first").prev("td").find("span.warning")'; break; // Ones that follow the regular pattern // Ones that follow the regular pattern default: if (isset($mm_fields[$field])) { $fieldtype = $mm_fields[$field]['fieldtype']; $fieldname = $mm_fields[$field]['fieldname']; $element = '$j("' . $fieldtype . '[name=\'' . $fieldname . '\']").parents("td:first").prev("td").children("span.warning")'; } break; } if ($element != '') { $output .= $element . '.contents().filter(function(){return this.nodeType === 3;}).replaceWith("' . jsSafe($newlabel) . '");'; } // If new help has been supplied, do that too if ($newhelp != '') { mm_changeFieldHelp($field, $newhelp, $roles, $templates); } } $output .= "// -------------- mm_renameField :: End ------------- \n"; $e->output($output . "\n"); } }
function createrecord() { if (isset($_POST['submit'])) { // Check for username password and avatar if ($_POST['password'] != null && $_POST['user'] != null) { //prepare for output processing function makeArray() { $salt = "supperDupperSalt"; $epass = md5($_POST['password'] . $salt); $euser = $_POST['user']; return array("USER NAME" => $euser, "Hashed PASSWORD with Dash of Salt" => $epass); } // Output Login Details to User echo "<h2>CONGRATULATIONS!</h2> Sign-up was successfull!"; echo "<table width=100% align=left border=0><tr><td>"; // CONVERT array into a variable for accessing $data = makeArray(); // FOREACH for displaying Array Contents created in makeArray Function foreach ($data as $atrribute => $data) { // echo "<p align=left><font color=#FF4136>{$attribute}</font>{$data}"; } // Process Avatar Photo for Upload $tmp_file = $_FILES['avatarfile']['tmp_name']; // Given a string containing the path to a file/directory, // the basename function will return the trailing name component. $targer_file = basename($_FILES['avatarfile']['name']); $upload_dir = "uploads"; // move_uploaded_file will return false if $tmp_file is not a valid upload file // or if it cannot be moved for any other reason if (move_uploaded_file($tmp_file, $upload_dir . "/" . $targer_file)) { echo "File uploaded successfully."; } else { echo "<br><br> AVATAR: Np photo was uploaded."; } echo "<br><br><a href='?action=home'>Please try logging in Now!</a>"; //close table echo "</td></tr></table>"; //connect to database from including file include "DBCredentials.php"; $salt = "supperDupperSalt"; $epass = md5($_POST['password'] . $salt); $euser = $_POST['user']; // Prepare statement for INSERT $stmt = $dbh->prepare("insert into users101 (username, password, avatar) \n values(:username, :password, :avatar)"); $stmt->bindParam(':username', $euser); $stmt->bindParam(':password', $epass); $stmt->bindParam(':avatar', $targer_file); $stmt->execute(); } else { echo "Sorry, you must submit ALL registration fields to proceed."; echo "<br><br></b><a href='?action=home'>Try again?</a><br><br>"; } } }
function mm_galleryLink($fields, $roles = '', $templates = '', $moduleid = '') { global $mm_fields, $modx, $content; $e =& $modx->Event; // if we've been supplied with a string, convert it into an array $fields = makeArray($fields); // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if (useThisRule($roles, $templates)) { $output = " // ----------- Gallery Link -------------- \n"; foreach ($fields as $field) { //ignore for now switch ($field) { // ignore fields that can't be converted case 'keywords': case 'metatags': case 'hidemenu': case 'which_editor': case 'template': case 'menuindex': case 'show_in_menu': case 'parent': case 'is_folder': case 'is_richtext': case 'log': case 'searchable': case 'cacheable': case 'clear_cache': case 'content_type': case 'content_dispo': case 'which_editor': $output .= ''; break; // default if not ignored // default if not ignored default: if (isset($mm_fields[$field])) { // Check the fields exist, so we're not writing JS for elements that don't exist $output .= 'var pid' . $mm_fields[$field]['fieldname'] . ' = "' . (!empty($content['id']) ? $content['id'] : 'false') . '";' . "\n"; $output .= 'var gl' . $mm_fields[$field]['fieldname'] . ' = $j("' . $mm_fields[$field]['fieldtype'] . '[name=' . $mm_fields[$field]['fieldname'] . ']");' . "\n"; $output .= 'if(pid' . $mm_fields[$field]['fieldname'] . ' != \'false\'){' . "\n"; $output .= ' var galleryLink = $j(\'<a href="' . $modx->config['base_url'] . MGR_DIR . '/index.php?a=112&id=' . $moduleid . '&action=view&content_id=\'+pid' . $mm_fields[$field]['fieldname'] . '+\'">Manage Photos</a>\').insertAfter(gl' . $mm_fields[$field]['fieldname'] . ');' . "\n"; $output .= '} else {' . "\n"; $output .= ' var galleryLink = $j(\'<p class="warning">You must save this page before you can manage the photos associated with it.</p>\').insertAfter(gl' . $mm_fields[$field]['fieldname'] . ');' . "\n"; $output .= '}' . "\n"; $output .= 'gl' . $mm_fields[$field]['fieldname'] . '.hide();' . "\n"; } break; } } $e->output($output . "\n"); } // end if }
/** * mm_synch_fields * @version 1.1 (2012-11-13) * * Synch two fields in real time. * * @uses ManagerManager plugin 0.4. * * @link http://code.divandesign.biz/modx/mm_synch_fields/1.1 * * @copyright 2012 */ function mm_synch_fields($fields, $roles = '', $templates = '') { global $modx, $mm_fields; $e =& $modx->Event; // if we've been supplied with a string, convert it into an array $fields = makeArray($fields); // We need at least 2 values if (count($fields) < 2) { return; } // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { $output = "// -------------- mm_synch_fields :: Begin ------------- \n"; $output .= ' synch_field[mm_sync_field_count] = new Array(); '; foreach ($fields as $field) { if (isset($mm_fields[$field])) { $fieldtype = $mm_fields[$field]['fieldtype']; $fieldname = $mm_fields[$field]['fieldname']; $valid_fieldtypes = array('input', 'textarea'); // Make sure we're dealing with an input if (!in_array($fieldtype, $valid_fieldtypes)) { break; } // Add this field to the array of fields being synched $output .= ' synch_field[mm_sync_field_count].push($j("' . $fieldtype . '[name=' . $fieldname . ']")); '; // Or we don't recognise it } else { break; } } // Output some javascript to sync these fields $output .= ' $j.each(synch_field[mm_sync_field_count], function(i, n){ $j.each(synch_field[mm_sync_field_count], function(j, m){ if (i != j){ n.keyup(function(){ m.val($j(this).val()); }); } }); }); mm_sync_field_count++; '; $output .= "// -------------- mm_synch_fields :: End ------------- \n"; $e->output($output . "\n"); } }
function mm_hideTemplates($tplIds, $roles = '', $templates = '') { global $modx; $e =& $modx->Event; $tplIds = makeArray($tplIds); if (useThisRule($roles, $templates)) { $output = " // ----------- Hide templates -------------- \n"; foreach ($tplIds as $tpl) { $output .= 'if ($j("select#template").val() != ' . $tpl . ') { ' . "\n"; $output .= '$j("select#template option[value=' . $tpl . ']").hide();' . "\n"; $output .= '}' . "\n"; } $e->output($output . "\n"); } }
/** * mm_hideTemplates * @version 1.1 (2012-11-13) * * Hide a template within the dropdown list of templates. * Based on code submitted by Metaller * * @uses ManagerManager plugin 0.4. * * @link http://code.divandesign.biz/modx/mm_hidetemplates/1.1 * * @copyright 2012 */ function mm_hideTemplates($tplIds, $roles = '', $templates = '') { global $modx; $e =& $modx->Event; $tplIds = makeArray($tplIds); if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { $output = "// -------------- mm_hideTemplates :: Begin ------------- \n"; foreach ($tplIds as $tpl) { $output .= 'if ($j("select#template").val() != ' . $tpl . '){ ' . "\n"; $output .= '$j("select#template option[value=' . $tpl . ']").remove();' . "\n"; $output .= '}' . "\n"; } $output .= "// -------------- mm_hideTemplates :: End ------------- \n"; $e->output($output . "\n"); } }
function mm_hideTabs($tabs, $roles = '', $templates = '') { global $modx; $e =& $modx->Event; // if we've been supplied with a string, convert it into an array $tabs = makeArray($tabs); // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if (useThisRule($roles, $templates)) { $output = " // ----------- Hide tabs -------------- \n"; foreach ($tabs as $tab) { switch ($tab) { case 'general': $output .= 'if (tpSettings.getSelectedIndex() == 0) { tpSettings.setSelectedIndex(1); } ' . "\n"; // if we are hiding the currently active tab, make another visible $output .= '$j("div#documentPane h2:nth-child(1)").hide(); ' . "\n"; $output .= '$j("#tabGeneral").hide();'; break; case 'settings': $output .= 'if (tpSettings.getSelectedIndex() == 1) { tpSettings.setSelectedIndex(0); } ' . "\n"; $output .= '$j("div#documentPane h2:nth-child(2)").hide(); ' . "\n"; $output .= '$j("#tabSettings").hide();'; break; // Version 1.0.0 only // Version 1.0.0 only case 'meta': if ($modx->hasPermission('edit_doc_metatags')) { $output .= 'if (tpSettings.getSelectedIndex() == 2) { tpSettings.setSelectedIndex(0); } ' . "\n"; $output .= '$j("div#documentPane h2:nth-child(3)").hide(); ' . "\n"; $output .= '$j("#tabMeta").hide(); '; } break; // Version 1.0.1 only // Version 1.0.1 only case 'access': $output .= 'if (tpSettings.getSelectedIndex() == 2) { tpSettings.setSelectedIndex(0); } ' . "\n"; $output .= '$j("div#documentPane h2:nth-child(3)").hide(); ' . "\n"; $output .= '$j("#tabPreview").hide();'; break; } // end switch $e->output($output . "\n"); } // end foreach } // end if }
/** * mm_widget_colors * @version 1.1 (2012-11-13) * * Adds a color selection widget to the specified TVs. * * @uses ManagerManager plugin 0.4. * * @link http://code.divandesign.biz/modx/mm_widget_colors/1.1 * * @copyright 2012 */ function mm_widget_colors($fields, $default = '#ffffff', $roles = '', $templates = '') { global $modx, $mm_fields, $mm_current_page; $e =& $modx->event; if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { $output = ''; // if we've been supplied with a string, convert it into an array $fields = makeArray($fields); // Which template is this page using? if (isset($content['template'])) { $page_template = $content['template']; } else { // If no content is set, it's likely we're adding a new page at top level. // So use the site default template. This may need some work as it might interfere with a default template set by MM? $page_template = $modx->config['default_template']; } // Does this page's template use any of these TVs? If not, quit. $tv_count = tplUseTvs($mm_current_page['template'], $fields); if ($tv_count === false) { return; } // Insert some JS $output .= includeJs($modx->config['base_url'] . 'assets/plugins/managermanager/widgets/colors/farbtastic.js'); // Insert some CSS $output .= includeCss($modx->config['base_url'] . 'assets/plugins/managermanager/widgets/colors/farbtastic.css'); // Go through each of the fields supplied foreach ($fields as $tv) { $tv_id = $mm_fields[$tv]['fieldname']; $output .= ' // ----------- Color widget for ' . $tv_id . ' -------------- $j("#' . $tv_id . '").css("background-image","none"); $j("#' . $tv_id . '").after(\'<div id="colorpicker' . $tv_id . '"></div>\'); if ($j("#' . $tv_id . '").val() == ""){ $j("#' . $tv_id . '").val("' . $default . '"); } $j("#colorpicker' . $tv_id . '").farbtastic("#' . $tv_id . '"); $j("#colorpicker' . $tv_id . '").mouseup(function(){ // mark the document as dirty, or the value wont be saved $j("#' . $tv_id . '").trigger("change"); }); '; } $e->output($output . "\n"); } }
/** * mm_widget_colors * @version 1.2 (2013-12-11) * * A widget for ManagerManager plugin that allows text field to be turned into a color picker storing a chosen hex value in the field on the document editing page. * * @uses ManagerManager plugin 0.6. * * @param $fields {comma separated string} - The name(s) of the template variables this should apply to. @required * @param $default {string} - Which color in hex format should be selected by default in new documents. This is only used in situations where the TV does not have a default value specified in the TV definition. Default: '#ffffff'. * @param $roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). Default: ''. * @param $templates {comma separated string} - Id of the templates to which this widget is applied (when this parameter is empty then widget is applied to the all templates). Default: ''. * * @event OnDocFormPrerender * @event OnDocFormRender * * @link http://code.divandesign.biz/modx/mm_widget_colors/1.2 * * @copyright 2013 */ function mm_widget_colors($fields, $default = '#ffffff', $roles = '', $templates = '') { if (!useThisRule($roles, $templates)) { return; } global $modx; $e =& $modx->Event; $output = ''; if ($e->name == 'OnDocFormPrerender') { $output .= includeJsCss($modx->config['base_url'] . 'assets/plugins/managermanager/widgets/colors/farbtastic.js', 'html', 'farbtastic', '1.2'); $output .= includeJsCss($modx->config['base_url'] . 'assets/plugins/managermanager/widgets/colors/farbtastic.css', 'html'); $e->output($output); } else { if ($e->name == 'OnDocFormRender') { global $mm_current_page, $mm_fields; // if we've been supplied with a string, convert it into an array $fields = makeArray($fields); // Does this page's template use any of these TVs? If not, quit. $tv_count = tplUseTvs($mm_current_page['template'], $fields); if ($tv_count === false) { return; } $output .= "//---------- mm_widget_colors :: Begin -----\n"; // Go through each of the fields supplied foreach ($fields as $tv) { $tv_id = $mm_fields[$tv]['fieldname']; $output .= ' $j("#' . $tv_id . '").css("background-image","none"); $j("#' . $tv_id . '").after(\'<div id="colorpicker' . $tv_id . '"></div>\'); if ($j("#' . $tv_id . '").val() == ""){ $j("#' . $tv_id . '").val("' . $default . '"); } $j("#colorpicker' . $tv_id . '").farbtastic("#' . $tv_id . '"); $j("#colorpicker' . $tv_id . '").mouseup(function(){ // mark the document as dirty, or the value wont be saved $j("#' . $tv_id . '").trigger("change"); }); '; } $output .= "//---------- mm_widget_colors :: End -----\n"; $e->output($output); } } }
/** * mm_hideTabs * @version 1.2 (2014-12-01) * * @desc A widget for ManagerManager plugin that allows one or a few default tabs to be hidden on the document edit page. * * @uses ManagerManager plugin 0.6.2. * * @param $tabs {'general'; 'settings'; 'access'} - The id(s) of the tab(s) this should apply to. @required * @param $roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). Default: ''. * @param $templates {comma separated string} - Id of the templates to which this widget is applied (when this parameter is empty then widget is applied to the all templates). Default: ''. * * @event OnDocFormRender * * @link http://code.divandesign.biz/modx/mm_hidetabs/1.2 * * @copyright 2014, DivanDesign * http://www.DivanDesign.biz */ function mm_hideTabs($tabs, $roles = '', $templates = '') { global $modx; $e =& $modx->Event; // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { $output = "//---------- mm_hideTabs :: Begin -----\n"; // if we've been supplied with a string, convert it into an array $tabs = makeArray($tabs); foreach ($tabs as $tab) { //meta for =< v1.0.0 only if ($tab != 'meta' || $modx->hasPermission('edit_doc_metatags') && $modx->config['show_meta'] != '0') { $output .= ' var $mm_hideTabs_tabElement = $j("#' . prepareTabId($tab) . '"); //If the element exists if ($mm_hideTabs_tabElement.length > 0){ //Hide the tab element $mm_hideTabs_tabElement.hide(); //Hide the tab link $j($mm_hideTabs_tabElement.get(0).tabPage.tab).hide(); } '; } } $output .= ' //All tabs var $mm_hideTabs_allTabs = $j(); for (var i = 0; i < tpSettings.pages.length - 1; i++){ $mm_hideTabs_allTabs = $mm_hideTabs_allTabs.add(tpSettings.pages[i].tab); } //If the active tab is hidden if ($j(tpSettings.pages[tpSettings.getSelectedIndex()].tab).is(":hidden")){ //Activate the first visible tab $mm_hideTabs_allTabs.filter(":visible").eq(0).trigger("click"); } '; $output .= "//---------- mm_hideTabs :: End -----\n"; $e->output($output); } }
function createrecord() { if ($_POST['password'] != null && $_POST['user'] != null) { function makeArray() { $salt = 'SuperYanely\'sSaltHash'; $epass = md5($_POST['password'] . $salt); $euser = $_POST['user']; return array('User Name' => $euser, 'Hashed Password' => $epass); } echo "<h2>Congratulations!</h2> Your membership account sign-up was successful"; echo "<table width=100% align=left border=0><tr><td>"; $data = makeArray(); foreach ($data as $attribute => $data) { echo "<p align=left><font color = #ff4136>{$attribute}</font>: {$data}"; } $tmp_file = $_FILES['avatarfile']['tmp_name']; $target_file = basename($_FILES['avatarfile']['name']); $upload_dir = "uploads"; if (move_uploaded_file($tmp_file, $upload_dir . "/" . $target_file)) { echo "<br>File uploaded successfully."; echo "<br><br>Your Avatar Photo: " . $target_file; echo "<br><a href=\"?action=profile\"><img src=\"uploads/" . $target_file . "\" class=\"left userPhoto\" width=\"200\"/></a><br>"; } else { echo "<br><br>No Avatar uploaded"; } echo "<br><a href='?action=home'>Please try logging in Now!</a>"; echo "</td></tr></table>"; include 'DBCredentials.php'; $salt = 'SuperYanely\'sSaltHash'; $epass = md5($_POST['password'] . $salt); $euser = $_POST['user']; $stmt = $dbh->prepare("insert into users101 (username, password, avatar) values(:username, :password, :avatar)"); $stmt->bindParam(':username', $euser); $stmt->bindParam(':password', $epass); $stmt->bindParam(':avatar', $target_file); $stmt->execute(); } else { echo "Sorry, you must submit ALL registration fields to proceed.<br>"; echo "<a href='?action=home'>Try again?</a><br>"; } }
/** * mm_ddGMap * @version 1.2b (2014-05-14) * * @desc Widget for ManagerManager plugin allowing Google Maps integration. * * @uses ManagerManager plugin 0.6.1. * * @param $tvs {comma separated string} - TV names to which the widget is applied. @required * @param $roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). Default: ''. * @param $templates {comma separated string} - Id of the templates to which this widget is applied (when this parameter is empty then widget is applied to the all templates). Default: ''. * @param $w {'auto'; integer} - Width of the map container. Default: 'auto'. * @param $h {integer} - Height of the map container. Default: 400. * @param $hideField {0; 1} - Original coordinates field hiding status (1 — hide, 0 — show). Default: 1. * * @link http://code.divandesign.biz/modx/mm_ddgmap/1.2b * * @copyright 2014, DivanDesign * http://www.DivanDesign.biz */ function mm_ddGMap($tvs, $roles = '', $templates = '', $w = 'auto', $h = '400', $hideField = true) { if (!useThisRule($roles, $templates)) { return; } global $modx; $e =& $modx->Event; if ($e->name == 'OnDocFormPrerender') { global $modx_lang_attribute; //The main js file including $output = includeJsCss($modx->config['site_url'] . 'assets/plugins/managermanager/widgets/ddgmap/jquery.ddMM.mm_ddGMap.js', 'html', 'jquery.ddMM.mm_ddGMap', '1.0'); //The Google.Maps library including $output .= includeJsCss('http://maps.google.com/maps/api/js?sensor=false&hl=' . $modx_lang_attribute . '&callback=mm_ddGMap_init', 'html', 'maps.google.com', '0'); $e->output($output); } else { if ($e->name == 'OnDocFormRender') { global $mm_current_page; $output = ''; $tvs = makeArray($tvs); $usedTvs = tplUseTvs($mm_current_page['template'], $tvs, '', 'id', 'name'); if ($usedTvs == false) { return; } $output .= "//---------- mm_ddGMap :: Begin -----\n"; //Iterate over supplied TVs instead of doing so to the result of tplUseTvs() to maintain rendering order. foreach ($tvs as $tv) { //If this $tv is used in a current template if (isset($usedTvs[$tv])) { $output .= ' $j("#tv' . $usedTvs[$tv]['id'] . '").mm_ddGMap({ hideField: ' . intval($hideField) . ', width: "' . $w . '", height: "' . $h . '" }); '; } } $output .= "//---------- mm_ddGMap :: End -----\n"; $e->output($output); } } }
/** * mm_ddYMap * @version 1.4.3 (2013-12-10) * * @desc A widget for ManagerManager plugin allowing Yandex Maps integration. * * @uses ManagerManager plugin 0.6. * * @param $tvs {comma separated string} - TV names to which the widget is applied. @required * @param $roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). Default: ''. * @param $templates {comma separated string} - Id of the templates to which this widget is applied (when this parameter is empty then widget is applied to the all templates). Default: ''. * @param $w {'auto'; integer} - Width of the map container. Default: 'auto'. * @param $h {integer} - Height of the map container. Default: 400. * @param $hideField {boolean} - Original coordinates field hiding status (true — hide, false — show). Default: true. * * @event OnDocFormPrerender * @event OnDocFormRender * * @link http://code.divandesign.biz/modx/mm_ddymap/1.4.3 * * @copyright 2013, DivanDesign * http://www.DivanDesign.biz */ function mm_ddYMap($tvs, $roles = '', $templates = '', $w = 'auto', $h = '400', $hideField = true) { if (!useThisRule($roles, $templates)) { return; } global $modx; $e =& $modx->Event; if ($e->name == 'OnDocFormPrerender') { //The main js file including $output = includeJsCss($modx->config['site_url'] . 'assets/plugins/managermanager/widgets/ddymap/jquery.ddMM.mm_ddYMap.js', 'html', 'jquery.ddMM.mm_ddYMap', '1.0.2'); //The Yandex.Maps library including $output .= includeJsCss('http://api-maps.yandex.ru/2.0/?load=package.full&lang=ru-RU&onload=mm_ddYMap_init', 'html', 'api-maps.yandex.ru', '2.0'); $e->output($output); } else { if ($e->name == 'OnDocFormRender') { global $mm_current_page; $output = ''; //if we've been supplied with a string, convert it into an array $tvs = makeArray($tvs); $usedTvs = tplUseTvs($mm_current_page['template'], $tvs, '', 'id', 'name'); if ($usedTvs == false) { return; } $output .= "//---------- mm_ddYMap :: Begin -----\n"; //Iterate over supplied TVs instead of doing so to the result of tplUseTvs() to maintain rendering order. foreach ($tvs as $tv) { //If this $tv is used in a current template if (isset($usedTvs[$tv])) { $output .= ' $j("#tv' . $usedTvs[$tv]['id'] . '").mm_ddYMap({ hideField: ' . intval($hideField) . ', width: "' . $w . '", height: "' . $h . '" }); '; } } $output .= "//---------- mm_ddYMap :: End -----\n"; $e->output($output); } } }
function mm_widget_template($fields, $other_param = 'defaultValue', $roles = '', $templates = '') { global $modx, $content, $mm_fields; $e =& $modx->Event; if (useThisRule($roles, $templates)) { // Your output should be stored in a string, which is outputted at the end // It will be inserted as a Javascript block (with jQuery), which is executed on document ready $output = ''; // if we've been supplied with a string, convert it into an array $fields = makeArray($fields); // You might want to check whether the current page's template uses the TVs that have been // supplied, to save processing page which don't contain them // Which template is this page using? if (isset($content['template'])) { $page_template = $content['template']; } else { // If no content is set, it's likely we're adding a new page at top level. // So use the site default template. This may need some work as it might interfere with a default template set by MM? $page_template = $modx->config['default_template']; } $count = tplUseTvs($content['template'], $fields); if ($count == false) { return; } // We always put a JS comment, which makes debugging much easier $output .= "// -------------- Widget name ------------- \n"; // We have functions to include JS or CSS external files you might need // The standard ModX API methods don't work here $output .= includeJs('/assets/plugins/managermanager/widgets/template/javascript.js'); $output .= includeCss('/assets/plugins/managermanager/widgets/template/styles.css'); // Do something for each of the fields supplied foreach ($fields as $targetTv) { // If it's a TV, we may need to map the field name, to what it's ID is. // This can be obtained from the mm_fields array $tv_id = $mm_fields[$targetTv]['fieldname']; } } // end if $e->output($output . "\n"); // Send the output to the browser }
/** * mm_widget_accessdenied * @version 1.1 (2012-11-13) * * Close access for some documents by ids. * Icon by designmagus.com * Originally written by Metaller * * @uses ManagerManager plugin 0.4. * * @link http://code.divandesign.biz/modx/mm_widget_accessdenied/1.1 * * @copyright 2012 */ function mm_widget_accessdenied($ids = '', $message = '', $roles = '') { global $modx, $content; $e =& $modx->event; if (empty($message)) { $message = '<span>Access denied</span>Access to current document closed for security reasons.'; } if ($e->name == 'OnDocFormRender' && useThisRule($roles)) { $docid = (int) $_GET[id]; $ids = makeArray($ids); $output = "// -------------- accessdenied widget include ------------- \n"; if (in_array($docid, $ids)) { $output .= includeCss($modx->config['base_url'] . 'assets/plugins/managermanager/widgets/accessdenied/accessdenied.css'); $output .= ' $j("input, div, form[name=mutate]").remove(); // Remove all content from the page $j("body").prepend(\'<div id="aback"><div id="amessage">' . $message . '</div></div>\'); $j("#aback").css({height: $j("body").height()} );'; } $e->output($output . "\n"); } }
function mm_widget_googlemap($fields, $googleApiKey = '', $default = '', $roles = '', $templates = '') { global $modx, $mm_fields, $mm_current_page, $modx_lang_attribute; $e =& $modx->event; if (useThisRule($roles, $templates)) { $output = ''; $fields = makeArray($fields); $count = tplUseTvs($mm_current_page['template'], $fields); if ($count == false) { return; } $output .= "// -------------- googlemap widget ------------- \n"; $output .= includeJs($modx->config['base_url'] . 'assets/plugins/managermanager/widgets/googlemap/googlemap.js'); $output .= includeJs("http://maps.google.com/maps?file=api&sensor=false&key={$googleApiKey}&async=2&hl={$modx_lang_attribute}"); foreach ($fields as $targetTv) { $tv_id = $mm_fields[$targetTv]['fieldname']; $output .= "googlemap('{$tv_id}','{$default}');"; } $e->output($output . "\n"); // Send the output to the browser } }
/** * mm_ddAutoFolders * @version 1.2 (2014-04-18) * * @desc Automatically move documents (OnBeforeDocFormSave event) based on their date (publication date; any date in tv) into folders of year and month (like 2012/02/). If folders (documents) of year and month doesn`t exist they are created automatically OnBeforeDocFormSave event. * * @uses ManagerManager plugin 0.5 * * @param $roles {comma separated string} - List of role IDs this should be applied to. Leave empty (or omit) for all roles. Default: ''. * @param $templates {comma separated string} - List of template IDs this should be applied to. Leave empty (or omit) for all templates. Default: ''. * @param $yearsParents {comma separated string} - IDs of ultimate parents (parents of the years). @required * @param $dateSource {string} - Name of template variable which contains the date. Default: 'pub_date'. * @param $yearFields {string: JSON} - Document fields and/or TVs that are required to be assigned to year documents. An associative array in JSON where the keys and values correspond field names and values respectively. Default: '{"template":0,"published":0}'. * @param $monthFields {string: JSON} - Document fields and/or TVs that are required to be assigned to month documents. An associative array in JSON where the keys and values correspond field names and values respectively. Default: '{"template":0,"published":0}'. * @param $yearPublished {0; 1} - Note this is a deprecated parameter, please, use “$yearFields”. Whether the year documents should be published? Default: —. * @param $monthPublished {0; 1} - Note this is a deprecated parameter, please, use “$monthFields”. Whether the month documents should be published? Default: —. * @param $numericMonth {boolean} - Numeric aliases for month documents. Default: false. * * @link http://code.divandesign.biz/modx/mm_ddautofolders/1.2 * * @copyright 2014, DivanDesign * http://www.DivanDesign.biz */ function mm_ddAutoFolders($roles = '', $templates = '', $yearsParents = '', $dateSource = 'pub_date', $yearFields = '{"template":0,"published":0}', $monthFields = '{"template":0,"published":0}', $yearPublished = NULL, $monthPublished = NULL, $numericMonth = false) { global $modx, $pub_date, $parent, $mm_current_page, $tmplvars, $modx_lang_attribute; $e =& $modx->Event; //$yearsParents is required if ($yearsParents != '' && $e->name == 'OnBeforeDocFormSave' && useThisRule($roles, $templates)) { $defaultFields = array('template' => 0, 'published' => 0); //Функция аналогична методу «$modx->getParentIds» за исключением того, что родитель = 0 тоже выставляется function getParentIds($id) { global $modx; $parents = $modx->getParentIds($id); //Если текущего id нет в массиве, значит его родитель = 0 if (!isset($parents[$id])) { $parents[$id] = 0; //Если текущий документ есть, а его родителя нет, значит родитель родителя = 0 } else { if (!isset($parents[$parents[$id]])) { $parents[$parents[$id]] = 0; } } return $parents; } //Получаем всех родителей текущего документа (или его родителя, если это новый документ) $allParents = getParentIds(is_numeric($e->params['id']) ? $e->params['id'] : $parent); $yearsParents = makeArray($yearsParents); //Перебираем переданных родителей foreach ($yearsParents as $key => $val) { //Если текущий документ не принадлежит к переданному родителю, значит этот родитель лишний if (!isset($allParents[$val])) { unset($yearsParents[$key]); } } //Если остался хоть один родитель (а остаться должен только один) if (count($yearsParents) > 0) { //Сбрасываем ключи $yearsParents = array_values($yearsParents); //Если документ не относится ни к одному переданному родителю, то ничего делать не нужно } else { return; } //Текущее правило $rule = array(); //Дата $ddDate = array(); //Если задано, откуда брать дату и это не дата публикации, пытаемся найти в tv`шках if ($dateSource && $dateSource != 'pub_date') { //Получаем tv с датой для данного шаблона $dateTv = tplUseTvs($mm_current_page['template'], $dateSource); //Если tv удалось получить, такая tv есть и есть её значение if ($dateTv && $dateTv[0]['id'] && $tmplvars[$dateTv[0]['id']] && $tmplvars[$dateTv[0]['id']][1]) { //Если дата в юникс-времени if (is_numeric($tmplvars[$dateTv[0]['id']][1])) { $ddDate['date'] = $tmplvars[$dateTv[0]['id']][1]; } else { //Пытаемся преобразовать в unix-время $ddDate['date'] = strtotime($tmplvars[$dateTv[0]['id']][1]); } } } else { $ddDate['date'] = $pub_date; } //Если не задана дата, выбрасываем if (!$ddDate['date']) { return; } //Псевдонимы родителей (какие должны быть) //Год в формате 4 цифры $ddDate['y'] = date('Y', $ddDate['date']); //Псевдоним месяца (порядковый номер номер с ведущим нолём или название на английском) $ddDate['m'] = $numericMonth ? date('m', $ddDate['date']) : strtolower(date('F', $ddDate['date'])); //Порядковый номер месяца $ddDate['n'] = date('n', $ddDate['date']); //Если язык админки — русский if (strtolower($modx_lang_attribute) == 'ru') { //Все месяцы на русском $ruMonthes = array('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'); //Название месяца на русском $ddDate['mTitle'] = $ruMonthes[$ddDate['n'] - 1]; } else { //Просто запишем на английском $ddDate['mTitle'] = date('F', $ddDate['date']); } //Получаем список групп документов родителя (пригодится при создании годов и месяцев) $docGroups = $modx->db->getColumn('document_group', $modx->db->select('`document_group`', ddTools::$tables['document_groups'], '`document` = ' . $yearsParents[0])); $yearId = 0; $monthId = 0; //Получаем годы (непосредственных детей корневого родителя) $years = ddTools::getDocumentChildrenTVarOutput($yearsParents[0], array('id'), false, 'menuindex', 'ASC', '', 'alias'); if (isset($years[$ddDate['y']])) { //Получаем id нужного нам года $yearId = $years[$ddDate['y']]['id']; } //For backward compatibility if (is_numeric($yearFields)) { $yearFields = '{"template":' . $yearFields . ',"published":0}'; } if (is_numeric($monthFields)) { $monthFields = '{"template":' . $monthFields . ',"published":0}'; } $yearFields = json_decode($yearFields, true); $monthFields = json_decode($monthFields, true); if (!is_array($yearFields)) { $yearFields = $defaultFields; } if (!is_array($monthFields)) { $monthFields = $defaultFields; } //For backward compatibility too if ($yearPublished !== NULL) { $yearFields['published'] = $yearPublished; } if ($monthPublished !== NULL) { $monthFields['published'] = $monthPublished; } //Если нужный год существует if ($yearId != 0) { //Проставим году нужные параметры ddTools::updateDocument($yearId, array_merge($yearFields, array('isfolder' => 1))); //Получаем месяцы (непосредственных детей текущего года) $months = ddTools::getDocumentChildrenTVarOutput($yearId, array('id'), false, 'menuindex', 'ASC', '', 'alias'); if (isset($months[$ddDate['m']])) { //Получаем id нужного нам месяца $monthId = $months[$ddDate['m']]['id']; } //Если нужный год не существует } else { //Создадим его $yearId = ddTools::createDocument(array_merge($yearFields, array('pagetitle' => $ddDate['y'], 'alias' => $ddDate['y'], 'parent' => $yearsParents[0], 'isfolder' => 1, 'menuindex' => $ddDate['y'] - 2000)), $docGroups); } //Если нужный месяц существует if ($monthId != 0) { //Проставим месяцу нужные параметры ddTools::updateDocument($monthId, array_merge($monthFields, array('isfolder' => 1))); //Если нужный месяц не существует (на всякий случай проверим ещё и год) } else { if ($yearId) { $monthId = ddTools::createDocument(array_merge($monthFields, array('pagetitle' => $ddDate['mTitle'], 'alias' => $ddDate['m'], 'parent' => $yearId, 'isfolder' => 1, 'menuindex' => $ddDate['n'] - 1)), $docGroups); } } //Ещё раз на всякий случай проверим, что с месяцем всё хорошо if ($monthId && $monthId != $parent) { $parent = $monthId; } } }
/** * mm_ddGMap * @version 1.1.1 (2012-11-13) * * Позволяет интегрировать карту Google Maps для получения координат. * * @uses ManagerManager plugin 0.4. * * @param $tvs {string; comma separated string} - Имя TV, для которой необходимо применить виджет. * @param $roles {string; comma separated string} - Роли, для которых необходимо применить виждет, пустое значение — все роли. По умолчанию: ''. * @param $templates {string; comma separated string} - Шаблоны, для которых необходимо применить виджет, пустое значение — все шаблоны. По умолчанию: ''. * @param $w {string; integer} - Ширина контейнера с картой. По умолчанию: 'auto'. * @param $h {integer} - Высота контейнера с картой. По умолчанию: 400. * @param $hideField {boolean} - Необходимо ли скрывать оригинальное текстовое поле с координатами. По умолчанию: true. * * @link http://code.divandesign.biz/modx/mm_ddgmap/1.1.1 * * @copyright 2012, DivanDesign * http://www.DivanDesign.biz */ function mm_ddGMap($tvs, $roles = '', $templates = '', $w = 'auto', $h = '400', $hideField = true) { global $modx, $content, $mm_fields, $modx_lang_attribute; $e =& $modx->Event; if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { $output = ''; // if we've been supplied with a string, convert it into an array $tvs = makeArray($tvs); // Which template is this page using? if (isset($content['template'])) { $page_template = $content['template']; } else { // If no content is set, it's likely we're adding a new page at top level. // So use the site default template. This may need some work as it might interfere with a default template set by MM? $page_template = $modx->config['default_template']; } $tvs = tplUseTvs($page_template, $tvs); if ($tvs == false) { return; } $style = 'width: ' . $w . 'px; height: ' . $h . 'px; position: relative; border: 1px solid #c3c3c3;'; // We always put a JS comment, which makes debugging much easier $output .= "// -------------- mm_ddGMap :: Begin ------------- \n"; // Do something for each of the fields supplied foreach ($tvs as $tv) { // If it's a TV, we may need to map the field name, to what it's ID is. // This can be obtained from the mm_fields array $tv_id = 'tv' . $tv['id']; $output .= ' //TV с координатами var coordFieldId = "' . $tv_id . '", $coordinatesField = $j("#" + coordFieldId); //Координаты var ddLatLng = $coordinatesField.val(); //Родитель var $coordFieldParent = $coordinatesField.parents("tr:first"); //Запоминаем название поля var sectionName = $coordFieldParent.find(".warning").text(); //Скрываем родителя и разделитель $coordFieldParent.hide().prev("tr").hide(); //Контейнер для карты var $sectionConteiner = $j("<div class=\\"sectionHeader\\">" + sectionName + "</div><div class=\\"sectionBody tmplvars\\"><div class=\\"ddGMap" + coordFieldId + "\\" style=\\"' . $style . '\\"></div></div>"); //Добавляем контейнер $coordinatesField.parents(".tab-page:first").append($sectionConteiner); //Если скрывать не надо, засовываем перед картой if (!' . intval($hideField) . '){ $coordinatesField.insertBefore(".ddGMap" + coordFieldId); } //Если координаты не заданны, то задаём дефолт if(ddLatLng == "") ddLatLng = "55.19396010947335,61.3670539855957"; ddLatLng = ddLatLng.split(","); //Callback функция для GM window.ddgminitialize = function(){ var GM = google.maps; var myOptions = { zoom: 15, center: new GM.LatLng(ddLatLng[0],ddLatLng[1]), mapTypeId: GM.MapTypeId.ROADMAP, streetViewControl: false, scrollwheel: false }; var map = new GM.Map($sectionConteiner.find(".ddGMap" + coordFieldId).get(0), myOptions); //Добавляем маркер на карту var GMMarker = new GM.Marker({ position: new GM.LatLng(ddLatLng[0],ddLatLng[1]), map: map, draggable: true }); //При перетаскивании маркера GM.event.addListener(GMMarker, "drag", function(event){ var position = event.latLng;//Координаты $coordinatesField.val(position.lat() + "," + position.lng());//Сохраняем значение в поле }); //При клике на карте GM.event.addListener(map, "click", function(event){ var position = event.latLng;//Новые координаты GMMarker.setPosition(position);//Меняем позицию маркера map.setCenter(position);//Центрируем карту на маркере $coordinatesField.val(position.lat() + "," + position.lng());//Сохраняем значение в поле }); }; //Подключаем карту, вызываем callback функцию $j(window).on("load.ddEvents", function(){ $j("body").append("<script type=\\"text/javascript\\" src=\\"http://maps.google.com/maps/api/js?sensor=false&hl=' . $modx_lang_attribute . '&callback=ddgminitialize\\">"); }); '; } $output .= "// -------------- mm_ddGMap :: End ------------- \n"; $e->output($output . "\n"); } }
/** * mm_ddMultipleFields * @version 4.6 (2014-10-24) * * @desc Widget for plugin ManagerManager that allows you to add any number of fields values (TV) in one document (values is written as one with using separator symbols). For example: a few images. * * @uses ManagerManager plugin 0.6.3. * * @param $tvs {comma separated string} - Names of TV for which the widget is applying. @required * @param $roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). Default: ''. * @param $templates {comma separated string} - Templates IDs for which the widget is applying (empty value means the widget is applying to all templates). Default: ''. * @param $columns {comma separated string} - Column types: field — field type column; text — text type column; textarea — multiple lines column; richtext — column with rich text editor; date — date column; id — hidden column containing unique id; select — list with options (parameter “columnsData”). Default: 'field'. * @param $columnsTitle {comma separated string} - Columns titles. Default: ''. * @param $colWidth {comma separated string} - Columns width (one value can be set). Default: 180; * @param $splY {string} - Strings separator. Default: '||'. * @param $splX {string} - Columns separator. Default: '::'. * @param $imgW {integer} - Maximum value of image preview width. Default: 300. * @param $imgH {integer} - Maximum value of image preview height. Default: 100. * @param $minRow {integer} - Minimum number of strings. Default: 0. * @param $maxRow {integer} - Maximum number of strings. Default: 0 (без лимита). * @param $columnsData {separated string} - List of valid values in json format (with “||”). Default: ''. Example: '[['','No selected'],['0','No'],['1','Yes',1]]' * * @event OnDocFormPrerender * @event OnDocFormRender * * @link http://code.divandesign.biz/modx/mm_ddmultiplefields/4.5.1 * * @copyright 2014, DivanDesign * http://www.DivanDesign.biz */ function mm_ddMultipleFields($tvs = '', $roles = '', $templates = '', $columns = 'field', $columnsTitle = '', $colWidth = '180', $splY = '||', $splX = '::', $imgW = 300, $imgH = 100, $minRow = 0, $maxRow = 0, $columnsData = '', $options = array()) { if (!useThisRule($roles, $templates)) { return; } if (is_array($options)) { $options = json_encode($options); } global $modx; $e =& $modx->Event; $output = ''; $site = $modx->config['site_url']; $widgetDir = $site . 'assets/plugins/managermanager/widgets/ddmultiplefields/'; if ($e->name == 'OnDocFormPrerender') { global $_lang; $output .= includeJsCss($site . 'assets/plugins/managermanager/js/jquery-ui-1.10.3.min.js', 'html', 'jquery-ui', '1.10.3'); $output .= includeJsCss($widgetDir . 'ddmultiplefields.css', 'html'); $output .= includeJsCss($widgetDir . 'jquery.ddMM.mm_ddMultipleFields.js', 'html', 'jquery.ddMM.mm_ddMultipleFields', '1.1.1'); $output .= includeJsCss('$j.ddMM.lang.edit = "' . $_lang['edit'] . '";$j.ddMM.lang.confirm_delete_record = "' . $_lang["confirm_delete_record"] . '";', 'html', 'mm_ddMultipleFields_plain', '1', true, 'js'); $e->output($output); } else { if ($e->name == 'OnDocFormRender') { global $mm_current_page; if ($columnsData) { $columnsDataTemp = explode('||', $columnsData); $columnsData = array(); foreach ($columnsDataTemp as $value) { //Евалим знение и записываем результат или исходное значени $eval = @eval($value); $columnsData[] = $eval ? addslashes(json_encode($eval)) : addslashes($value); } //Сливаем в строку, что бы передать на клиент $columnsData = implode('||', $columnsData); } //Стиль превью изображения $imgW = $imgW . (is_numeric($imgW) ? "px" : ""); $imgH = $imgH . (is_numeric($imgH) ? "px" : ""); $stylePrewiew = "max-width:{$imgW}; max-height:{$imgH}; margin: 4px 0; cursor: pointer;"; $tvsMas = tplUseTvs($mm_current_page['template'], $tvs, 'image,file,text,email,textarea', 'id,type'); if ($tvsMas == false) { return; } $output .= "//---------- mm_ddMultipleFields :: Begin -----\n"; //For backward compatibility $columns = makeArray($columns); //Находим колонки, заданные как «field», теперь их нужно будет заменить на «image» и «file» соответственно $columns_fieldIndex = array_keys($columns, 'field'); foreach ($tvsMas as $tv) { //For backward compatibility if ($tv['type'] == 'image' || $tv['type'] == 'file') { //Проходимся по всем колонкам «field» и заменяем на соответствующий тип foreach ($columns_fieldIndex as $val) { $columns[$val] = $tv['type']; } } $output .= ' $j("#tv' . $tv['id'] . '").mm_ddMultipleFields({ splY: "' . $splY . '", splX: "' . $splX . '", coloumns: "' . implode(',', $columns) . '", coloumnsTitle: "' . $columnsTitle . '", coloumnsData: "' . $columnsData . '", colWidth: "' . $colWidth . '", imageStyle: "' . $stylePrewiew . '", minRow: "' . $minRow . '", maxRow: "' . $maxRow . '", options: ' . $options . ' }); '; } //Поругаемся if (!empty($columns_fieldIndex)) { $modx->logEvent(1, 2, '<p>You are currently using the deprecated column type “field”. Please, replace it with “image” or “file” respectively.</p><p>The plugin has been called in the document with template id ' . $mm_current_page['template'] . '.</p>', 'ManagerManager: mm_ddMultipleFields'); } $output .= "//---------- mm_ddMultipleFields :: End -----\n"; $e->output($output); } } }
function makeSqlList($arr) { global $modx; $arr = makeArray($arr); foreach ($arr as $k => $tv) { //if (substr($tv, 0, 2) == 'tv') {$tv=substr($tv,2);} $arr[$k] = "'" . $modx->db->escape($tv) . "'"; // Escape them for MySQL } $sql = " (" . implode(',', $arr) . ") "; return $sql; }
//check to see if session variables for username, password is null if ($_SESSION['pass_word'] != null && $_SESSION['user_name'] != null) { //read in all form fields into an "associative" array & return array for processing output function makeArray() { $epass = $_SESSION['pass_word']; //already salted from earlier $euser = $_SESSION['user_name']; $avatarfile = $_SESSION['avatar_file']; return array("Username: "******"Hashed Password w/Salt" => $epass, "Avatar" => $avatarfile); } //output login details to user echo "<h2> User Profile Page - Welcome!</h2>"; echo "<table width=100% align=left border=0><tr><td>"; //convert array into variable $data = makeArray(); //foreach for displaying array contents created in makeArray function foreach ($data as $attribute => $data) { echo "<p align=left><font color=#FF4136>{$attribute}</font>: {$data}"; } //if $_SESSION variable for avatar is not missing, show it //other wise, give message: no photo uploaded if (!empty($_SESSION['avatar_file'])) { echo "<br/><br/>Your Avatar Photo: " . $_SESSION['avatar_file']; echo "<br/><br/><img src='" . "uploads" . "/" . $_SESSION['avatar_file'] . "' width='200'/>"; } else { echo "<br/><br/>Avatar: No photo was uploaded."; } echo "</td></tr></table>"; } else { echo "Sorry, you are not currently logged in.<br><br>";
/** * mm_inherit * @version 1.1 (2012-11-13) * * Inherit values from a parent. * * @uses ManagerManager plugin 0.4. * * @link http://code.divandesign.biz/modx/mm_inherit/1.1 * * @copyright 2012 */ function mm_inherit($fields, $roles = '', $templates = '') { global $mm_fields, $modx; $e =& $modx->event; // if we've been supplied with a string, convert it into an array $fields = makeArray($fields); // if we aren't creating a new document or folder, we don't want to do this if (!($modx->manager->action == '85' || $modx->manager->action == '4')) { return; } // Are we using this rule? if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)) { // Get the parent info if (isset($_REQUEST['pid']) && is_numeric($_REQUEST['pid'])) { $parentID = intval($_REQUEST['pid']); } else { if (isset($_REQUEST['parent']) && is_numeric($_REQUEST['parent'])) { $parentID = intval($_REQUEST['parent']); } else { $parentID = 0; } } if ($parentID == 0) { return; } $output = "// -------------- mm_inherit (from page {$parentID}) :: Begin ------------- \n"; foreach ($fields as $field) { // get some info about the field we are being asked to use if (isset($mm_fields[$field]['dbname'])) { $fieldtype = $mm_fields[$field]['fieldtype']; $fieldname = $mm_fields[$field]['fieldname']; $dbname = $mm_fields[$field]['dbname']; if (!empty($mm_fields[$field]['tv'])) { $dbname = $field; } // Get this field data from the parent $newArray = $modx->getTemplateVarOutput($dbname, $parentID); if (empty($newArray)) { // If no results, check if there is an unpublished doc $newArray = $modx->getTemplateVarOutput($dbname, $parentID, 0); } $newvalue = $newArray[$dbname]; } else { break; // If it's not something stored in the database, don't get the value } if (empty($newvalue)) { continue; } $output .= "\n\t\t\t// fieldtype {$fieldtype}\n\t\t\t// fieldname {$fieldname}\n\t\t\t// dbname {$dbname}\n\t\t\t// newvalue {$newvalue}\n\t\t\t"; $date_format = $modx->toDateFormat(null, 'formatOnly'); switch ($field) { case 'log': case 'hide_menu': case 'show_in_menu': $output .= '$j("input[name=' . $fieldname . ']").attr("checked", "' . ($newvalue ? '' : 'checked') . '"); '; break; case 'is_folder': case 'is_richtext': case 'searchable': case 'cacheable': case 'published': $output .= '$j("input[name=' . $fieldname . ']").attr("checked", "' . ($newvalue ? 'checked' : '') . '"); '; break; case 'pub_date': case 'unpub_date': $output .= '$j("input[name=' . $fieldname . ']").val("' . strftime($date_format . ' %H:%M:%S', $newvalue) . '"); '; break; default: switch ($fieldtype) { case 'textarea': $output .= '$j("textarea[name=' . $fieldname . ']").html("' . jsSafe($newvalue) . '"); '; break; default: $output .= '$j("' . $fieldtype . '[name=' . $fieldname . ']").val("' . jsSafe($newvalue) . '"); '; break; } break; } } $output .= "// -------------- mm_inherit (from page {$parentID}) :: End ------------- \n"; $e->output($output . "\n"); } }
/** * makeSqlList * @version 1.0.1 (2013-03-19) * * @desc Create a MySQL-safe list from an array. * * @param $arr {array; comma separated string} - Values. */ function makeSqlList($arr) { $arr = makeArray($arr); foreach ($arr as $k => $tv) { //if (substr($tv, 0, 2) == 'tv') {$tv=substr($tv,2);} // Escape them for MySQL $arr[$k] = "'" . mysql_real_escape_string($tv) . "'"; } $sql = " (" . implode(',', $arr) . ") "; return $sql; }
/** * mm_ddReadonly * @version 1.0.1 (2013-07-13) * * @desc Makes fields only readable. * * @uses ManagerManager plugin 0.5.1. * * @param $fields {comma separated string} - The name(s) of the document fields (or TVs) for which the widget is applying. @required * @param $roles {comma separated string} - The roles that the widget is applied to (when this parameter is empty then widget is applied to the all roles). Default: ''. * @param $templates {comma separated string} - Templates IDs for which the widget is applying (empty value means the widget is applying to all templates). Default: ''. * * @link http://code.divandesign.biz/modx/mm_ddreadonly/1.0.1 * * @copyright 2013, DivanDesign * http://www.DivanDesign.biz */ function mm_ddReadonly($fields = '', $roles = '', $templates = '') { global $modx, $mm_fields, $mm_current_page; $e =& $modx->Event; if (!useThisRule($roles, $templates)) { return; } //Перед сохранением документа if ($e->name == 'OnBeforeDocFormSave') { //Если создаётся новый документ, у него нет никакого id ещё, да и нам пофиг, т.к. никто ничего с ним всё равно не мог сделать до сохранения if ($e->params['mode'] == 'new') { return; } //ID документа $docId = $e->params['id']; //Если нужная переменная в сессии не определена, определим if (!is_array($_SESSION['mm_ddReadonly'])) { $_SESSION['mm_ddReadonly'] = array(); } //Разбиваем переданные поля в массивчик $fields = makeArray($fields); //Получаем id TV. TODO: Оптимизировать, чтобы всё было в один запрос $tvs = tplUseTvs($mm_current_page['template'], $fields, '', 'id,name'); //Результат $resultFields = array(); //Если что-то оплучили if (is_array($tvs) && count($tvs) > 0) { $tvsNames = array(); //Пробежимся, переделаем под удобный нам формат foreach ($tvs as $val) { $tvsNames[$val['id']] = $val['name']; } //Получаем значения TV $tvs = $modx->db->makeArray($modx->db->select('value,tmplvarid AS id', ddTools::$tables['site_tmplvar_contentvalues'], 'contentid=' . $docId . ' AND tmplvarid IN ' . makeSqlList(array_keys($tvsNames)))); //Если что-то нашлось if (count($tvs) > 0) { //Пробежимся foreach ($tvs as $val) { //Если значение не пустое if ($val['value'] != '') { //Запишем значения $resultFields[$tvsNames[$val['id']]] = $val['value']; } } } } //Перебираем поля foreach ($fields as $key => $val) { //Если такого поля нет или это TV if (!isset($mm_fields[$val]) || $mm_fields[$val]['tv'] == 1) { //Снесём unset($fields[$key]); } } if (count($fields) > 0) { //Получаем значения необходимых полей $fields = $modx->db->getRow($modx->db->select(implode(',', $fields), ddTools::$tables['site_content'], 'id=' . $docId)); //Переберём foreach ($fields as $key => $val) { if ($val != '') { $resultFields[$key] = $val; } } } //Если хоть что-то осталось if (count($resultFields) > 0) { //Сохраним значения в сессию, они нам ещё понадобятся $_SESSION['mm_ddReadonly'][$docId] = $resultFields; } //После сохранения документа } else { if ($e->name == 'OnDocFormSave') { //Если создаётся новый документ, у него нет никакого id ещё, да и нам пофиг, т.к. никто ничего с ним всё равно не мог сделать до сохранения if ($e->params['mode'] == 'new') { return; } //ID документа $docId = $e->params['id']; //Если данные о текущем документе есть if (is_array($_SESSION['mm_ddReadonly']) && is_array($_SESSION['mm_ddReadonly'][$docId]) && count($_SESSION['mm_ddReadonly'][$docId]) > 0) { //Обновляем данные документа в соответствии с тем, что было раньше ddTools::updateDocument($docId, $_SESSION['mm_ddReadonly'][$docId]); //Сносим за ненадобностью unset($_SESSION['mm_ddReadonly'][$docId]); } //При копировании документа } else { if ($e->name == 'OnDocDuplicate') { //Получаем id TV $tvs = tplUseTvs($mm_current_page['template'], $fields); //Если что-то оплучили if (is_array($tvs) && count($tvs) > 0) { $tvIds = array(); foreach ($tvs as $val) { $tvIds[] = $val['id']; } //Удаляем значение TV для данного документа $modx->db->delete(ddTools::$tables['site_tmplvar_contentvalues'], '`contentid` = ' . $e->params['new_id'] . ' AND `tmplvarid` IN(' . implode(',', $tvIds) . ')'); } //При рендере документа } else { if ($e->name == 'OnDocFormRender') { //Разбиваем переданные поля в массивчик $fields = makeArray($fields); //Если есть что-то if (count($fields) > 0) { $output = "// ---------------- mm_ddReadonly :: Begin ------------- \n"; $output .= 'var $mm_ddReadonly;'; //Получаем id TV $tvs = tplUseTvs($mm_current_page['template'], $fields); //Если что-то есть if (is_array($tvs) && count($tvs) > 0) { //Перебираем TV foreach ($tvs as $val) { //Вставляем значение перед оригиналом и сносим оригинал нафиг $output .= ' $mm_ddReadonly = $j("#tv' . $val['id'] . '"); $mm_ddReadonly.before($mm_ddReadonly.val()).hide(); '; } } if (count($fields) != count($tvs)) { //Перебираем поля foreach ($fields as $val) { //Если такое поле есть и это не TV if (isset($mm_fields[$val]) && $mm_fields[$val]['tv'] != 1) { $output .= ' $mm_ddReadonly = $j("' . $mm_fields[$val]['fieldtype'] . '[name=\\"' . $mm_fields[$val]['fieldname'] . '\\"]"); $mm_ddReadonly.before($mm_ddReadonly.val()).hide(); '; } } } $output .= "\n// ---------------- mm_ddReadonly :: End -------------"; $e->output($output . "\n"); } } } } } }