repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
l1ght13aby/Ubilling
userstats/modules/engine/api.lightastral.php
28509
<?php /** * Return web form element id * * @return string */ function la_InputId() { // I know it looks really funny. // You can also get a truly random values by throwing dice ;) $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $result = ""; for ($p = 0; $p < 8; $p++) { $result .= $characters[mt_rand(0, (strlen($characters) - 1))]; } return ($result); } /** * Return web form body * * @param string $action action URL * @param string $method method: POST or GET * @param string $inputs inputs string to include * @param string $class class for form * @param string $legend form legend * @param bool $cleanStyle clean css style * @param string $options some inline form options * * @return string */ function la_Form($action, $method, $inputs, $class = '', $legend = '', $cleanStyle = true, $options = '') { if ($class != '') { $form_class = ' class="' . $class . '" '; } else { $form_class = ''; } if ($legend != '') { $form_legend = '<legend>' . __($legend) . '</legend> <br>'; } else { $form_legend = ''; } if ($cleanStyle) { $cleanDiv = '<div style="clear:both;"></div>'; } else { $cleanDiv = ''; } $form = ' <form action="' . $action . '" method="' . $method . '" ' . $form_class . ' ' . $options . '> ' . $form_legend . ' ' . $inputs . ' </form> ' . $cleanDiv . ' '; return ($form); } /** * Return text input Web From element * * @param string $name name of element * @param string $label text label for input * @param string $value current value * @param bool $br append new line * @param string $size input size * @param string $pattern input check pattern. Avaible: geo, mobile, finance, ip, net-cidr, digits, email, alpha, alphanumeric,mac * @param string $class class of the element * @param string $ctrlID id of the element * @param string $options * * @return string * */ function la_TextInput($name, $label = '', $value = '', $br = false, $size = '', $pattern = '', $class = '', $ctrlID = '', $options = '') { $inputid = ( empty($ctrlID) ) ? la_InputId() : $ctrlID; $opts = ( empty($options) ) ? '' : $options; //set size if ($size != '') { $input_size = 'size="' . $size . '"'; } else { $input_size = ''; } if ($br) { $newline = '<br>'; } else { $newline = ''; } // We will verify that we correctly enter data by input type $pattern = ($pattern == 'geo') ? 'pattern="-?\d{1,2}(\.\d+)\s?,\s?-?\d{1,3}(\.\d+)" placeholder="0.00000,0.00000" title="' . __('The format of geographic data can be') . ': 40.7143528,-74.0059731 ; 41.40338, 2.17403 ; -14.235004 , 51.92528"' : $pattern; $pattern = ($pattern == 'mobile') ? 'pattern="\+?(\d{1,3})?\d{2,3}\d{7}" placeholder="(+)(38)0500000000" title="' . __('The mobile number format can be') . ': +38026121104, 0506430501, 375295431122"' : $pattern; $pattern = ($pattern == 'finance') ? 'pattern="\d+(\.\d+)?" placeholder="0(.00)" title="' . __('The financial input format can be') . ': 1 ; 4.01 ; 2 ; 0.001"' : $pattern; // For this pattern IP adress also can be 0.0.0.0 $pattern = ($pattern == 'ip') ? 'pattern="^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" placeholder="0.0.0.0" title="' . __('The IP address format can be') . ': 192.1.1.1"' : $pattern; // For this pattern exclude cidr /31 $pattern = ($pattern == 'net-cidr') ? 'pattern="^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\/([0-9]|[1-2][0-9]|30|32)$" placeholder="0.0.0.0/0" title="' . __('The format of IP address with mask can be') . ': 192.1.1.1/32 ' . __('and the mask can not be /31') . '"' : $pattern; $pattern = ($pattern == 'digits') ? 'pattern="^\d+$" placeholder="0" title="' . __('This field can only contain digits') . '"' : $pattern; $pattern = ($pattern == 'email') ? 'pattern="^([\w\._-]+)@([\w\._-]+)\.([a-z]{2,6}\.?)$" placeholder="bobrik@bobrik.com" title="' . __('This field can only contain email address') . '"' : $pattern; $pattern = ($pattern == 'alpha') ? 'pattern="[a-zA-Z]+" placeholder="aZ" title="' . __('This field can only contain Latin letters') . '"' : $pattern; $pattern = ($pattern == 'alphanumeric') ? 'pattern="[a-zA-Z0-9]+" placeholder="aZ09" title="' . __('This field can only contain Latin letters and numbers') . '"' : $pattern; $pattern = ($pattern == 'mac') ? 'pattern="^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$|^[a-fA-F0-9]{2}-[a-fA-F0-9]{2}-[a-fA-F0-9]{2}-[a-fA-F0-9]{2}-[a-fA-F0-9]{2}-[a-fA-F0-9]{2}$" placeholder="00:02:02:34:72:a5" title="' . __('This MAC have wrong format') . '"' : $pattern; $result = '<input type="text" name="' . $name . '" value="' . $value . '" ' . $input_size . ' id="' . $inputid . '" class="' . $class . '" ' . $opts . ' ' . $pattern . '>' . "\n"; if ($label != '') { $result .= ' <label for="' . $inputid . '">' . __($label) . '</label>' . "\n"; } $result .= $newline . "\n"; return ($result); } /** * Return password input Web From element * * @param string $name name of element * @param string $label text label for input * @param string $value current value * @param bool $br append new line * @param string $size input size * * @return string */ function la_PasswordInput($name, $label = '', $value = '', $br = false, $size = '') { $inputid = la_InputId(); //set size if ($size != '') { $input_size = 'size="' . $size . '"'; } else { $input_size = ''; } if ($br) { $newline = '<br>'; } else { $newline = ''; } $result = '<input type="password" name="' . $name . '" value="' . $value . '" ' . $input_size . ' id="' . $inputid . '">' . "\n"; if ($label != '') { $result .= ' <label for="' . $inputid . '">' . __($label) . '</label>' . "\n"; } $result .= $newline . "\n"; return ($result); } /** * Return link form element * * @param string $url needed URL * @param string $title text title of URL * @param bool $br append new line - bool * @param string $class class for link * @param string $options for link * * @return string */ function la_Link($url, $title, $br = false, $class = '', $options = '') { if ($class != '') { $link_class = 'class="' . $class . '"'; } else { $link_class = ''; } if ($br) { $newline = '<br>'; } else { $newline = ''; } $opts = ( empty($options) ) ? '' : ' ' . $options; $result = '<a href="' . $url . '" ' . $link_class . $opts . '>' . __($title) . '</a>' . "\n"; $result .= $newline . "\n"; return ($result); } /** * Return Radio box Web From element * * @param string $name name of element * @param string $label text label for input * @param string $value current value * @param bool $br append new line - bool * @param bool $checked is checked? - bool * * @return string */ function la_RadioInput($name, $label = '', $value = '', $br = false, $checked = false) { $inputid = la_InputId(); if ($br) { $newline = '<br>'; } else { $newline = ''; } if ($checked) { $check = 'checked=""'; } else { $check = ''; } $result = '<input type="radio" name="' . $name . '" value="' . $value . '" id="' . $inputid . '" ' . $check . '>' . "\n"; if ($label != '') { $result .= ' <label for="' . $inputid . '">' . __($label) . '</label>' . "\n"; } $result .= $newline . "\n"; return ($result); } /** * Return check box Web From element * * @param string $name name of element * @param string $label text label for input * @param bool $br append new line - bool * @param bool $checked is checked? - bool * * @return string */ function la_CheckInput($name, $label = '', $br = false, $checked = false) { $inputid = la_InputId(); if ($br) { $newline = '<br>'; } else { $newline = ''; } if ($checked) { $check = 'checked=""'; } else { $check = ''; } $result = '<input type="checkbox" id="' . $inputid . '" name="' . $name . '" ' . $check . ' />'; if ($label != '') { $result .= ' <label for="' . $inputid . '">' . __($label) . '</label>' . "\n"; } $result .= $newline . "\n"; return ($result); } /** * Return textarea Web From element * * @param string $name name of element * @param string $label text label for input * @param string $value value for element * @param bool $br append new line - bool * @param string $size size in format "10x20" * * @return string */ function la_TextArea($name, $label = '', $value = '', $br = false, $size = '') { $inputid = la_InputId(); //set columns and rows count if ($size != '') { $sizexplode = explode('x', $size); $input_size = 'cols="' . $sizexplode[0] . '" rows="' . $sizexplode[1] . '" '; } else { $input_size = ''; } if ($br) { $newline = '<br>'; } else { $newline = ''; } $result = '<textarea name="' . $name . '" ' . $input_size . ' id="' . $inputid . '">' . $value . '</textarea>' . "\n"; if ($label != '') { $result .= ' <label for="' . $inputid . '">' . __($label) . '</label>' . "\n"; ; } $result .= $newline . "\n"; return ($result); } /** * Return hidden input web form element * * @param string $name name of element * @param string s$value value for input * * @return string */ function la_HiddenInput($name, $value = '') { $result = '<input type="hidden" name="' . $name . '" value="' . $value . '">'; return ($result); } /** * Return submit web form element * * @param string $value text label for button * * @return string */ function la_Submit($value) { $result = '<input type="submit" value="' . __($value) . '">'; return ($result); } /** * Return select Web From element * * @param string $name name of element * @param array $params array of elements $value=>$option * @param string $label text label for input * @param string $selected selected $value for selector * @param string $br append new line - bool * * @return string */ function la_Selector($name, $params, $label, $selected = '', $br = false) { $inputid = la_InputId(); if ($br) { $newline = '<br>'; } else { $newline = ''; } $result = '<select name="' . $name . '" id="' . $inputid . '">'; if (!empty($params)) { foreach ($params as $value => $eachparam) { $sel_flag = ''; if ($selected != '') { if ($selected == $value) { $sel_flag = 'SELECTED'; } } $result .= '<option value="' . $value . '" ' . $sel_flag . '>' . $eachparam . '</option>' . "\n"; } } $result .= '</select>' . "\n"; if ($label != '') { $result .= '<label for="' . $inputid . '">' . __($label) . '</label>'; } $result .= $newline . "\n"; return ($result); } /** * Return Month select Web From element * * @param string $name name of element * @param string $label text label for input * @param string $selected selected $value for selector * @param string $br append new line - bool * * @return string * */ function la_MonthSelector($name, $label, $selected = '', $br = false) { $allmonth = months_array(); $params = array(); //localize months foreach ($allmonth as $monthnum => $monthname) { $params[$monthnum] = rcms_date_localise($monthname); } $inputid = la_InputId(); if ($br) { $newline = '<br>'; } else { $newline = ''; } $result = '<select name="' . $name . '" id="' . $inputid . '">'; if (!empty($params)) { foreach ($params as $value => $eachparam) { $sel_flag = ''; if ($selected != '') { if ($selected == $value) { $sel_flag = 'SELECTED'; } } $result .= '<option value="' . $value . '" ' . $sel_flag . '>' . $eachparam . '</option>' . "\n"; } } $result .= '</select>' . "\n"; if ($label != '') { $result .= '<label for="' . $inputid . '">' . __($label) . '</label>'; } $result .= $newline . "\n"; return ($result); } /** * Return Year select Web From element * * @param string $name name of element * @param string $label text label for input * @param string $br append new line - bool * @return string * */ function la_YearSelector($name, $label = '', $br = false) { $curyear = curyear(); $inputid = la_InputId(); $count = 5; if ($br) { $newline = '<br>'; } else { $newline = ''; } $selector = '<select name="' . $name . '">'; for ($i = 0; $i < $count; $i++) { $selector .= '<option value="' . ($curyear - $i) . '">' . ($curyear - $i) . '</option>'; } $selector .= '</select>'; if ($label != '') { $selector .= '<label for="' . $inputid . '">' . __($label) . '</label>'; } $selector .= $newline; return($selector); } /** * Check for POST have needed variables * * @param string $params array of POST variables to check * @return bool * */ function la_CheckPost($params) { $result = true; if (!empty($params)) { foreach ($params as $eachparam) { if (isset($_POST[$eachparam])) { if (empty($_POST[$eachparam])) { $result = false; } } else { $result = false; } } } return ($result); } /** * Check for GET have needed variables * * @param array $params array of GET variables to check * * @return bool * */ function la_CheckGet($params) { $result = true; if (!empty($params)) { foreach ($params as $eachparam) { if (isset($_GET[$eachparam])) { if (empty($_GET[$eachparam])) { $result = false; } } else { $result = false; } } } return ($result); } /** * Construct HTML table row element * * @param string $cells table row cells * @param string $class table row class * * @return string * */ function la_TableRow($cells, $class = '') { if ($class != '') { $rowclass = 'class="' . $class . '"'; } else { $rowclass = ''; } $result = '<tr ' . $rowclass . '>' . $cells . '</tr>' . "\n"; return ($result); } /** * Construct HTML table cell element * * @param string $data table cell data * @param string $width width of cell element * @param string $class table cell class * @param string $customkey table cell custom param * * @return string */ function la_TableCell($data, $width = '', $class = '', $customkey = '') { if ($width != '') { $cellwidth = 'width="' . $width . '"'; } else { $cellwidth = ''; } if ($class != '') { $cellclass = 'class="' . $class . '"'; } else { $cellclass = ''; } if ($customkey != '') { $customkey = $customkey; } else { $customkey = ''; } $result = '<td ' . $cellwidth . ' ' . $cellclass . ' ' . $customkey . '>' . $data . '</td>' . "\n"; return ($result); } /** * Construct HTML table body * * @param string $rows table rows data * @param string $width width of cell element * @param string $border table border width * @param string $class table cell class * * @return string * */ function la_TableBody($rows, $width = '', $border = '0', $class = '') { if ($width != '') { $tablewidth = 'width="' . $width . '"'; } else { $tablewidth = ''; } if ($class != '') { $tableclass = 'class="' . $class . '"'; } else { $tableclass = ''; } if ($border != '') { $tableborder = 'border="' . $border . '"'; } else { $tableborder = ''; } $result = ' <table ' . $tablewidth . ' ' . $tableborder . ' ' . $tableclass . ' > ' . $rows . ' </table> '; return ($result); } /** * Returns image body * * @param string $url image url * * @return string */ function la_img($url, $title = '') { if ($title != '') { $imgtitle = 'title="' . $title . '"'; } else { $imgtitle = ''; } $result = '<img src="' . $url . '" ' . $imgtitle . ' border="0">'; return ($result); } /** * Returns image body with some dimensions * * @param string $url image url * @param string $title title attribure for image * @param string $width image width * @param string $height image height * * @return string * */ function la_img_sized($url, $title = '', $width = '', $height = '', $style = '') { $imgtitle = ($title != '') ? 'title="' . $title . '"' : ''; $imgwidth = ($width != '') ? 'width="' . $width . '"' : ''; $imgheight = ($height != '') ? 'height="' . $height . '"' : ''; $imgstyle = (empty($style)) ? '' : ' style="' . $style . '" '; $result = '<img src="' . $url . '" ' . $imgtitle . ' ' . $imgwidth . ' ' . $imgheight . $imgstyle . ' border="0">'; return ($result); } /** * Returns some count of delimiters * * @param int $count count of delimited rows * * @return string */ function la_delimiter($count = 1) { $result = ''; for ($i = 0; $i <= $count; $i++) { $result .= '<br />'; } return ($result); } /** * Returns some count of non-breaking space symbols * * @param int $count * * @return string */ function la_nbsp($count = 1) { $result = ''; for ($i = 0; $i < $count; $i++) { $result .= '&nbsp;'; } return ($result); } /** * Returns some html styled tag * * @param string $tag HTML tag entity * @param string $closed tag is closing? * @param string $class tag styling class * @param string $options tag extra options * * @return string */ function la_tag($tag, $closed = false, $class = '', $options = '') { if (!empty($class)) { $tagclass = ' class="' . $class . '"'; } else { $tagclass = ''; } if ($closed) { $tagclose = '/'; } else { $tagclose = ''; } if ($options != '') { $tagoptions = $options; } else { $tagoptions = ''; } $result = '<' . $tagclose . $tag . $tagclass . ' ' . $tagoptions . '>'; return ($result); } /** * Returns calendar widget with preset date * * @param string $field field name to insert calendar * * @return string * */ function la_DatePickerPreset($field, $date) { $inputid = la_InputId(); $us_config = zbs_LoadConfig(); $curlang = $us_config['lang']; $skinPath = zbs_GetCurrentSkinPath($us_config); $iconsPath = $skinPath . 'iconz/'; $result = '<script> $(function() { $( "#' . $inputid . '" ).datepicker({ showOn: "both", buttonImage: "' . $iconsPath . 'icon_calendar.gif", buttonImageOnly: true, dateFormat: "yy-mm-dd", showAnim: "slideDown" }); $.datepicker.regional[\'english\'] = { closeText: \'Done\', prevText: \'Prev\', nextText: \'Next\', currentText: \'Today\', monthNames: [\'January\',\'February\',\'March\',\'April\',\'May\',\'June\', \'July\',\'August\',\'September\',\'October\',\'November\',\'December\'], monthNamesShort: [\'Jan\', \'Feb\', \'Mar\', \'Apr\', \'May\', \'Jun\', \'Jul\', \'Aug\', \'Sep\', \'Oct\', \'Nov\', \'Dec\'], dayNames: [\'Sunday\', \'Monday\', \'Tuesday\', \'Wednesday\', \'Thursday\', \'Friday\', \'Saturday\'], dayNamesShort: [\'Sun\', \'Mon\', \'Tue\', \'Wed\', \'Thu\', \'Fri\', \'Sat\'], dayNamesMin: [\'Su\',\'Mo\',\'Tu\',\'We\',\'Th\',\'Fr\',\'Sa\'], weekHeader: \'Wk\', dateFormat: \'dd/mm/yy\', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: \'\'}; $.datepicker.regional[\'russian\'] = { closeText: \'Закрыть\', prevText: \'&#x3c;Пред\', nextText: \'След&#x3e;\', currentText: \'Сегодня\', monthNames: [\'Январь\',\'Февраль\',\'Март\',\'Апрель\',\'Май\',\'Июнь\', \'Июль\',\'Август\',\'Сентябрь\',\'Октябрь\',\'Ноябрь\',\'Декабрь\'], monthNamesShort: [\'Янв\',\'Фев\',\'Мар\',\'Апр\',\'Май\',\'Июн\', \'Июл\',\'Авг\',\'Сен\',\'Окт\',\'Ноя\',\'Дек\'], dayNames: [\'воскресенье\',\'понедельник\',\'вторник\',\'среда\',\'четверг\',\'пятница\',\'суббота\'], dayNamesShort: [\'вск\',\'пнд\',\'втр\',\'срд\',\'чтв\',\'птн\',\'сбт\'], dayNamesMin: [\'Вс\',\'Пн\',\'Вт\',\'Ср\',\'Чт\',\'Пт\',\'Сб\'], weekHeader: \'Нед\', dateFormat: \'dd.mm.yy\', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: \'\'}; $.datepicker.regional[\'ukrainian\'] = { closeText: \'Закрити\', prevText: \'&#x3c;\', nextText: \'&#x3e;\', currentText: \'Сьогодні\', monthNames: [\'Січень\',\'Лютий\',\'Березень\',\'Квітень\',\'Травень\',\'Червень\', \'Липень\',\'Серпень\',\'Вересень\',\'Жовтень\',\'Листопад\',\'Грудень\'], monthNamesShort: [\'Січ\',\'Лют\',\'Бер\',\'Кві\',\'Тра\',\'Чер\', \'Лип\',\'Сер\',\'Вер\',\'Жов\',\'Лис\',\'Гру\'], dayNames: [\'неділя\',\'понеділок\',\'вівторок\',\'середа\',\'четвер\',\'п’ятниця\',\'субота\'], dayNamesShort: [\'нед\',\'пнд\',\'вів\',\'срд\',\'чтв\',\'птн\',\'сбт\'], dayNamesMin: [\'Нд\',\'Пн\',\'Вт\',\'Ср\',\'Чт\',\'Пт\',\'Сб\'], weekHeader: \'Тиж\', dateFormat: \'dd/mm/yy\', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: \'\'}; $.datepicker.setDefaults($.datepicker.regional[\'' . $curlang . '\']); }); </script> <input type="text" id="' . $inputid . '" name="' . $field . '" value="' . $date . '" size="10"> '; return($result); } /** * Returns modal window JS code * * @param string $link * @param string $title * @param string $content * @param string $linkclass * @param string $width * @param string $height * * @return string */ function la_modal($link, $title, $content, $linkclass = '', $width = '', $height = '') { $wid = la_inputid(); //setting link class if ($linkclass != '') { $link_class = 'class="' . $linkclass . '"'; } else { $link_class = ''; } //setting auto width if not specified if ($width == '') { $width = '600'; } //setting auto width if not specified if ($height == '') { $height = '400'; } $dialog = ' <script type="text/javascript"> $(function() { $( "#dialog-modal_' . $wid . '" ).dialog({ autoOpen: false, width: ' . $width . ', height: ' . $height . ', modal: true, show: "drop", hide: "fold" }); $( "#opener_' . $wid . '" ).click(function() { $( "#dialog-modal_' . $wid . '" ).dialog( "open" ); return false; }); }); </script> <div id="dialog-modal_' . $wid . '" title="' . $title . '" style="display:none; width:1px; height:1px;"> <p> ' . $content . ' </p> </div> <a href="#" id="opener_' . $wid . '" ' . $link_class . '>' . $link . '</a> '; return($dialog); } /** * Returns link that calls new modal window with automatic dimensions by inside content * * @param string $link link text * @param string $title modal window title * @param string $content modal window content * @param string $linkclass link class * * @return string * */ function la_modalAuto($link, $title, $content, $linkclass = '') { $wid = la_inputid(); //setting link class if ($linkclass != '') { $link_class = 'class="' . $linkclass . '"'; } else { $link_class = ''; } $width = "'auto'"; $height = "'auto'"; $dialog = ' <script type="text/javascript"> $(function() { $( "#dialog-modal_' . $wid . '" ).dialog({ autoOpen: false, width: \'auto\', height: \'auto\', modal: true, show: "drop", hide: "fold" }); $( "#opener_' . $wid . '" ).click(function() { $( "#dialog-modal_' . $wid . '" ).dialog( "open" ); return false; }); }); </script> <div id="dialog-modal_' . $wid . '" title="' . $title . '" style="display:none; width:1px; height:1px;"> <p> ' . $content . ' </p> </div> <a href="#" id="opener_' . $wid . '" ' . $link_class . '>' . $link . '</a> '; return($dialog); } /** * Returns new opened modal window with some content * * @param string $title modal window title * @param string $content modal window content * @param string $width modal window width * @param string $height modal window height * @return string * */ function la_modalOpened($title, $content, $width = '', $height = '') { $wid = la_inputid(); //setting auto width if not specified if ($width == '') { $width = "'auto'"; } //setting auto width if not specified if ($height == '') { $height = "'auto'"; } $dialog = ' <script type="text/javascript"> $(function() { $( "#dialog-modal_' . $wid . '" ).dialog({ autoOpen: true, width: ' . $width . ', height: ' . $height . ', modal: true, show: "drop", hide: "fold", create: function( event, ui ) { $(this).css("maxWidth", "800px"); } }); $( "#opener_' . $wid . '" ).click(function() { $( "#dialog-modal_' . $wid . '" ).dialog( "open" ); return false; }); }); </script> <div id="dialog-modal_' . $wid . '" title="' . $title . '" style="display:none; width:1px; height:1px;"> <p> ' . $content . ' </p> </div> '; return($dialog); } /** * Returns JS confirmation url * * @param string $url URL if confirmed * @param string $title link title * @param string $alerttext alert text * @return string * */ function la_JSAlert($url, $title, $alerttext) { $result = '<a onclick="if(!confirm(\'' . __($alerttext) . '\')) { return false;}" href="' . $url . '">' . $title . '</a>'; return ($result); } /** * Returns JS confirmation url with some applied class * * @param string $url URL if confirmed * @param string $title link title * @param string $alerttext alert text * @param string $functiontorun function name with parameters which must exist on a page * * @return string */ function la_JSAlertStyled($url, $title, $alerttext, $class = '', $functiontorun = '') { $class = (!empty($class)) ? 'class="' . $class . '"' : ''; if (empty($functiontorun)) { $result = '<a onclick="if(!confirm(\'' . __($alerttext) . '\')) { return false;}" href="' . $url . '" ' . $class . '>' . $title . '</a>'; } else { $result = '<a onclick="if(!confirm(\'' . __($alerttext) . '\')) { return false;} else { ' . $functiontorun . '; }" href="' . $url . '" ' . $class . '>' . $title . '</a>'; } return ($result); } /** * Returns confirmation dialog to navigate to some URL * * @param string $url * @param string $title * @param string $alerttext * @param string $class * @param string $cancelUrl * * @return string */ function la_ConfirmDialog($url, $title, $alerttext, $class = '', $cancelUrl = '') { $result = ''; $dialog = __($alerttext); $dialog .= la_tag('br'); $dialog .= la_tag('center', false); $dialog .= la_Link($url, __('Agree'), false, 'anreadbutton'); if ($cancelUrl) { $dialog .= la_Link($cancelUrl, __('Cancel'), false, 'anunreadbutton'); } $dialog .= la_tag('center', true); $result .= la_modalAuto($title, __($title), $dialog, $class); return($result); } ?>
gpl-2.0
Doap/acopio
0217/add_all_to_cart0228.php
2899
<?php require_once("../wp-config.php"); require_once("../wp-load.php"); function curHostURL() { $HostURL = 'http'; if ($_SERVER["HTTPS"] == "on") {$HostURL .= "s";} $HostURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $HostURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"]; } else { $HostURL .= $_SERVER["SERVER_NAME"]; } return $HostURL; } $wp->init(); $wp->parse_request(); $wp->query_posts(); $wp->register_globals(); $wp->send_headers(); //echo $_POST['acopio_id']; $acopio_id = $_POST['acopio_id']; $products_to_add = $wpdb->get_results( " SELECT * FROM wp_acopiometa WHERE acopio_id = $acopio_id ORDER BY acopiometa_id ASC; " ,ARRAY_A); get_header(); if (!empty($products_to_add)) { foreach ($products_to_add as $product_to_add) { $acopiometa_id = $product_to_add['acopiometa_id']; $acopio_id = $product_to_add['acopio_id']; $product_id = $product_to_add['product_id']; $item_id = $product_to_add['item_id']; $quantity = $product_to_add['quantity']; $cajillas = $product_to_add['cajillas']; // echo $acopiometa_id . '<br>'; // echo $acopio_id . '<br>'; // echo $product_id . '<br>'; // echo $item_id . '<br>'; // echo $quantity . '<br>'; // echo $cajillas . '<br>'; // echo '<br>'; //$request_url = curHostURL(); //$request_url .= '/wp-admin/admin-ajax.php?action=tcp_shopping_cart_actions&to_do=add&tcp_add_to_shopping_cart=&tcp_count%5B%5D=' . $quantity .'&tcp_post_id%5B%5D=' . $product_id; //$response = http_get('/wp-admin/admin-ajax.php?action=tcp_shopping_cart_actions&to_do=add&tcp_add_to_shopping_cart=&tcp_count%5B%5D=' . $quantity .'&tcp_post_id%5B%5D=' . $product_id, array("timeout"=>1), $info); //print_r($info); //$curl = curl_init(); // Set some options - we are passing in a useragent too here //curl_setopt_array($curl, array( // CURLOPT_RETURNTRANSFER => 1, // CURLOPT_URL => $request_url //)); // Send the request & save response to $resp //$resp = curl_exec($curl); // Close request to clear up some resources //curl_close($curl); //print_r($resp); //wp_remote_get($request_url); ?> <script> function ready<?php echo $product_id; ?>( jQuery ) { var product_id = '<?php echo $product_id; ?>'; var quantity = '<?php echo $quantity; ?>'; data = 'action=tcp_shopping_cart_actions&to_do=add&tcp_add_to_shopping_cart=&tcp_count%5B%5D=' . quantity . '&tcp_post_id%5B%5D=' . product_id; feedback.show(); jQuery.getJSON( "<?php echo admin_url( 'admin-ajax.php' ); ?>", data ).done( function( response ) { feedback.hide(); tcpDispatcher.fire( post_id ); } ).fail( function (error ) { feedback.hide(); tcpDispatcher.fire( post_id ); } ); } $( document ).ready( ready<?php echo $product_id; ?> ); </script> <?php } } else { echo 'Nothing to do'; } get_footer(); ?>
gpl-2.0
tatsuhiro-t/aria2
src/CUIDCounter.cc
1846
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2010 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "CUIDCounter.h" namespace aria2 { CUIDCounter::CUIDCounter() : count_(0) {} CUIDCounter::~CUIDCounter() = default; cuid_t CUIDCounter::newID() { if (count_ == INT64_MAX) { count_ = 0; } return ++count_; } } // namespace aria2
gpl-2.0
cidesa/roraima-comunal
lib/model/Presupuesto5Peer.php
421
<?php /** * Subclase para crear funcionalidades específicas de busqueda y actualización en la tabla 'presupuesto5'. * * * * @package Roraima * @subpackage lib.model * @author $Author$ <desarrollo@cidesa.com.ve> * @version SVN: $Id$ * * @copyright Copyright 2007, Cide S.A. * @license http://opensource.org/licenses/gpl-2.0.php GPLv2 */ class Presupuesto5Peer extends BasePresupuesto5Peer { }
gpl-2.0
cidesa/roraima-comunal
lib/model/Hisconb.php
349
<?php /** * Subclass for representing a row from the 'hisconb'. * * * * @package Roraima * @subpackage lib.model * @author $Author$ <desarrollo@cidesa.com.ve> * @version SVN: $Id$ * * @copyright Copyright 2007, Cide S.A. * @license http://opensource.org/licenses/gpl-2.0.php GPLv2 */ class Hisconb extends BaseHisconb { }
gpl-2.0
ipomoena/dasher
Src/Common/Trace.cpp
902
// Trace.cpp // // Copyright (c) 2005 David Ward #include "Common.h" #include "Trace.h" // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // Customize behaviour of Trace here #ifdef _WIN32 // On Windows, send Trace to the Debug window in DevStudio // The ATL/MFC Trace application also picks up Trace when running #include "Windows.h" void DasherTraceOutputImpl(const char *pszFormat, va_list vargs) { // TODO: Reimplement // char buffer[2048]; // _vsnprintf(buffer, 2048,pszFormat, vargs); // OutputDebugStringA(buffer); } #else // Send Trace to stdout void DasherTraceOutputImpl(const char *pszFormat, va_list vargs) { vfprintf(stdout, pszFormat, vargs); } #endif
gpl-2.0
akohlmey/lammps
lib/kokkos/core/unit_test/TestAtomicOperations.hpp
25670
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ #include <Kokkos_Core.hpp> namespace TestAtomicOperations { //----------------------------------------------- //--------------zero_functor--------------------- //----------------------------------------------- template <class T, class DEVICE_TYPE> struct ZeroFunctor { using execution_space = DEVICE_TYPE; using type = typename Kokkos::View<T, execution_space>; using h_type = typename Kokkos::View<T, execution_space>::HostMirror; type data; KOKKOS_INLINE_FUNCTION void operator()(int) const { data() = 0; } }; //----------------------------------------------- //--------------init_functor--------------------- //----------------------------------------------- template <class T, class DEVICE_TYPE> struct InitFunctor { using execution_space = DEVICE_TYPE; using type = typename Kokkos::View<T, execution_space>; using h_type = typename Kokkos::View<T, execution_space>::HostMirror; type data; T init_value; KOKKOS_INLINE_FUNCTION void operator()(int) const { data() = init_value; } InitFunctor(T _init_value) : init_value(_init_value) {} }; //--------------------------------------------------- //--------------atomic_load/store/assign--------------------- //--------------------------------------------------- #ifdef KOKKOS_ENABLE_IMPL_DESUL_ATOMICS template <class T, class DEVICE_TYPE> struct LoadStoreFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { T old = Kokkos::atomic_load(&data()); if (old != i0) Kokkos::abort("Kokkos Atomic Load didn't get the right value"); Kokkos::atomic_store(&data(), i1); Kokkos::atomic_assign(&data(), old); } LoadStoreFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; #endif template <class T, class DeviceType> bool LoadStoreAtomicTest(T i0, T i1) { using execution_space = typename DeviceType::execution_space; struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); #ifdef KOKKOS_ENABLE_DESUL_ATOMICS struct LoadStoreFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); #else h_data() = i1; #endif Kokkos::deep_copy(h_data, data); return h_data() == i0; } //--------------------------------------------------- //--------------atomic_fetch_max--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct MaxFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { // Kokkos::atomic_fetch_max( &data(), (T) 1 ); Kokkos::atomic_fetch_max(&data(), (T)i1); } MaxFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T MaxAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct MaxFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T MaxAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = (i0 > i1 ? i0 : i1); T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool MaxAtomicTest(T i0, T i1) { T res = MaxAtomic<T, DeviceType>(i0, i1); T resSerial = MaxAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = MaxAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_min--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct MinFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_fetch_min(&data(), (T)i1); } MinFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T MinAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct MinFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T MinAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = (i0 < i1 ? i0 : i1); T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool MinAtomicTest(T i0, T i1) { T res = MinAtomic<T, DeviceType>(i0, i1); T resSerial = MinAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = MinAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_increment--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct IncFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_increment(&data()); } IncFunctor(T _i0) : i0(_i0) {} }; template <class T, class execution_space> T IncAtomic(T i0) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct IncFunctor<T, execution_space> f(i0); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T IncAtomicCheck(T i0) { T* data = new T[1]; data[0] = 0; *data = i0 + 1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool IncAtomicTest(T i0) { T res = IncAtomic<T, DeviceType>(i0); T resSerial = IncAtomicCheck<T>(i0); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = IncAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_decrement--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct DecFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_decrement(&data()); } DecFunctor(T _i0) : i0(_i0) {} }; template <class T, class execution_space> T DecAtomic(T i0) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct DecFunctor<T, execution_space> f(i0); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T DecAtomicCheck(T i0) { T* data = new T[1]; data[0] = 0; *data = i0 - 1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool DecAtomicTest(T i0) { T res = DecAtomic<T, DeviceType>(i0); T resSerial = DecAtomicCheck<T>(i0); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = DecAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_mul--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct MulFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_fetch_mul(&data(), (T)i1); } MulFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T MulAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct MulFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T MulAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = i0 * i1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool MulAtomicTest(T i0, T i1) { T res = MulAtomic<T, DeviceType>(i0, i1); T resSerial = MulAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = MulAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_div--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct DivFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_fetch_div(&data(), (T)i1); } DivFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T DivAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct DivFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T DivAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = i0 / i1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool DivAtomicTest(T i0, T i1) { T res = DivAtomic<T, DeviceType>(i0, i1); T resSerial = DivAtomicCheck<T>(i0, i1); bool passed = true; using Kokkos::abs; using std::abs; if (abs((resSerial - res) * 1.) > 1e-5) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = DivAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_mod--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct ModFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_fetch_mod(&data(), (T)i1); } ModFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T ModAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct ModFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T ModAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = i0 % i1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool ModAtomicTest(T i0, T i1) { T res = ModAtomic<T, DeviceType>(i0, i1); T resSerial = ModAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = ModAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_and--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct AndFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { T result = Kokkos::atomic_fetch_and(&data(), (T)i1); Kokkos::atomic_and(&data(), result); } AndFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T AndAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct AndFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T AndAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = i0 & i1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool AndAtomicTest(T i0, T i1) { T res = AndAtomic<T, DeviceType>(i0, i1); T resSerial = AndAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = AndAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_or---------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct OrFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { T result = Kokkos::atomic_fetch_or(&data(), (T)i1); Kokkos::atomic_or(&data(), result); } OrFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T OrAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct OrFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T OrAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = i0 | i1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool OrAtomicTest(T i0, T i1) { T res = OrAtomic<T, DeviceType>(i0, i1); T resSerial = OrAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = OrAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_xor--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct XorFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_fetch_xor(&data(), (T)i1); } XorFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T XorAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct XorFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T XorAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = i0 ^ i1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool XorAtomicTest(T i0, T i1) { T res = XorAtomic<T, DeviceType>(i0, i1); T resSerial = XorAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = XorAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_lshift--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct LShiftFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_fetch_lshift(&data(), (T)i1); } LShiftFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T LShiftAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct LShiftFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T LShiftAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = i0 << i1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool LShiftAtomicTest(T i0, T i1) { T res = LShiftAtomic<T, DeviceType>(i0, i1); T resSerial = LShiftAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = LShiftAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_fetch_rshift--------------------- //--------------------------------------------------- template <class T, class DEVICE_TYPE> struct RShiftFunctor { using execution_space = DEVICE_TYPE; using type = Kokkos::View<T, execution_space>; type data; T i0; T i1; KOKKOS_INLINE_FUNCTION void operator()(int) const { Kokkos::atomic_fetch_rshift(&data(), (T)i1); } RShiftFunctor(T _i0, T _i1) : i0(_i0), i1(_i1) {} }; template <class T, class execution_space> T RShiftAtomic(T i0, T i1) { struct InitFunctor<T, execution_space> f_init(i0); typename InitFunctor<T, execution_space>::type data("Data"); typename InitFunctor<T, execution_space>::h_type h_data("HData"); f_init.data = data; Kokkos::parallel_for(1, f_init); execution_space().fence(); struct RShiftFunctor<T, execution_space> f(i0, i1); f.data = data; Kokkos::parallel_for(1, f); execution_space().fence(); Kokkos::deep_copy(h_data, data); T val = h_data(); return val; } template <class T> T RShiftAtomicCheck(T i0, T i1) { T* data = new T[1]; data[0] = 0; *data = i0 >> i1; T val = *data; delete[] data; return val; } template <class T, class DeviceType> bool RShiftAtomicTest(T i0, T i1) { T res = RShiftAtomic<T, DeviceType>(i0, i1); T resSerial = RShiftAtomicCheck<T>(i0, i1); bool passed = true; if (resSerial != res) { passed = false; std::cout << "Loop<" << typeid(T).name() << ">( test = RShiftAtomicTest" << " FAILED : " << resSerial << " != " << res << std::endl; } return passed; } //--------------------------------------------------- //--------------atomic_test_control------------------ //--------------------------------------------------- template <class T, class DeviceType> bool AtomicOperationsTestIntegralType(int i0, int i1, int test) { switch (test) { case 1: return MaxAtomicTest<T, DeviceType>((T)i0, (T)i1); case 2: return MinAtomicTest<T, DeviceType>((T)i0, (T)i1); case 3: return MulAtomicTest<T, DeviceType>((T)i0, (T)i1); case 4: return DivAtomicTest<T, DeviceType>((T)i0, (T)i1); case 5: return ModAtomicTest<T, DeviceType>((T)i0, (T)i1); case 6: return AndAtomicTest<T, DeviceType>((T)i0, (T)i1); case 7: return OrAtomicTest<T, DeviceType>((T)i0, (T)i1); case 8: return XorAtomicTest<T, DeviceType>((T)i0, (T)i1); case 9: return LShiftAtomicTest<T, DeviceType>((T)i0, (T)i1); case 10: return RShiftAtomicTest<T, DeviceType>((T)i0, (T)i1); case 11: return IncAtomicTest<T, DeviceType>((T)i0); case 12: return DecAtomicTest<T, DeviceType>((T)i0); case 13: return LoadStoreAtomicTest<T, DeviceType>((T)i0, (T)i1); } return 0; } template <class T, class DeviceType> bool AtomicOperationsTestNonIntegralType(int i0, int i1, int test) { switch (test) { case 1: return MaxAtomicTest<T, DeviceType>((T)i0, (T)i1); case 2: return MinAtomicTest<T, DeviceType>((T)i0, (T)i1); case 3: return MulAtomicTest<T, DeviceType>((T)i0, (T)i1); case 4: return DivAtomicTest<T, DeviceType>((T)i0, (T)i1); case 5: return LoadStoreAtomicTest<T, DeviceType>((T)i0, (T)i1); } return 0; } } // namespace TestAtomicOperations
gpl-2.0
dan-harlav/sosb
sites/all/modules/contrib/wrappers_delight/modules/wrappers_delight_query/includes/WdUserWrapperQuery.php
6007
<?php /** * @file * Class WdUserWrapperQuery */ class WdUserWrapperQuery extends WdWrapperQuery { /** * Construct a WdUserWrapperQuery */ public function __construct() { parent::__construct('user'); } /** * Construct a WdUserWrapperQuery * * @return WdUserWrapperQuery */ public static function find() { return new self(); } /** * Query by the user UID. * * @param int $uid * @param string $operator * * @return $this */ public function byUid($uid, $operator = NULL) { return parent::byId($uid, $operator); } /** * Query by the user name. * * @param string $name * @param string $operator * * @return $this */ public function byName($name, $operator = NULL) { return $this->byPropertyConditions(array('name' => array($name, $operator))); } /** * Query by the user email address. * * @param string $mail * @param string $operator * * @return $this */ public function byMail($mail, $operator = NULL) { return $this->byPropertyConditions(array('mail' => array($mail, $operator))); } /** * Query by the user created time. * * @param int $time * @param string $operator * * @return $this */ public function byCreatedTime($time, $operator = NULL) { return $this->byPropertyConditions(array('created' => array($time, $operator))); } /** * Query by the user last login time. * * @param int $time * @param string $operator * * @return $this */ public function byLastLogin($time, $operator = NULL) { return $this->byPropertyConditions(array('login' => array($time, $operator))); } /** * Query by the user last access time. * * @param int $time * @param string $operator * * @return $this */ public function byLastAccess($time, $operator = NULL) { return $this->byPropertyConditions(array('access' => array($time, $operator))); } /** * Query by the user status * * @param int $status * @param string $operator * * @return $this */ public function byStatus($status, $operator = NULL) { return $this->byPropertyConditions(array('status' => array($status, $operator))); } /** * Query by the user picture. * * @param int $fid * @param string $operator * * @return $this */ public function byPicture($fid, $operator = NULL) { return $this->byPropertyConditions(array('picture' => array($fid, $operator))); } /** * Query by the user signature. * * @param string $signature * @param string $operator * * @return $this */ public function bySignature($signature, $operator = NULL) { return $this->byPropertyConditions(array('signature' => array($signature, $operator))); } /** * Query by the user theme. * * @param string $theme * @param string $operator * * @return $this */ public function byTheme($theme, $operator = NULL) { return $this->byPropertyConditions(array('theme' => array($theme, $operator))); } /** * Query by the user initial email address. * * @param string $mail * @param string $operator * * @return $this */ public function byInitialEmail($mail, $operator = NULL) { return $this->byPropertyConditions(array('init' => array($mail, $operator))); } /** * @return WdUserWrapperQueryResults */ public function execute() { return new WdUserWrapperQueryResults($this->entityType, $this->query->execute()); } /** * Order by UID * * @param string $direction * * @return $this */ public function orderByUid($direction = 'ASC') { return parent::orderById($direction); } /** * Order by created time * * @param string $direction * * @return $this */ public function orderByCreatedTime($direction = 'ASC') { return $this->orderByProperty('created', $direction); } /** * Order by initial email * * @param string $direction * * @return $this */ public function orderByInitialEmail($direction = 'ASC') { return $this->orderByProperty('init', $direction); } /** * Order by last access * * @param string $direction * * @return $this */ public function orderByLastAccess($direction = 'ASC') { return $this->orderByProperty('access', $direction); } /** * Order by last login * * @param string $direction * * @return $this */ public function orderByLastLogin($direction = 'ASC') { return $this->orderByProperty('login', $direction); } /** * Order by email * * @param string $direction * * @return $this */ public function orderByMail($direction = 'ASC') { return $this->orderByProperty('mail', $direction); } /** * Order by username * * @param string $direction * * @return $this */ public function orderByName($direction = 'ASC') { return $this->orderByProperty('name', $direction); } /** * Order by picture * * @param string $direction * * @return $this */ public function orderByPicture($direction = 'ASC') { return $this->orderByProperty('picture', $direction); } /** * Order by signature * * @param string $direction * * @return $this */ public function orderBySignature($direction = 'ASC') { return $this->orderByProperty('signature', $direction); } /** * Order by status * * @param string $direction * * @return $this */ public function orderByStatus($direction = 'ASC') { return $this->orderByProperty('status', $direction); } /** * Order by published theme * * @param string $direction * * @return $this */ public function orderByTheme($direction = 'ASC') { return $this->orderByProperty('theme', $direction); } } class WdUserWrapperQueryResults extends WdWrapperQueryResults { /** * @return WdUserWrapper */ public function current() { return parent::current(); } }
gpl-2.0
GiGa-Emulator/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/quest/katalam/_12844AnastasiaRequest.java
3890
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package quest.katalam; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.world.zone.ZoneName; /** * @author Romanz */ public class _12844AnastasiaRequest extends QuestHandler { private final static int questId = 12844; public _12844AnastasiaRequest() { super(questId); } @Override public void register() { qe.registerQuestNpc(801230).addOnTalkEvent(questId); qe.registerOnEnterZone(ZoneName.get("WZ_WEATHERZONELDF5A_WEATHER2_600050000"), questId); qe.registerOnKillInWorld(600050000, questId); } @Override public boolean onKillInWorldEvent(QuestEnv env) { Player player = env.getPlayer(); if (env.getVisibleObject() instanceof Player && player != null && player.isInsideZone(ZoneName.get("WZ_WEATHERZONELDF5A_WEATHER2_600050000"))) { if ((env.getPlayer().getLevel() >= (((Player)env.getVisibleObject()).getLevel() - 5)) && (env.getPlayer().getLevel() <= (((Player)env.getVisibleObject()).getLevel() + 9))) { return defaultOnKillRankedEvent(env, 0, 1, true); // reward } } return false; } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); int targetId = env.getTargetId(); if (qs != null && qs.getStatus() == QuestStatus.REWARD) { if (targetId == 801230) { switch (env.getDialog()) { case USE_OBJECT: return sendQuestDialog(env, 10002); case SELECT_QUEST_REWARD: return sendQuestDialog(env, 5); default: return sendQuestEndDialog(env); } } } return false; } @Override public boolean onEnterZoneEvent(QuestEnv env, ZoneName zoneName) { if (zoneName == ZoneName.get("WZ_WEATHERZONELDF5A_WEATHER2_600050000")) { Player player = env.getPlayer(); if (player == null) return false; QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null || qs.getStatus() == QuestStatus.NONE || qs.canRepeat()) { QuestService.startQuest(env); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(0, 0)); return true; } } return false; } }
gpl-2.0
tobiasbuhrer/tobiasb
vendor/symfony/http-foundation/IpUtils.php
5774
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpFoundation; /** * Http utility functions. * * @author Fabien Potencier <fabien@symfony.com> */ class IpUtils { private static $checkedIps = []; /** * This class should not be instantiated. */ private function __construct() { } /** * Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets. * * @param string $requestIp IP to check * @param string|array $ips List of IPs or subnets (can be a string if only a single one) * * @return bool Whether the IP is valid */ public static function checkIp($requestIp, $ips) { if (null === $requestIp) { return false; } if (!\is_array($ips)) { $ips = [$ips]; } $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4'; foreach ($ips as $ip) { if (self::$method($requestIp, $ip)) { return true; } } return false; } /** * Compares two IPv4 addresses. * In case a subnet is given, it checks if it contains the request IP. * * @param string $requestIp IPv4 address to check * @param string $ip IPv4 address or subnet in CIDR notation * * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet */ public static function checkIp4($requestIp, $ip) { $cacheKey = $requestIp.'-'.$ip; if (isset(self::$checkedIps[$cacheKey])) { return self::$checkedIps[$cacheKey]; } if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) { return self::$checkedIps[$cacheKey] = false; } if (str_contains($ip, '/')) { [$address, $netmask] = explode('/', $ip, 2); if ('0' === $netmask) { return self::$checkedIps[$cacheKey] = filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4); } if ($netmask < 0 || $netmask > 32) { return self::$checkedIps[$cacheKey] = false; } } else { $address = $ip; $netmask = 32; } if (false === ip2long($address)) { return self::$checkedIps[$cacheKey] = false; } return self::$checkedIps[$cacheKey] = 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask); } /** * Compares two IPv6 addresses. * In case a subnet is given, it checks if it contains the request IP. * * @author David Soria Parra <dsp at php dot net> * * @see https://github.com/dsp/v6tools * * @param string $requestIp IPv6 address to check * @param string $ip IPv6 address or subnet in CIDR notation * * @return bool Whether the IP is valid * * @throws \RuntimeException When IPV6 support is not enabled */ public static function checkIp6($requestIp, $ip) { $cacheKey = $requestIp.'-'.$ip; if (isset(self::$checkedIps[$cacheKey])) { return self::$checkedIps[$cacheKey]; } if (!((\extension_loaded('sockets') && \defined('AF_INET6')) || @inet_pton('::1'))) { throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".'); } if (str_contains($ip, '/')) { [$address, $netmask] = explode('/', $ip, 2); if ('0' === $netmask) { return (bool) unpack('n*', @inet_pton($address)); } if ($netmask < 1 || $netmask > 128) { return self::$checkedIps[$cacheKey] = false; } } else { $address = $ip; $netmask = 128; } $bytesAddr = unpack('n*', @inet_pton($address)); $bytesTest = unpack('n*', @inet_pton($requestIp)); if (!$bytesAddr || !$bytesTest) { return self::$checkedIps[$cacheKey] = false; } for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) { $left = $netmask - 16 * ($i - 1); $left = ($left <= 16) ? $left : 16; $mask = ~(0xFFFF >> $left) & 0xFFFF; if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) { return self::$checkedIps[$cacheKey] = false; } } return self::$checkedIps[$cacheKey] = true; } /** * Anonymizes an IP/IPv6. * * Removes the last byte for v4 and the last 8 bytes for v6 IPs */ public static function anonymize(string $ip): string { $wrappedIPv6 = false; if ('[' === substr($ip, 0, 1) && ']' === substr($ip, -1, 1)) { $wrappedIPv6 = true; $ip = substr($ip, 1, -1); } $packedAddress = inet_pton($ip); if (4 === \strlen($packedAddress)) { $mask = '255.255.255.0'; } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) { $mask = '::ffff:ffff:ff00'; } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) { $mask = '::ffff:ff00'; } else { $mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000'; } $ip = inet_ntop($packedAddress & inet_pton($mask)); if ($wrappedIPv6) { $ip = '['.$ip.']'; } return $ip; } }
gpl-2.0
javalidigital/riema
wp-content/plugins/simple-links/classes/Simple_Link.php
3305
<?php /** * Simple Link * * Custom Post Type handler * * @class Simple_Link * @package Simple Links * * @since 2.5.3 * * * @todo Remove SL_post_type_tax dependencies * */ class Simple_Link { const POST_TYPE = 'simple_link'; private $post_id; /** * @var self */ static $current; public function __construct( $id ){ $this->post_id = $id; self::$current = $this; } /** * Register Post Type * * Registers the simple_link post type * * @todo change to register_post_type once dependcies are fixed * * @return void */ public static function register_sl_post_type(){ $single = __( 'Link', 'simple-links' ); $plural = __( 'Links', 'simple-links' ); $args = array( 'menu_icon' => SIMPLE_LINKS_IMG_DIR . 'menu-icon.png', 'labels' => array( 'name' => __( 'Simple Links', 'simple-links' ), 'singular_name' => $single, 'search_items' => sprintf( __( 'Search %s', 'simple-links' ), $plural ), 'popular_items' => sprintf( __( 'Popular %s', 'simple-links' ), $plural ), 'all_items' => sprintf( __( 'All %s', 'simple-links' ), $plural ), 'parent_item' => sprintf( __( 'Parent %s', 'simple-links' ), $single ), 'parent_item_colon' => sprintf( __( 'Parent %s:', 'simple-links' ), $single ), 'edit_item' => sprintf( __( 'Edit %s', 'simple-links' ), $single ), 'update_item' => sprintf( __( 'Update %s', 'simple-links' ), $single ), 'add_new_item' => sprintf( __( 'Add New %s', 'simple-links' ), $single ), 'new_item_name' => sprintf( __( 'New %s Name', 'simple-links' ), $single ), 'separate_items_with_commas' => sprintf( __( 'Separate %s with commas', 'simple-links' ), $single ), 'add_or_remove_items' => sprintf( __( 'Add or remove %s', 'simple-links' ), $plural ), 'choose_from_most_used' => sprintf( __( 'Choose from the most used %s', 'simple-links' ), $plural ), 'view_item' => sprintf( __( 'View %s', 'simple-links' ), $single ), 'add_new' => sprintf( __( 'Add New %s', 'simple-links' ), $single ), 'new_item' => sprintf( __( 'New %s', 'simple-links' ), $single ), 'menu_name' => __( 'Simple Links', 'simple-links' ), 'not_found' => sprintf( __('No %s found.', 'simple-links' ), $plural ), 'not_found_in_trash' => sprintf( __('No %s found in Trash.', 'simple-links' ), $plural ), ), 'hierachical' => false, 'supports' => array( 'thumbnail', 'title', 'page-attributes', 'revisions' ), 'publicly_queryable' => false, 'public' => false, 'show_ui' => true, 'show_in_nav_menus' => false, 'has_archive' => false, 'rewrite' => false, 'exclude_from_search' => true, 'register_meta_box_cb' => array( Simple_Links_Meta_Boxes::get_instance(), 'meta_box' ) ); register_post_type( self::POST_TYPE, apply_filters( 'simple-links-register-post-type', $args ) ); } }
gpl-2.0
dhenrygithub/QGIS
python/plugins/processing/algs/gdal/tri.py
2757
# -*- coding: utf-8 -*- """ *************************************************************************** tri.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Alexander Bruy' __date__ = 'October 2013' __copyright__ = '(C) 2013, Alexander Bruy' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm from processing.core.parameters import ParameterRaster from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterNumber from processing.core.outputs import OutputRaster from processing.algs.gdal.GdalUtils import GdalUtils pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] class tri(GdalAlgorithm): INPUT = 'INPUT' BAND = 'BAND' COMPUTE_EDGES = 'COMPUTE_EDGES' OUTPUT = 'OUTPUT' def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('TRI (Terrain Ruggedness Index)') self.group, self.i18n_group = self.trAlgorithm('[GDAL] Analysis') self.addParameter(ParameterRaster(self.INPUT, self.tr('Input layer'))) self.addParameter(ParameterNumber(self.BAND, self.tr('Band number'), 1, 99, 1)) self.addParameter(ParameterBoolean(self.COMPUTE_EDGES, self.tr('Compute edges'), False)) self.addOutput(OutputRaster(self.OUTPUT, self.tr('Terrain Ruggedness Index'))) def getConsoleCommands(self): arguments = ['TRI'] arguments.append(unicode(self.getParameterValue(self.INPUT))) arguments.append(unicode(self.getOutputValue(self.OUTPUT))) arguments.append('-b') arguments.append(unicode(self.getParameterValue(self.BAND))) if self.getParameterValue(self.COMPUTE_EDGES): arguments.append('-compute_edges') return ['gdaldem', GdalUtils.escapeAndJoin(arguments)]
gpl-2.0
lcrojanouninorte/gie_portal
sites/all/libraries/ckeditor/plugins/googledocs/dialogs/googledocs.js
4109
CKEDITOR.dialog.add('googledocs', function (editor) { return { title: editor.lang.googledocs.title, width: 400, height: 350, onLoad : function() { getDocuments(); }, contents: [ // document settings tab { id: 'settingsTab', label: editor.lang.googledocs.settingsTab, elements: [ // select { type: 'select', id: 'documents', className: 'googledocs', label: editor.lang.googledocs.selectDocument, items: [], 'default': '', size: 4, onChange: function( api ) { var dialog = CKEDITOR.dialog.getCurrent(); var url = dialog.getContentElement('settingsTab', 'txtUrl'); url.setValue( this.getValue() ); } }, // url { type: 'text', id: 'txtUrl', label: editor.lang.googledocs.url, required: true, validate: CKEDITOR.dialog.validate.notEmpty( editor.lang.googledocs.alertUrl ) }, // options { type: 'hbox', widths: [ '60px', '330px' ], className: 'googledocs', children: [ // width { type: 'text', width: '45px', id: 'txtWidth', label: editor.lang.common.width, 'default': 710, required: true, validate: CKEDITOR.dialog.validate.integer( editor.lang.googledocs.alertWidth ) }, // height { type: 'text', id: 'txtHeight', width: '45px', label: editor.lang.common.height, 'default': 920, required: true, validate: CKEDITOR.dialog.validate.integer( editor.lang.googledocs.alertHeight ) } ] } ] }, // upload tab { id: 'uploadTab', label: editor.lang.googledocs.uploadTab, filebrowser: 'uploadButton', elements: [ // file input { type: 'file', id: 'upload' }, // submit button { type: 'fileButton', id: 'uploadButton', label: editor.lang.googledocs.btnUpload, filebrowser: { action: 'QuickUpload', // target: 'settingsTab:txtUrl', onSelect: function( fileUrl, data ) { getDocuments( fileUrl ); } }, 'for': [ 'uploadTab', 'upload' ] } ] } ], onOk: function() { var dialog = this; var iframe = editor.document.createElement( 'iframe' ); var srcEncoded = encodeURIComponent( dialog.getValueOf( 'settingsTab', 'txtUrl' ) ); iframe.setAttribute( 'src', 'http://docs.google.com/viewer?url=' + srcEncoded + '&embedded=true' ); iframe.setAttribute( 'width', dialog.getValueOf( 'settingsTab', 'txtWidth' ) ); iframe.setAttribute( 'height', dialog.getValueOf( 'settingsTab', 'txtHeight' ) ); iframe.setAttribute( 'style', 'border: none;' ); editor.insertElement( iframe ); }, onShow: function() { getDocuments(); } }; }); // get documents list in format [[document1_name, document1_url],[document2_name, document2_url], ...] var getDocuments = function( url ) { if( CKEDITOR.env.ie7Compat ) { fixIE7display(); } $.get( CKEDITOR.currentInstance.config.filebrowserGoogledocsBrowseUrl, function( data ) { var dialog = CKEDITOR.dialog.getCurrent(); var documents = dialog.getContentElement('settingsTab', 'documents'); documents.clear(); $.each( data, function( index, document ) { documents.add( document.name, document.url ); }); documents.setValue( url ); console.log( url ); url && documents.focus(); }, "json" ); };
gpl-2.0
TripleYou/WordPress_3.7_kit_startup
wp-includes/meta.php
29091
<?php /** * Metadata API * * Functions for retrieving and manipulating metadata of various WordPress object types. Metadata * for an object is a represented by a simple key-value pair. Objects may contain multiple * metadata entries that share the same key and differ only in their value. * * @package WordPress * @subpackage Meta * @since 2.9.0 */ /** * Add metadata for the specified object. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * @uses do_action() Calls 'added_{$meta_type}_meta' with meta_id of added metadata entry, * object ID, meta key, and meta value * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key * @param mixed $meta_value Metadata value. Must be serializable if non-scalar. * @param bool $unique Optional, default is false. Whether the specified metadata key should be * unique for the object. If true, and the object already has a value for the specified * metadata key, no change will be made * @return int|bool The meta ID on successful update, false on failure. */ function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) { if ( !$meta_type || !$meta_key ) return false; if ( !$object_id = absint($object_id) ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; global $wpdb; $column = sanitize_key($meta_type . '_id'); // expected_slashed ($meta_key) $meta_key = wp_unslash($meta_key); $meta_value = wp_unslash($meta_value); $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type ); $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique ); if ( null !== $check ) return $check; if ( $unique && $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) ) return false; $_meta_value = $meta_value; $meta_value = maybe_serialize( $meta_value ); do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value ); $result = $wpdb->insert( $table, array( $column => $object_id, 'meta_key' => $meta_key, 'meta_value' => $meta_value ) ); if ( ! $result ) return false; $mid = (int) $wpdb->insert_id; wp_cache_delete($object_id, $meta_type . '_meta'); do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value ); return $mid; } /** * Update metadata for the specified object. If no value already exists for the specified object * ID and metadata key, the metadata will be added. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of * metadata entry to update, object ID, meta key, and meta value * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of * updated metadata entry, object ID, meta key, and meta value * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key * @param mixed $meta_value Metadata value. Must be serializable if non-scalar. * @param mixed $prev_value Optional. If specified, only update existing metadata entries with * the specified value. Otherwise, update all entries. * @return bool True on successful update, false on failure. */ function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') { if ( !$meta_type || !$meta_key ) return false; if ( !$object_id = absint($object_id) ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; global $wpdb; $column = sanitize_key($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // expected_slashed ($meta_key) $meta_key = wp_unslash($meta_key); $passed_value = $meta_value; $meta_value = wp_unslash($meta_value); $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type ); $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value ); if ( null !== $check ) return (bool) $check; // Compare existing value to new value if no prev value given and the key exists only once. if ( empty($prev_value) ) { $old_value = get_metadata($meta_type, $object_id, $meta_key); if ( count($old_value) == 1 ) { if ( $old_value[0] === $meta_value ) return false; } } if ( ! $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) ) return add_metadata($meta_type, $object_id, $meta_key, $passed_value); $_meta_value = $meta_value; $meta_value = maybe_serialize( $meta_value ); $data = compact( 'meta_value' ); $where = array( $column => $object_id, 'meta_key' => $meta_key ); if ( !empty( $prev_value ) ) { $prev_value = maybe_serialize($prev_value); $where['meta_value'] = $prev_value; } do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); if ( 'post' == $meta_type ) do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value ); $result = $wpdb->update( $table, $data, $where ); if ( ! $result ) return false; wp_cache_delete($object_id, $meta_type . '_meta'); do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); if ( 'post' == $meta_type ) do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value ); return true; } /** * Delete metadata for the specified object. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of * deleted metadata entries, object ID, meta key, and meta value * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key * @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar. If specified, only delete metadata entries * with this value. Otherwise, delete all entries with the specified meta_key. * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries * for all objects, ignoring the specified object_id. Otherwise, only delete matching * metadata entries for the specified object_id. * @return bool True on successful delete, false on failure. */ function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) { if ( !$meta_type || !$meta_key ) return false; if ( (!$object_id = absint($object_id)) && !$delete_all ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; global $wpdb; $type_column = sanitize_key($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // expected_slashed ($meta_key) $meta_key = wp_unslash($meta_key); $meta_value = wp_unslash($meta_value); $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all ); if ( null !== $check ) return (bool) $check; $_meta_value = $meta_value; $meta_value = maybe_serialize( $meta_value ); $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key ); if ( !$delete_all ) $query .= $wpdb->prepare(" AND $type_column = %d", $object_id ); if ( $meta_value ) $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value ); $meta_ids = $wpdb->get_col( $query ); if ( !count( $meta_ids ) ) return false; if ( $delete_all ) $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) ); do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value ); // Old-style action. if ( 'post' == $meta_type ) do_action( 'delete_postmeta', $meta_ids ); $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )"; $count = $wpdb->query($query); if ( !$count ) return false; if ( $delete_all ) { foreach ( (array) $object_ids as $o_id ) { wp_cache_delete($o_id, $meta_type . '_meta'); } } else { wp_cache_delete($object_id, $meta_type . '_meta'); } do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value ); // Old-style action. if ( 'post' == $meta_type ) do_action( 'deleted_postmeta', $meta_ids ); return true; } /** * Retrieve metadata for the specified object. * * @since 2.9.0 * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for * the specified object. * @param bool $single Optional, default is false. If true, return only the first value of the * specified meta_key. This parameter has no effect if meta_key is not specified. * @return string|array Single metadata value, or array of values */ function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) { if ( !$meta_type ) return false; if ( !$object_id = absint($object_id) ) return false; $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single ); if ( null !== $check ) { if ( $single && is_array( $check ) ) return $check[0]; else return $check; } $meta_cache = wp_cache_get($object_id, $meta_type . '_meta'); if ( !$meta_cache ) { $meta_cache = update_meta_cache( $meta_type, array( $object_id ) ); $meta_cache = $meta_cache[$object_id]; } if ( !$meta_key ) return $meta_cache; if ( isset($meta_cache[$meta_key]) ) { if ( $single ) return maybe_unserialize( $meta_cache[$meta_key][0] ); else return array_map('maybe_unserialize', $meta_cache[$meta_key]); } if ($single) return ''; else return array(); } /** * Determine if a meta key is set for a given object * * @since 3.3.0 * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key. * @return boolean true of the key is set, false if not. */ function metadata_exists( $meta_type, $object_id, $meta_key ) { if ( ! $meta_type ) return false; if ( ! $object_id = absint( $object_id ) ) return false; $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true ); if ( null !== $check ) return true; $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' ); if ( !$meta_cache ) { $meta_cache = update_meta_cache( $meta_type, array( $object_id ) ); $meta_cache = $meta_cache[$object_id]; } if ( isset( $meta_cache[ $meta_key ] ) ) return true; return false; } /** * Get meta data by meta ID * * @since 3.3.0 * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $meta_id ID for a specific meta row * @return object Meta object or false. */ function get_metadata_by_mid( $meta_type, $meta_id ) { global $wpdb; if ( ! $meta_type ) return false; if ( !$meta_id = absint( $meta_id ) ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; $id_column = ( 'user' == $meta_type ) ? 'umeta_id' : 'meta_id'; $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) ); if ( empty( $meta ) ) return false; if ( isset( $meta->meta_value ) ) $meta->meta_value = maybe_unserialize( $meta->meta_value ); return $meta; } /** * Update meta data by meta ID * * @since 3.3.0 * * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value * and object_id of the given meta_id. * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $meta_id ID for a specific meta row * @param string $meta_value Metadata value * @param string $meta_key Optional, you can provide a meta key to update it * @return bool True on successful update, false on failure. */ function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) { global $wpdb; // Make sure everything is valid. if ( ! $meta_type ) return false; if ( ! $meta_id = absint( $meta_id ) ) return false; if ( ! $table = _get_meta_table( $meta_type ) ) return false; $column = sanitize_key($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // Fetch the meta and go on if it's found. if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) { $original_key = $meta->meta_key; $original_value = $meta->meta_value; $object_id = $meta->{$column}; // If a new meta_key (last parameter) was specified, change the meta key, // otherwise use the original key in the update statement. if ( false === $meta_key ) { $meta_key = $original_key; } elseif ( ! is_string( $meta_key ) ) { return false; } // Sanitize the meta $_meta_value = $meta_value; $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type ); $meta_value = maybe_serialize( $meta_value ); // Format the data query arguments. $data = array( 'meta_key' => $meta_key, 'meta_value' => $meta_value ); // Format the where query arguments. $where = array(); $where[$id_column] = $meta_id; do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); if ( 'post' == $meta_type ) do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value ); // Run the update query, all fields in $data are %s, $where is a %d. $result = $wpdb->update( $table, $data, $where, '%s', '%d' ); if ( ! $result ) return false; // Clear the caches. wp_cache_delete($object_id, $meta_type . '_meta'); do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); if ( 'post' == $meta_type ) do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value ); return true; } // And if the meta was not found. return false; } /** * Delete meta data by meta ID * * @since 3.3.0 * * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value * and object_id of the given meta_id. * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $meta_id ID for a specific meta row * @return bool True on successful delete, false on failure. */ function delete_metadata_by_mid( $meta_type, $meta_id ) { global $wpdb; // Make sure everything is valid. if ( ! $meta_type ) return false; if ( ! $meta_id = absint( $meta_id ) ) return false; if ( ! $table = _get_meta_table( $meta_type ) ) return false; // object and id columns $column = sanitize_key($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // Fetch the meta and go on if it's found. if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) { $object_id = $meta->{$column}; do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value ); // Old-style action. if ( 'post' == $meta_type || 'comment' == $meta_type ) do_action( "delete_{$meta_type}meta", $meta_id ); // Run the query, will return true if deleted, false otherwise $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) ); // Clear the caches. wp_cache_delete($object_id, $meta_type . '_meta'); do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value ); // Old-style action. if ( 'post' == $meta_type || 'comment' == $meta_type ) do_action( "deleted_{$meta_type}meta", $meta_id ); return $result; } // Meta id was not found. return false; } /** * Update the metadata cache for the specified objects. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int|array $object_ids array or comma delimited list of object IDs to update cache for * @return mixed Metadata cache for the specified objects, or false on failure. */ function update_meta_cache($meta_type, $object_ids) { if ( empty( $meta_type ) || empty( $object_ids ) ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; $column = sanitize_key($meta_type . '_id'); global $wpdb; if ( !is_array($object_ids) ) { $object_ids = preg_replace('|[^0-9,]|', '', $object_ids); $object_ids = explode(',', $object_ids); } $object_ids = array_map('intval', $object_ids); $cache_key = $meta_type . '_meta'; $ids = array(); $cache = array(); foreach ( $object_ids as $id ) { $cached_object = wp_cache_get( $id, $cache_key ); if ( false === $cached_object ) $ids[] = $id; else $cache[$id] = $cached_object; } if ( empty( $ids ) ) return $cache; // Get meta info $id_list = join(',', $ids); $meta_list = $wpdb->get_results( $wpdb->prepare("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)", $meta_type), ARRAY_A ); if ( !empty($meta_list) ) { foreach ( $meta_list as $metarow) { $mpid = intval($metarow[$column]); $mkey = $metarow['meta_key']; $mval = $metarow['meta_value']; // Force subkeys to be array type: if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) ) $cache[$mpid] = array(); if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) ) $cache[$mpid][$mkey] = array(); // Add a value to the current pid/key: $cache[$mpid][$mkey][] = $mval; } } foreach ( $ids as $id ) { if ( ! isset($cache[$id]) ) $cache[$id] = array(); wp_cache_add( $id, $cache[$id], $cache_key ); } return $cache; } /** * Given a meta query, generates SQL clauses to be appended to a main query * * @since 3.2.0 * * @see WP_Meta_Query * * @param array $meta_query A meta query * @param string $type Type of meta * @param string $primary_table * @param string $primary_id_column * @param object $context (optional) The main query object * @return array( 'join' => $join_sql, 'where' => $where_sql ) */ function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) { $meta_query_obj = new WP_Meta_Query( $meta_query ); return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context ); } /** * Container class for a multiple metadata query * * @since 3.2.0 */ class WP_Meta_Query { /** * List of metadata queries. A single query is an associative array: * - 'key' string The meta key * - 'value' string|array The meta value * - 'compare' (optional) string How to compare the key to the value. * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', * 'BETWEEN', 'NOT BETWEEN', 'REGEXP', 'NOT REGEXP', 'RLIKE'. * Default: '=' * - 'type' string (optional) The type of the value. * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. * Default: 'CHAR' * * @since 3.2.0 * @access public * @var array */ public $queries = array(); /** * The relation between the queries. Can be one of 'AND' or 'OR'. * * @since 3.2.0 * @access public * @var string */ public $relation; /** * Constructor * * @param array $meta_query (optional) A meta query */ function __construct( $meta_query = false ) { if ( !$meta_query ) return; if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) { $this->relation = 'OR'; } else { $this->relation = 'AND'; } $this->queries = array(); foreach ( $meta_query as $key => $query ) { if ( ! is_array( $query ) ) continue; $this->queries[] = $query; } } /** * Constructs a meta query based on 'meta_*' query vars * * @since 3.2.0 * @access public * * @param array $qv The query variables */ function parse_query_vars( $qv ) { $meta_query = array(); // Simple query needs to be first for orderby=meta_value to work correctly foreach ( array( 'key', 'compare', 'type' ) as $key ) { if ( !empty( $qv[ "meta_$key" ] ) ) $meta_query[0][ $key ] = $qv[ "meta_$key" ]; } // WP_Query sets 'meta_value' = '' by default if ( isset( $qv[ 'meta_value' ] ) && '' !== $qv[ 'meta_value' ] && ( ! is_array( $qv[ 'meta_value' ] ) || $qv[ 'meta_value' ] ) ) $meta_query[0]['value'] = $qv[ 'meta_value' ]; if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) { $meta_query = array_merge( $meta_query, $qv['meta_query'] ); } $this->__construct( $meta_query ); } /** * Given a meta type, return the appropriate alias if applicable * * @since 3.7.0 * * @param string $type MySQL type to cast meta_value * @return string MySQL type */ function get_cast_for_type( $type = '' ) { if ( empty( $type ) ) return 'CHAR'; $meta_type = strtoupper( $type ); if ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED', 'NUMERIC' ) ) ) return 'CHAR'; if ( 'NUMERIC' == $meta_type ) $meta_type = 'SIGNED'; return $meta_type; } /** * Generates SQL clauses to be appended to a main query. * * @since 3.2.0 * @access public * * @param string $type Type of meta * @param string $primary_table * @param string $primary_id_column * @param object $context (optional) The main query object * @return array( 'join' => $join_sql, 'where' => $where_sql ) */ function get_sql( $type, $primary_table, $primary_id_column, $context = null ) { global $wpdb; if ( ! $meta_table = _get_meta_table( $type ) ) return false; $meta_id_column = sanitize_key( $type . '_id' ); $join = array(); $where = array(); $key_only_queries = array(); $queries = array(); // Split out the queries with empty arrays as value foreach ( $this->queries as $k => $q ) { if ( isset( $q['value'] ) && is_array( $q['value'] ) && empty( $q['value'] ) ) { $key_only_queries[$k] = $q; unset( $this->queries[$k] ); } } // Split out the meta_key only queries (we can only do this for OR) if ( 'OR' == $this->relation ) { foreach ( $this->queries as $k => $q ) { if ( ! isset( $q['value'] ) && ! empty( $q['key'] ) ) $key_only_queries[$k] = $q; else $queries[$k] = $q; } } else { $queries = $this->queries; } // Specify all the meta_key only queries in one go if ( $key_only_queries ) { $join[] = "INNER JOIN $meta_table ON $primary_table.$primary_id_column = $meta_table.$meta_id_column"; foreach ( $key_only_queries as $key => $q ) $where["key-only-$key"] = $wpdb->prepare( "$meta_table.meta_key = %s", trim( $q['key'] ) ); } foreach ( $queries as $k => $q ) { $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : ''; $meta_type = $this->get_cast_for_type( isset( $q['type'] ) ? $q['type'] : '' ); $meta_value = isset( $q['value'] ) ? $q['value'] : null; if ( isset( $q['compare'] ) ) $meta_compare = strtoupper( $q['compare'] ); else $meta_compare = is_array( $meta_value ) ? 'IN' : '='; if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'NOT EXISTS', 'REGEXP', 'NOT REGEXP', 'RLIKE' ) ) ) $meta_compare = '='; $i = count( $join ); $alias = $i ? 'mt' . $i : $meta_table; if ( 'NOT EXISTS' == $meta_compare ) { $join[$i] = "LEFT JOIN $meta_table"; $join[$i] .= $i ? " AS $alias" : ''; $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column AND $alias.meta_key = '$meta_key')"; $where[$k] = ' ' . $alias . '.' . $meta_id_column . ' IS NULL'; continue; } $join[$i] = "INNER JOIN $meta_table"; $join[$i] .= $i ? " AS $alias" : ''; $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)"; $where[$k] = ''; if ( !empty( $meta_key ) ) $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key ); if ( is_null( $meta_value ) ) { if ( empty( $where[$k] ) ) unset( $join[$i] ); continue; } if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) { if ( ! is_array( $meta_value ) ) $meta_value = preg_split( '/[,\s]+/', $meta_value ); if ( empty( $meta_value ) ) { unset( $join[$i] ); continue; } } else { $meta_value = trim( $meta_value ); } if ( 'IN' == substr( $meta_compare, -2) ) { $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')'; } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) { $meta_value = array_slice( $meta_value, 0, 2 ); $meta_compare_string = '%s AND %s'; } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) { $meta_value = '%' . like_escape( $meta_value ) . '%'; $meta_compare_string = '%s'; } else { $meta_compare_string = '%s'; } if ( ! empty( $where[$k] ) ) $where[$k] .= ' AND '; $where[$k] = ' (' . $where[$k] . $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value ); } $where = array_filter( $where ); if ( empty( $where ) ) $where = ''; else $where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )'; $join = implode( "\n", $join ); if ( ! empty( $join ) ) $join = ' ' . $join; return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $this->queries, $type, $primary_table, $primary_id_column, $context ) ); } } /** * Retrieve the name of the metadata table for the specified object type. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * * @param string $type Type of object to get metadata table for (e.g., comment, post, or user) * @return mixed Metadata table name, or false if no metadata table exists */ function _get_meta_table($type) { global $wpdb; $table_name = $type . 'meta'; if ( empty($wpdb->$table_name) ) return false; return $wpdb->$table_name; } /** * Determine whether a meta key is protected * * @since 3.1.3 * * @param string $meta_key Meta key * @return bool True if the key is protected, false otherwise. */ function is_protected_meta( $meta_key, $meta_type = null ) { $protected = ( '_' == $meta_key[0] ); return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type ); } /** * Sanitize meta value * * @since 3.1.3 * * @param string $meta_key Meta key * @param mixed $meta_value Meta value to sanitize * @param string $meta_type Type of meta * @return mixed Sanitized $meta_value */ function sanitize_meta( $meta_key, $meta_value, $meta_type ) { return apply_filters( "sanitize_{$meta_type}_meta_{$meta_key}", $meta_value, $meta_key, $meta_type ); } /** * Register meta key * * @since 3.3.0 * * @param string $meta_type Type of meta * @param string $meta_key Meta key * @param string|array $sanitize_callback A function or method to call when sanitizing the value of $meta_key. * @param string|array $auth_callback Optional. A function or method to call when performing edit_post_meta, add_post_meta, and delete_post_meta capability checks. * @param array $args Arguments */ function register_meta( $meta_type, $meta_key, $sanitize_callback, $auth_callback = null ) { if ( is_callable( $sanitize_callback ) ) add_filter( "sanitize_{$meta_type}_meta_{$meta_key}", $sanitize_callback, 10, 3 ); if ( empty( $auth_callback ) ) { if ( is_protected_meta( $meta_key, $meta_type ) ) $auth_callback = '__return_false'; else $auth_callback = '__return_true'; } if ( is_callable( $auth_callback ) ) add_filter( "auth_{$meta_type}_meta_{$meta_key}", $auth_callback, 10, 6 ); }
gpl-2.0
chrisinammo/arthurmcneil
components/com_search/views/search/tmpl/default_form.php
2282
<?php defined('_JEXEC') or die('Restricted access'); ?> <form id="searchForm" action="<?php echo JRoute::_( 'index.php?option=com_search' );?>" method="post" name="searchForm"> <table class="contentpaneopen<?php echo $this->params->get( 'pageclass_sfx' ); ?>"> <tr> <td nowrap="nowrap"> <label for="search_searchword"> <?php echo JText::_( 'Search Keyword' ); ?>: </label> </td> <td nowrap="nowrap"> <input type="text" name="searchword" id="search_searchword" size="30" maxlength="20" value="<?php echo $this->escape($this->searchword); ?>" class="inputbox" /> </td> <td width="100%" nowrap="nowrap"> <button name="Search" onClick="this.form.submit()" class="button"><?php echo JText::_( 'Search' );?></button> </td> </tr> <tr> <td colspan="3"> <?php echo $this->lists['searchphrase']; ?> </td> </tr> <tr> <td colspan="3"> <label for="ordering"> <?php echo JText::_( 'Ordering' );?>: </label> <?php echo $this->lists['ordering'];?> </td> </tr> </table> <?php if ($this->params->get( 'search_areas', 1 )) : ?> <?php echo JText::_( 'Search Only' );?>: <?php foreach ($this->searchareas['search'] as $val => $txt) : $checked = is_array( $this->searchareas['active'] ) && in_array( $val, $this->searchareas['active'] ) ? 'checked="checked"' : ''; ?> <input type="checkbox" name="areas[]" value="<?php echo $val;?>" id="area_<?php echo $val;?>" <?php echo $checked;?> /> <label for="area_<?php echo $val;?>"> <?php echo JText::_($txt); ?> </label> <?php endforeach; ?> <?php endif; ?> <table class="searchintro<?php echo $this->params->get( 'pageclass_sfx' ); ?>"> <tr> <td colspan="3" > <br /> <?php echo JText::_( 'Search Keyword' ) .' <b>'. $this->escape($this->searchword) .'</b>'; ?> </td> </tr> <tr> <td> <br /> <?php echo $this->result; ?> </td> </tr> </table> <br /> <?php if($this->total > 0) : ?> <div align="center"> <div style="float: right;"> <label for="limit"> <?php echo JText::_( 'Display Num' ); ?> </label> <?php echo $this->pagination->getLimitBox( ); ?> </div> <div> <?php echo $this->pagination->getPagesCounter(); ?> </div> </div> <?php endif; ?> <input type="hidden" name="task" value="search" /> </form>
gpl-2.0
cw196/tiwal
wp-includes/version.php
642
<?php /** * The WordPress version string * * @global string $wp_version */ $wp_version = '4.3.1'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. * * @global int $wp_db_version */ $wp_db_version = 33056; /** * Holds the TinyMCE version * * @global string $tinymce_version */ $tinymce_version = '4205-20150910'; /** * Holds the required PHP version * * @global string $required_php_version */ $required_php_version = '5.2.4'; /** * Holds the required MySQL version * * @global string $required_mysql_version */ $required_mysql_version = '5.0'; $wp_local_package = '';
gpl-2.0
plone/plone.patternslib
src/plone/patternslib/static/components/patternslib/src/pat/expandable-tree/expandable-tree.js
2265
define([ "jquery", "pat-inject", "pat-parser", "pat-registry" ], function($, inject, Parser, registry) { var parser = new Parser("expandable"); parser.addArgument("load-content"); var _ = { name: "expandable", trigger: "ul.pat-expandable", jquery_plugin: true, init: function($el) { // make sure inject folders have a ul $el.find(".folder[data-pat-expandable]:not(:has(ul))") .append("<ul />"); // find all folders that contain a ul var $folders = $el.find("li.folder:has(ul)"); // inject span.toggle as first child of each folder $folders.prepend("<span class='toggle'></span>"); // all folders are implicitly closed $folders.filter(":not(.open,.closed)").addClass("closed"); // trigger open event for open folders $folders.filter(".open").trigger("patterns-folder-open"); // wire spans as control elements var $ctrls = $el.find("span.toggle"); $ctrls.each(function() { var $ctrl = $(this), $folder = $ctrl.parent(); $ctrl.on("click.pat-expandable", function() { $folder.toggleClass("open closed") .filter(".open[data-pat-expandable]") .patExpandable("loadContent"); }); }); return $el; }, loadContent: function($el) { return $el.each(function() { var $el = $(this), url = parser.parse($el).loadContent, components = url.split("#"), base_url = components[0], id = components[1] ? "#" + components[1] : "body", opts = [{ url: base_url, source: id, $target: $el.find("ul"), dataType: "html" }]; inject.execute(opts, $el); }); } }; registry.register(_); return _; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
gpl-2.0
Frazurbluu/ServUO
Scripts/Services/Monster Stealing/Items/StoneSkinLotion.cs
1246
using System; using Server.Mobiles; using Server; namespace Server.Items { [TypeAlias("drNO.ThieveItems.StoneSkinLotion")] public class StoneSkinLotion : BaseBalmOrLotion { protected override void ApplyEffect(PlayerMobile pm) { pm.AddResistanceMod(new ResistanceMod(ResistanceType.Cold, -5)); pm.AddResistanceMod(new ResistanceMod(ResistanceType.Fire, -5)); pm.AddResistanceMod(new ResistanceMod(ResistanceType.Physical, 30)); base.ApplyEffect(pm); } public override int LabelNumber { get { return 1094944; } } // Stone Skin Lotion [Constructable] public StoneSkinLotion() : base(0xEFD) { m_EffectType = ThieveConsumableEffect.StoneSkinLotionEffect; } public StoneSkinLotion(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
gpl-2.0
alexbevi/scummvm
engines/xeen/dialogs/dialogs_message.cpp
3317
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "common/scummsys.h" #include "xeen/dialogs/dialogs_message.h" #include "xeen/events.h" #include "xeen/xeen.h" namespace Xeen { void MessageDialog::show(XeenEngine *vm, const Common::String &msg, MessageWaitType waitType) { MessageDialog *dlg = new MessageDialog(vm); dlg->execute(msg, waitType); delete dlg; } void MessageDialog::execute(const Common::String &msg, MessageWaitType waitType) { EventsManager &events = *_vm->_events; Windows &windows = *_vm->_windows; Window &w = windows[6]; w.open(); w.writeString(msg); w.update(); switch (waitType) { case WT_FREEZE_WAIT: while (!_vm->shouldExit() && !events.isKeyMousePressed()) events.pollEventsAndWait(); events.clearEvents(); break; case WT_ANIMATED_WAIT: if (windows[11]._enabled || _vm->_mode == MODE_INTERACTIVE7) { g_vm->_locations->wait(); break; } // fall through case WT_NONFREEZED_WAIT: do { events.updateGameCounter(); _vm->_interface->draw3d(true); events.wait(1); if (checkEvents(_vm)) break; } while (!_vm->shouldExit() && !_buttonValue); break; case WT_LOC_WAIT: g_vm->_locations->wait(); break; default: break; } w.close(); } /*------------------------------------------------------------------------*/ void ErrorScroll::show(XeenEngine *vm, const Common::String &msg, MessageWaitType waitType) { Common::String s = Common::String::format("\x3""c\v010\t000%s", msg.c_str()); MessageDialog::show(vm, s, waitType); } /*------------------------------------------------------------------------*/ void CantCast::show(XeenEngine *vm, int spellId, int componentNum) { CantCast *dlg = new CantCast(vm); dlg->execute(spellId, componentNum); delete dlg; } void CantCast::execute(int spellId, int componentNum) { EventsManager &events = *_vm->_events; Sound &sound = *_vm->_sound; Spells &spells = *_vm->_spells; Windows &windows = *_vm->_windows; Window &w = windows[6]; Mode oldMode = _vm->_mode; _vm->_mode = MODE_FF; sound.playFX(21); w.open(); w.writeString(Common::String::format(Res.NOT_ENOUGH_TO_CAST, Res.SPELL_CAST_COMPONENTS[componentNum - 1], spells._spellNames[spellId].c_str() )); w.update(); do { events.pollEventsAndWait(); } while (!_vm->shouldExit() && !events.isKeyMousePressed()); events.clearEvents(); w.close(); _vm->_mode = oldMode; } } // End of namespace Xeen
gpl-2.0
cidesa/roraima-comunal
lib/model/Tspararc.php
554
<?php /** * Subclass for representing a row from the 'tspararc'. * * * * @package Roraima * @subpackage lib.model * @author $Author: dmartinez $ <desarrollo@cidesa.com.ve> * @version SVN: $Id: Tspararc.php 34269 2009-10-26 21:21:50Z dmartinez $ * * @copyright Copyright 2007, Cide S.A. * @license http://opensource.org/licenses/gpl-2.0.php GPLv2 */ class Tspararc extends BaseTspararc { protected $archivo=""; public function getNomcue() { return Herramientas::getX('NUMCUE','Tsdefban','Nomcue',self::getNumcue()); } }
gpl-2.0
JohnDeved/citra
src/core/hle/service/soc_u.cpp
29123
// Copyright 2014 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #include <algorithm> #include <cstring> #include <unordered_map> #include <vector> #include "common/assert.h" #include "common/bit_field.h" #include "common/common_types.h" #include "common/logging/log.h" #include "common/scope_exit.h" #include "core/hle/kernel/session.h" #include "core/hle/result.h" #include "core/hle/service/soc_u.h" #include "core/memory.h" #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> // MinGW does not define several errno constants #ifndef _MSC_VER #define EBADMSG 104 #define ENODATA 120 #define ENOMSG 122 #define ENOSR 124 #define ENOSTR 125 #define ETIME 137 #define EIDRM 2001 #define ENOLINK 2002 #endif // _MSC_VER #else #include <cerrno> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <poll.h> #include <sys/socket.h> #include <unistd.h> #endif #ifdef _WIN32 #define WSAEAGAIN WSAEWOULDBLOCK #define WSAEMULTIHOP -1 // Invalid dummy value #define ERRNO(x) WSA##x #define GET_ERRNO WSAGetLastError() #define poll(x, y, z) WSAPoll(x, y, z); #else #define ERRNO(x) x #define GET_ERRNO errno #define closesocket(x) close(x) #endif static const s32 SOCKET_ERROR_VALUE = -1; //////////////////////////////////////////////////////////////////////////////////////////////////// // Namespace SOC_U namespace SOC_U { /// Holds the translation from system network errors to 3DS network errors static const std::unordered_map<int, int> error_map = {{ {E2BIG, 1}, {ERRNO(EACCES), 2}, {ERRNO(EADDRINUSE), 3}, {ERRNO(EADDRNOTAVAIL), 4}, {ERRNO(EAFNOSUPPORT), 5}, {ERRNO(EAGAIN), 6}, {ERRNO(EALREADY), 7}, {ERRNO(EBADF), 8}, {EBADMSG, 9}, {EBUSY, 10}, {ECANCELED, 11}, {ECHILD, 12}, {ERRNO(ECONNABORTED), 13}, {ERRNO(ECONNREFUSED), 14}, {ERRNO(ECONNRESET), 15}, {EDEADLK, 16}, {ERRNO(EDESTADDRREQ), 17}, {EDOM, 18}, {ERRNO(EDQUOT), 19}, {EEXIST, 20}, {ERRNO(EFAULT), 21}, {EFBIG, 22}, {ERRNO(EHOSTUNREACH), 23}, {EIDRM, 24}, {EILSEQ, 25}, {ERRNO(EINPROGRESS), 26}, {ERRNO(EINTR), 27}, {ERRNO(EINVAL), 28}, {EIO, 29}, {ERRNO(EISCONN), 30}, {EISDIR, 31}, {ERRNO(ELOOP), 32}, {ERRNO(EMFILE), 33}, {EMLINK, 34}, {ERRNO(EMSGSIZE), 35}, {ERRNO(EMULTIHOP), 36}, {ERRNO(ENAMETOOLONG), 37}, {ERRNO(ENETDOWN), 38}, {ERRNO(ENETRESET), 39}, {ERRNO(ENETUNREACH), 40}, {ENFILE, 41}, {ERRNO(ENOBUFS), 42}, #ifdef ENODATA {ENODATA, 43}, #endif {ENODEV, 44}, {ENOENT, 45}, {ENOEXEC, 46}, {ENOLCK, 47}, {ENOLINK, 48}, {ENOMEM, 49}, {ENOMSG, 50}, {ERRNO(ENOPROTOOPT), 51}, {ENOSPC, 52}, #ifdef ENOSR {ENOSR, 53}, #endif #ifdef ENOSTR {ENOSTR, 54}, #endif {ENOSYS, 55}, {ERRNO(ENOTCONN), 56}, {ENOTDIR, 57}, {ERRNO(ENOTEMPTY), 58}, {ERRNO(ENOTSOCK), 59}, {ENOTSUP, 60}, {ENOTTY, 61}, {ENXIO, 62}, {ERRNO(EOPNOTSUPP), 63}, {EOVERFLOW, 64}, {EPERM, 65}, {EPIPE, 66}, {EPROTO, 67}, {ERRNO(EPROTONOSUPPORT), 68}, {ERRNO(EPROTOTYPE), 69}, {ERANGE, 70}, {EROFS, 71}, {ESPIPE, 72}, {ESRCH, 73}, {ERRNO(ESTALE), 74}, #ifdef ETIME {ETIME, 75}, #endif {ERRNO(ETIMEDOUT), 76}, }}; /// Converts a network error from platform-specific to 3ds-specific static int TranslateError(int error) { auto found = error_map.find(error); if (found != error_map.end()) return -found->second; return error; } /// Holds the translation from system network socket options to 3DS network socket options /// Note: -1 = No effect/unavailable static const std::unordered_map<int, int> sockopt_map = {{ {0x0004, SO_REUSEADDR}, {0x0080, -1}, {0x0100, -1}, {0x1001, SO_SNDBUF}, {0x1002, SO_RCVBUF}, {0x1003, -1}, #ifdef _WIN32 /// Unsupported in WinSock2 {0x1004, -1}, #else {0x1004, SO_RCVLOWAT}, #endif {0x1008, SO_TYPE}, {0x1009, SO_ERROR}, }}; /// Converts a socket option from 3ds-specific to platform-specific static int TranslateSockOpt(int console_opt_name) { auto found = sockopt_map.find(console_opt_name); if (found != sockopt_map.end()) { return found->second; } return console_opt_name; } /// Holds information about a particular socket struct SocketHolder { u32 socket_fd; ///< The socket descriptor bool blocking; ///< Whether the socket is blocking or not, it is only read on Windows. }; /// Structure to represent the 3ds' pollfd structure, which is different than most implementations struct CTRPollFD { u32 fd; ///< Socket handle union Events { u32 hex; ///< The complete value formed by the flags BitField<0, 1, u32> pollin; BitField<1, 1, u32> pollpri; BitField<2, 1, u32> pollhup; BitField<3, 1, u32> pollerr; BitField<4, 1, u32> pollout; BitField<5, 1, u32> pollnval; Events& operator=(const Events& other) { hex = other.hex; return *this; } /// Translates the resulting events of a Poll operation from platform-specific to 3ds /// specific static Events TranslateTo3DS(u32 input_event) { Events ev = {}; if (input_event & POLLIN) ev.pollin.Assign(1); if (input_event & POLLPRI) ev.pollpri.Assign(1); if (input_event & POLLHUP) ev.pollhup.Assign(1); if (input_event & POLLERR) ev.pollerr.Assign(1); if (input_event & POLLOUT) ev.pollout.Assign(1); if (input_event & POLLNVAL) ev.pollnval.Assign(1); return ev; } /// Translates the resulting events of a Poll operation from 3ds specific to platform /// specific static u32 TranslateToPlatform(Events input_event) { u32 ret = 0; if (input_event.pollin) ret |= POLLIN; if (input_event.pollpri) ret |= POLLPRI; if (input_event.pollhup) ret |= POLLHUP; if (input_event.pollerr) ret |= POLLERR; if (input_event.pollout) ret |= POLLOUT; if (input_event.pollnval) ret |= POLLNVAL; return ret; } }; Events events; ///< Events to poll for (input) Events revents; ///< Events received (output) /// Converts a platform-specific pollfd to a 3ds specific structure static CTRPollFD FromPlatform(pollfd const& fd) { CTRPollFD result; result.events.hex = Events::TranslateTo3DS(fd.events).hex; result.revents.hex = Events::TranslateTo3DS(fd.revents).hex; result.fd = static_cast<u32>(fd.fd); return result; } /// Converts a 3ds specific pollfd to a platform-specific structure static pollfd ToPlatform(CTRPollFD const& fd) { pollfd result; result.events = Events::TranslateToPlatform(fd.events); result.revents = Events::TranslateToPlatform(fd.revents); result.fd = fd.fd; return result; } }; /// Union to represent the 3ds' sockaddr structure union CTRSockAddr { /// Structure to represent a raw sockaddr struct { u8 len; ///< The length of the entire structure, only the set fields count u8 sa_family; ///< The address family of the sockaddr u8 sa_data[0x1A]; ///< The extra data, this varies, depending on the address family } raw; /// Structure to represent the 3ds' sockaddr_in structure struct CTRSockAddrIn { u8 len; ///< The length of the entire structure u8 sin_family; ///< The address family of the sockaddr_in u16 sin_port; ///< The port associated with this sockaddr_in u32 sin_addr; ///< The actual address of the sockaddr_in } in; /// Convert a 3DS CTRSockAddr to a platform-specific sockaddr static sockaddr ToPlatform(CTRSockAddr const& ctr_addr) { sockaddr result; result.sa_family = ctr_addr.raw.sa_family; memset(result.sa_data, 0, sizeof(result.sa_data)); // We can not guarantee ABI compatibility between platforms so we copy the fields manually switch (result.sa_family) { case AF_INET: { sockaddr_in* result_in = reinterpret_cast<sockaddr_in*>(&result); result_in->sin_port = ctr_addr.in.sin_port; result_in->sin_addr.s_addr = ctr_addr.in.sin_addr; memset(result_in->sin_zero, 0, sizeof(result_in->sin_zero)); break; } default: ASSERT_MSG(false, "Unhandled address family (sa_family) in CTRSockAddr::ToPlatform"); break; } return result; } /// Convert a platform-specific sockaddr to a 3DS CTRSockAddr static CTRSockAddr FromPlatform(sockaddr const& addr) { CTRSockAddr result; result.raw.sa_family = static_cast<u8>(addr.sa_family); // We can not guarantee ABI compatibility between platforms so we copy the fields manually switch (result.raw.sa_family) { case AF_INET: { sockaddr_in const* addr_in = reinterpret_cast<sockaddr_in const*>(&addr); result.raw.len = sizeof(CTRSockAddrIn); result.in.sin_port = addr_in->sin_port; result.in.sin_addr = addr_in->sin_addr.s_addr; break; } default: ASSERT_MSG(false, "Unhandled address family (sa_family) in CTRSockAddr::ToPlatform"); break; } return result; } }; /// Holds info about the currently open sockets static std::unordered_map<u32, SocketHolder> open_sockets; /// Close all open sockets static void CleanupSockets() { for (auto sock : open_sockets) closesocket(sock.second.socket_fd); open_sockets.clear(); } static void Socket(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 domain = cmd_buffer[1]; // Address family u32 type = cmd_buffer[2]; u32 protocol = cmd_buffer[3]; // Only 0 is allowed according to 3dbrew, using 0 will let the OS decide which protocol to use if (protocol != 0) { cmd_buffer[1] = UnimplementedFunction(ErrorModule::SOC).raw; // TODO(Subv): Correct error code return; } if (domain != AF_INET) { cmd_buffer[1] = UnimplementedFunction(ErrorModule::SOC).raw; // TODO(Subv): Correct error code return; } if (type != SOCK_DGRAM && type != SOCK_STREAM) { cmd_buffer[1] = UnimplementedFunction(ErrorModule::SOC).raw; // TODO(Subv): Correct error code return; } u32 socket_handle = static_cast<u32>(::socket(domain, type, protocol)); if ((s32)socket_handle != SOCKET_ERROR_VALUE) open_sockets[socket_handle] = {socket_handle, true}; int result = 0; if ((s32)socket_handle == SOCKET_ERROR_VALUE) result = TranslateError(GET_ERRNO); cmd_buffer[0] = IPC::MakeHeader(2, 2, 0); cmd_buffer[1] = result; cmd_buffer[2] = socket_handle; } static void Bind(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 len = cmd_buffer[2]; // Virtual address of the sock_addr structure VAddr sock_addr_addr = cmd_buffer[6]; if (!Memory::IsValidVirtualAddress(sock_addr_addr)) { cmd_buffer[1] = -1; // TODO(Subv): Correct code return; } CTRSockAddr ctr_sock_addr; Memory::ReadBlock(sock_addr_addr, reinterpret_cast<u8*>(&ctr_sock_addr), sizeof(CTRSockAddr)); sockaddr sock_addr = CTRSockAddr::ToPlatform(ctr_sock_addr); int res = ::bind(socket_handle, &sock_addr, std::max<u32>(sizeof(sock_addr), len)); int result = 0; if (res != 0) result = TranslateError(GET_ERRNO); cmd_buffer[0] = IPC::MakeHeader(5, 2, 0); cmd_buffer[1] = result; cmd_buffer[2] = res; } static void Fcntl(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 ctr_cmd = cmd_buffer[2]; u32 ctr_arg = cmd_buffer[3]; int result = 0; u32 posix_ret = 0; // TODO: Check what hardware returns for F_SETFL (unspecified by POSIX) SCOPE_EXIT({ cmd_buffer[1] = result; cmd_buffer[2] = posix_ret; }); if (ctr_cmd == 3) { // F_GETFL #ifdef _WIN32 posix_ret = 0; auto iter = open_sockets.find(socket_handle); if (iter != open_sockets.end() && iter->second.blocking == false) posix_ret |= 4; // O_NONBLOCK #else int ret = ::fcntl(socket_handle, F_GETFL, 0); if (ret == SOCKET_ERROR_VALUE) { result = TranslateError(GET_ERRNO); posix_ret = -1; return; } posix_ret = 0; if (ret & O_NONBLOCK) posix_ret |= 4; // O_NONBLOCK #endif } else if (ctr_cmd == 4) { // F_SETFL #ifdef _WIN32 unsigned long tmp = (ctr_arg & 4 /* O_NONBLOCK */) ? 1 : 0; int ret = ioctlsocket(socket_handle, FIONBIO, &tmp); if (ret == SOCKET_ERROR_VALUE) { result = TranslateError(GET_ERRNO); posix_ret = -1; return; } auto iter = open_sockets.find(socket_handle); if (iter != open_sockets.end()) iter->second.blocking = (tmp == 0); #else int flags = ::fcntl(socket_handle, F_GETFL, 0); if (flags == SOCKET_ERROR_VALUE) { result = TranslateError(GET_ERRNO); posix_ret = -1; return; } flags &= ~O_NONBLOCK; if (ctr_arg & 4) // O_NONBLOCK flags |= O_NONBLOCK; int ret = ::fcntl(socket_handle, F_SETFL, flags); if (ret == SOCKET_ERROR_VALUE) { result = TranslateError(GET_ERRNO); posix_ret = -1; return; } #endif } else { LOG_ERROR(Service_SOC, "Unsupported command (%d) in fcntl call", ctr_cmd); result = TranslateError(EINVAL); // TODO: Find the correct error posix_ret = -1; return; } } static void Listen(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 backlog = cmd_buffer[2]; int ret = ::listen(socket_handle, backlog); int result = 0; if (ret != 0) result = TranslateError(GET_ERRNO); cmd_buffer[0] = IPC::MakeHeader(3, 2, 0); cmd_buffer[1] = result; cmd_buffer[2] = ret; } static void Accept(Service::Interface* self) { // TODO(Subv): Calling this function on a blocking socket will block the emu thread, // preventing graceful shutdown when closing the emulator, this can be fixed by always // performing nonblocking operations and spinlock until the data is available u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; socklen_t max_addr_len = static_cast<socklen_t>(cmd_buffer[2]); sockaddr addr; socklen_t addr_len = sizeof(addr); u32 ret = static_cast<u32>(::accept(socket_handle, &addr, &addr_len)); if ((s32)ret != SOCKET_ERROR_VALUE) open_sockets[ret] = {ret, true}; int result = 0; if ((s32)ret == SOCKET_ERROR_VALUE) { result = TranslateError(GET_ERRNO); } else { CTRSockAddr ctr_addr = CTRSockAddr::FromPlatform(addr); Memory::WriteBlock(cmd_buffer[0x104 >> 2], &ctr_addr, sizeof(ctr_addr)); } cmd_buffer[0] = IPC::MakeHeader(4, 2, 2); cmd_buffer[1] = result; cmd_buffer[2] = ret; cmd_buffer[3] = IPC::StaticBufferDesc(static_cast<u32>(max_addr_len), 0); } static void GetHostId(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); char name[128]; gethostname(name, sizeof(name)); addrinfo hints = {}; addrinfo* res; hints.ai_family = AF_INET; getaddrinfo(name, nullptr, &hints, &res); sockaddr_in* sock_addr = reinterpret_cast<sockaddr_in*>(res->ai_addr); in_addr* addr = &sock_addr->sin_addr; cmd_buffer[2] = addr->s_addr; cmd_buffer[1] = 0; freeaddrinfo(res); } static void Close(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; int ret = 0; open_sockets.erase(socket_handle); ret = closesocket(socket_handle); int result = 0; if (ret != 0) result = TranslateError(GET_ERRNO); cmd_buffer[2] = ret; cmd_buffer[1] = result; } static void SendTo(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 len = cmd_buffer[2]; u32 flags = cmd_buffer[3]; u32 addr_len = cmd_buffer[4]; VAddr input_buff_address = cmd_buffer[8]; if (!Memory::IsValidVirtualAddress(input_buff_address)) { cmd_buffer[1] = -1; // TODO(Subv): Find the right error code return; } // Memory address of the dest_addr structure VAddr dest_addr_addr = cmd_buffer[10]; if (!Memory::IsValidVirtualAddress(dest_addr_addr)) { cmd_buffer[1] = -1; // TODO(Subv): Find the right error code return; } std::vector<u8> input_buff(len); Memory::ReadBlock(input_buff_address, input_buff.data(), input_buff.size()); CTRSockAddr ctr_dest_addr; Memory::ReadBlock(dest_addr_addr, &ctr_dest_addr, sizeof(ctr_dest_addr)); int ret = -1; if (addr_len > 0) { sockaddr dest_addr = CTRSockAddr::ToPlatform(ctr_dest_addr); ret = ::sendto(socket_handle, reinterpret_cast<const char*>(input_buff.data()), len, flags, &dest_addr, sizeof(dest_addr)); } else { ret = ::sendto(socket_handle, reinterpret_cast<const char*>(input_buff.data()), len, flags, nullptr, 0); } int result = 0; if (ret == SOCKET_ERROR_VALUE) result = TranslateError(GET_ERRNO); cmd_buffer[2] = ret; cmd_buffer[1] = result; } static void RecvFrom(Service::Interface* self) { // TODO(Subv): Calling this function on a blocking socket will block the emu thread, // preventing graceful shutdown when closing the emulator, this can be fixed by always // performing nonblocking operations and spinlock until the data is available u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 len = cmd_buffer[2]; u32 flags = cmd_buffer[3]; socklen_t addr_len = static_cast<socklen_t>(cmd_buffer[4]); struct { u32 output_buffer_descriptor; u32 output_buffer_addr; u32 address_buffer_descriptor; u32 output_src_address_buffer; } buffer_parameters; std::memcpy(&buffer_parameters, &cmd_buffer[64], sizeof(buffer_parameters)); if (!Memory::IsValidVirtualAddress(buffer_parameters.output_buffer_addr)) { cmd_buffer[1] = -1; // TODO(Subv): Find the right error code return; } if (!Memory::IsValidVirtualAddress(buffer_parameters.output_src_address_buffer)) { cmd_buffer[1] = -1; // TODO(Subv): Find the right error code return; } std::vector<u8> output_buff(len); sockaddr src_addr; socklen_t src_addr_len = sizeof(src_addr); int ret = ::recvfrom(socket_handle, reinterpret_cast<char*>(output_buff.data()), len, flags, &src_addr, &src_addr_len); if (ret >= 0 && buffer_parameters.output_src_address_buffer != 0 && src_addr_len > 0) { CTRSockAddr ctr_src_addr = CTRSockAddr::FromPlatform(src_addr); Memory::WriteBlock(buffer_parameters.output_src_address_buffer, &ctr_src_addr, sizeof(ctr_src_addr)); } int result = 0; int total_received = ret; if (ret == SOCKET_ERROR_VALUE) { result = TranslateError(GET_ERRNO); total_received = 0; } else { // Write only the data we received to avoid overwriting parts of the buffer with zeros Memory::WriteBlock(buffer_parameters.output_buffer_addr, output_buff.data(), total_received); } cmd_buffer[1] = result; cmd_buffer[2] = ret; cmd_buffer[3] = total_received; } static void Poll(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 nfds = cmd_buffer[1]; int timeout = cmd_buffer[2]; VAddr input_fds_addr = cmd_buffer[6]; VAddr output_fds_addr = cmd_buffer[0x104 >> 2]; if (!Memory::IsValidVirtualAddress(input_fds_addr) || !Memory::IsValidVirtualAddress(output_fds_addr)) { cmd_buffer[1] = -1; // TODO(Subv): Find correct error code. return; } std::vector<CTRPollFD> ctr_fds(nfds); Memory::ReadBlock(input_fds_addr, ctr_fds.data(), nfds * sizeof(CTRPollFD)); // The 3ds_pollfd and the pollfd structures may be different (Windows/Linux have different // sizes) // so we have to copy the data std::vector<pollfd> platform_pollfd(nfds); std::transform(ctr_fds.begin(), ctr_fds.end(), platform_pollfd.begin(), CTRPollFD::ToPlatform); const int ret = ::poll(platform_pollfd.data(), nfds, timeout); // Now update the output pollfd structure std::transform(platform_pollfd.begin(), platform_pollfd.end(), ctr_fds.begin(), CTRPollFD::FromPlatform); Memory::WriteBlock(output_fds_addr, ctr_fds.data(), nfds * sizeof(CTRPollFD)); int result = 0; if (ret == SOCKET_ERROR_VALUE) result = TranslateError(GET_ERRNO); cmd_buffer[1] = result; cmd_buffer[2] = ret; } static void GetSockName(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; socklen_t ctr_len = cmd_buffer[2]; // Memory address of the ctr_dest_addr structure VAddr ctr_dest_addr_addr = cmd_buffer[0x104 >> 2]; sockaddr dest_addr; socklen_t dest_addr_len = sizeof(dest_addr); int ret = ::getsockname(socket_handle, &dest_addr, &dest_addr_len); if (ctr_dest_addr_addr != 0 && Memory::IsValidVirtualAddress(ctr_dest_addr_addr)) { CTRSockAddr ctr_dest_addr = CTRSockAddr::FromPlatform(dest_addr); Memory::WriteBlock(ctr_dest_addr_addr, &ctr_dest_addr, sizeof(ctr_dest_addr)); } else { cmd_buffer[1] = -1; // TODO(Subv): Verify error return; } int result = 0; if (ret != 0) result = TranslateError(GET_ERRNO); cmd_buffer[2] = ret; cmd_buffer[1] = result; } static void Shutdown(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; int how = cmd_buffer[2]; int ret = ::shutdown(socket_handle, how); int result = 0; if (ret != 0) result = TranslateError(GET_ERRNO); cmd_buffer[2] = ret; cmd_buffer[1] = result; } static void GetPeerName(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; socklen_t len = cmd_buffer[2]; // Memory address of the ctr_dest_addr structure VAddr ctr_dest_addr_addr = cmd_buffer[0x104 >> 2]; sockaddr dest_addr; socklen_t dest_addr_len = sizeof(dest_addr); int ret = ::getpeername(socket_handle, &dest_addr, &dest_addr_len); if (ctr_dest_addr_addr != 0 && Memory::IsValidVirtualAddress(ctr_dest_addr_addr)) { CTRSockAddr ctr_dest_addr = CTRSockAddr::FromPlatform(dest_addr); Memory::WriteBlock(ctr_dest_addr_addr, &ctr_dest_addr, sizeof(ctr_dest_addr)); } else { cmd_buffer[1] = -1; return; } int result = 0; if (ret != 0) result = TranslateError(GET_ERRNO); cmd_buffer[2] = ret; cmd_buffer[1] = result; } static void Connect(Service::Interface* self) { // TODO(Subv): Calling this function on a blocking socket will block the emu thread, // preventing graceful shutdown when closing the emulator, this can be fixed by always // performing nonblocking operations and spinlock until the data is available u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; socklen_t len = cmd_buffer[2]; // Memory address of the ctr_input_addr structure VAddr ctr_input_addr_addr = cmd_buffer[6]; if (!Memory::IsValidVirtualAddress(ctr_input_addr_addr)) { cmd_buffer[1] = -1; // TODO(Subv): Verify error return; } CTRSockAddr ctr_input_addr; Memory::ReadBlock(ctr_input_addr_addr, &ctr_input_addr, sizeof(ctr_input_addr)); sockaddr input_addr = CTRSockAddr::ToPlatform(ctr_input_addr); int ret = ::connect(socket_handle, &input_addr, sizeof(input_addr)); int result = 0; if (ret != 0) result = TranslateError(GET_ERRNO); cmd_buffer[0] = IPC::MakeHeader(6, 2, 0); cmd_buffer[1] = result; cmd_buffer[2] = ret; } static void InitializeSockets(Service::Interface* self) { // TODO(Subv): Implement #ifdef _WIN32 WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); #endif u32* cmd_buffer = Kernel::GetCommandBuffer(); cmd_buffer[0] = IPC::MakeHeader(1, 1, 0); cmd_buffer[1] = RESULT_SUCCESS.raw; } static void ShutdownSockets(Service::Interface* self) { // TODO(Subv): Implement CleanupSockets(); #ifdef _WIN32 WSACleanup(); #endif u32* cmd_buffer = Kernel::GetCommandBuffer(); cmd_buffer[1] = 0; } static void GetSockOpt(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; int optname = TranslateSockOpt(cmd_buffer[3]); socklen_t optlen = (socklen_t)cmd_buffer[4]; int ret = -1; int err = 0; if (optname < 0) { #ifdef _WIN32 err = WSAEINVAL; #else err = EINVAL; #endif } else { // 0x100 = static buffer offset (bytes) // + 0x4 = 2nd pointer (u32) position // >> 2 = convert to u32 offset instead of byte offset (cmd_buffer = u32*) char* optval = reinterpret_cast<char*>(Memory::GetPointer(cmd_buffer[0x104 >> 2])); ret = ::getsockopt(socket_handle, level, optname, optval, &optlen); err = 0; if (ret == SOCKET_ERROR_VALUE) { err = TranslateError(GET_ERRNO); } } cmd_buffer[0] = IPC::MakeHeader(0x11, 4, 2); cmd_buffer[1] = ret; cmd_buffer[2] = err; cmd_buffer[3] = optlen; } static void SetSockOpt(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; int optname = TranslateSockOpt(cmd_buffer[3]); int ret = -1; int err = 0; if (optname < 0) { #ifdef _WIN32 err = WSAEINVAL; #else err = EINVAL; #endif } else { socklen_t optlen = static_cast<socklen_t>(cmd_buffer[4]); const char* optval = reinterpret_cast<const char*>(Memory::GetPointer(cmd_buffer[8])); ret = static_cast<u32>(::setsockopt(socket_handle, level, optname, optval, optlen)); err = 0; if (ret == SOCKET_ERROR_VALUE) { err = TranslateError(GET_ERRNO); } } cmd_buffer[0] = IPC::MakeHeader(0x12, 4, 4); cmd_buffer[1] = ret; cmd_buffer[2] = err; } const Interface::FunctionInfo FunctionTable[] = { {0x00010044, InitializeSockets, "InitializeSockets"}, {0x000200C2, Socket, "Socket"}, {0x00030082, Listen, "Listen"}, {0x00040082, Accept, "Accept"}, {0x00050084, Bind, "Bind"}, {0x00060084, Connect, "Connect"}, {0x00070104, nullptr, "recvfrom_other"}, {0x00080102, RecvFrom, "RecvFrom"}, {0x00090106, nullptr, "sendto_other"}, {0x000A0106, SendTo, "SendTo"}, {0x000B0042, Close, "Close"}, {0x000C0082, Shutdown, "Shutdown"}, {0x000D0082, nullptr, "GetHostByName"}, {0x000E00C2, nullptr, "GetHostByAddr"}, {0x000F0106, nullptr, "GetAddrInfo"}, {0x00100102, nullptr, "GetNameInfo"}, {0x00110102, GetSockOpt, "GetSockOpt"}, {0x00120104, SetSockOpt, "SetSockOpt"}, {0x001300C2, Fcntl, "Fcntl"}, {0x00140084, Poll, "Poll"}, {0x00150042, nullptr, "SockAtMark"}, {0x00160000, GetHostId, "GetHostId"}, {0x00170082, GetSockName, "GetSockName"}, {0x00180082, GetPeerName, "GetPeerName"}, {0x00190000, ShutdownSockets, "ShutdownSockets"}, {0x001A00C0, nullptr, "GetNetworkOpt"}, {0x001B0040, nullptr, "ICMPSocket"}, {0x001C0104, nullptr, "ICMPPing"}, {0x001D0040, nullptr, "ICMPCancel"}, {0x001E0040, nullptr, "ICMPClose"}, {0x001F0040, nullptr, "GetResolverInfo"}, {0x00210002, nullptr, "CloseSockets"}, {0x00230040, nullptr, "AddGlobalSocket"}, }; //////////////////////////////////////////////////////////////////////////////////////////////////// // Interface class Interface::Interface() { Register(FunctionTable); } Interface::~Interface() { CleanupSockets(); #ifdef _WIN32 WSACleanup(); #endif } } // namespace
gpl-2.0
sobomax/virtualbox_64bit_edd
src/VBox/Frontends/VirtualBox/src/extensions/QIWidgetValidator.cpp
4888
/* $Id: QIWidgetValidator.cpp $ */ /** @file * VBox Qt GUI - VirtualBox Qt extensions: QIWidgetValidator class implementation. */ /* * Copyright (C) 2006-2013 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifdef VBOX_WITH_PRECOMPILED_HEADERS # include <precomp.h> #else /* !VBOX_WITH_PRECOMPILED_HEADERS */ /* GUI includes: */ # include "QIWidgetValidator.h" # include "UISettingsPage.h" #endif /* !VBOX_WITH_PRECOMPILED_HEADERS */ QObjectValidator::QObjectValidator(QValidator *pValidator, QObject *pParent /* = 0 */) : QObject(pParent) , m_pValidator(pValidator) , m_state(QValidator::Invalid) { /* Prepare: */ prepare(); } void QObjectValidator::sltValidate(QString strInput /* = QString() */) { /* Make sure validator assigned: */ AssertPtrReturnVoid(m_pValidator); /* Validate: */ int iPosition = 0; const QValidator::State state = m_pValidator->validate(strInput, iPosition); /* If validity state changed: */ if (m_state != state) { /* Update last validity state: */ m_state = state; /* Notifies listener(s) about validity change: */ emit sigValidityChange(m_state); } } void QObjectValidator::prepare() { /* Make sure validator assigned: */ AssertPtrReturnVoid(m_pValidator); /* Register validator as child: */ m_pValidator->setParent(this); /* Validate: */ sltValidate(); } QObjectValidatorGroup::QObjectValidatorGroup(QObject *pParent) : QObject(pParent) , m_fResult(false) { } void QObjectValidatorGroup::addObjectValidator(QObjectValidator *pObjectValidator) { /* Make sure object-validator passed: */ AssertPtrReturnVoid(pObjectValidator); /* Register object-validator as child: */ pObjectValidator->setParent(this); /* Insert object-validator to internal map: */ m_group.insert(pObjectValidator, toResult(pObjectValidator->state())); /* Attach object-validator to group: */ connect(pObjectValidator, SIGNAL(sigValidityChange(QValidator::State)), this, SLOT(sltValidate(QValidator::State))); } void QObjectValidatorGroup::sltValidate(QValidator::State state) { /* Determine sender object-validator: */ QObjectValidator *pObjectValidatorSender = qobject_cast<QObjectValidator*>(sender()); /* Make sure that is one of our senders: */ AssertReturnVoid(pObjectValidatorSender && m_group.contains(pObjectValidatorSender)); /* Update internal map: */ m_group[pObjectValidatorSender] = toResult(state); /* Enumerate all the registered object-validators: */ bool fResult = true; foreach (QObjectValidator *pObjectValidator, m_group.keys()) if (!toResult(pObjectValidator->state())) { fResult = false; break; } /* If validity state changed: */ if (m_fResult != fResult) { /* Update last validity state: */ m_fResult = fResult; /* Notifies listener(s) about validity change: */ emit sigValidityChange(m_fResult); } } /* static */ bool QObjectValidatorGroup::toResult(QValidator::State state) { return state == QValidator::Acceptable; } UIPageValidator::UIPageValidator(QObject *pParent, UISettingsPage *pPage) : QObject(pParent) , m_pPage(pPage) , m_fIsValid(true) { } QPixmap UIPageValidator::warningPixmap() const { return m_pPage->warningPixmap(); } QString UIPageValidator::internalName() const { return m_pPage->internalName(); } void UIPageValidator::setLastMessage(const QString &strLastMessage) { /* Remember new message: */ m_strLastMessage = strLastMessage; /* Should we show corresponding warning icon? */ if (m_strLastMessage.isEmpty()) emit sigHideWarningIcon(); else emit sigShowWarningIcon(); } void UIPageValidator::revalidate() { /* Notify listener(s) about validity change: */ emit sigValidityChanged(this); } QValidator::State QIULongValidator::validate (QString &aInput, int &aPos) const { Q_UNUSED (aPos); QString stripped = aInput.trimmed(); if (stripped.isEmpty() || stripped.toUpper() == QString ("0x").toUpper()) return Intermediate; bool ok; ulong entered = aInput.toULong (&ok, 0); if (!ok) return Invalid; if (entered >= mBottom && entered <= mTop) return Acceptable; return (entered > mTop ) ? Invalid : Intermediate; }
gpl-2.0
octoray/AJAX_PFI
testmon/vendors/ckeditor/plugins/a11yhelp/dialogs/lang/km.js
5194
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp", "km", {title: "Accessibility Instructions", contents: "មាតិកា​ជំនួយ។ ដើម្បី​បិទ​ផ្ទាំង​នេះ សូម​ចុច ESC ។", legend: [ {name: "ទូទៅ", items: [ {name: "របារ​ឧបករណ៍​កម្មវិធី​និពន្ធ", legend: "Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT-TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button."}, {name: "ផ្ទាំង​កម្មវិធីនិពន្ធ", legend: "Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. Then move to next tab with TAB OR RIGTH ARROW. Move to previous tab with SHIFT + TAB or LEFT ARROW. Press SPACE or ENTER to select the tab page."}, {name: "Editor Context Menu", legend: "Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."}, {name: "Editor List Box", legend: "Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT + TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."}, {name: "Editor Element Path Bar", legend: "Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."} ]}, {name: "ពាក្យបញ្ជា", items: [ {name: "ការ​បញ្ជា​មិនធ្វើវិញ", legend: "ចុច ${undo}"}, {name: "ការបញ្ជា​ធ្វើវិញ", legend: "ចុច ${redo}"}, {name: "ការបញ្ជា​អក្សរ​ដិត", legend: "ចុច ${bold}"}, {name: "ការបញ្ជា​អក្សរ​ទ្រេត", legend: "ចុច ${italic}"}, {name: "ពាក្យបញ្ជា​បន្ទាត់​ពីក្រោម", legend: "ចុច ${underline}"}, {name: "ពាក្យបញ្ជា​តំណ", legend: "ចុច ${link}"}, {name: " Toolbar Collapse command", legend: "Press ${toolbarCollapse}"}, {name: " Access previous focus space command", legend: "Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."}, {name: " Access next focus space command", legend: "Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."}, {name: "ជំនួយ​ពី​ភាព​ងាយស្រួល", legend: "ជួយ ${a11yHelp}"} ]} ], backspace: "Backspace", tab: "Tab", enter: "Enter", shift: "Shift", ctrl: "Ctrl", alt: "Alt", pause: "Pause", capslock: "Caps Lock", escape: "Escape", pageUp: "ទំព័រ​លើ", pageDown: "ទំព័រ​ក្រោម", end: "ចុង", home: "ផ្ទះ", leftArrow: "ព្រួញ​ឆ្វេង", upArrow: "ព្រួញ​លើ", rightArrow: "ព្រួញ​ស្ដាំ", downArrow: "ព្រួញ​ក្រោម", insert: "បញ្ចូល", "delete": "លុប", leftWindowKey: "Left Windows key", rightWindowKey: "Right Windows key", selectKey: "ជ្រើស​គ្រាប់​ចុច", numpad0: "Numpad 0", numpad1: "Numpad 1", numpad2: "Numpad 2", numpad3: "Numpad 3", numpad4: "Numpad 4", numpad5: "Numpad 5", numpad6: "Numpad 6", numpad7: "Numpad 7", numpad8: "Numpad 8", numpad9: "Numpad 9", multiply: "គុណ", add: "បន្ថែម", subtract: "ដក", decimalPoint: "Decimal Point", divide: "ចែក", f1: "F1", f2: "F2", f3: "F3", f4: "F4", f5: "F5", f6: "F6", f7: "F7", f8: "F8", f9: "F9", f10: "F10", f11: "F11", f12: "F12", numLock: "Num Lock", scrollLock: "បិទ​រំកិល", semiColon: "ចុច​ក្បៀស", equalSign: "សញ្ញា​អឺរ៉ូ", comma: "ក្បៀស", dash: "Dash", period: "ចុច", forwardSlash: "Forward Slash", graveAccent: "Grave Accent", openBracket: "តង្កៀប​បើក", backSlash: "Backslash", closeBracket: "តង្កៀប​បិទ", singleQuote: "បន្តក់​មួយ"});
gpl-2.0
janewang0913/sbu
wp-content/themes/sbu-theme/inc/jetpack.php
758
<?php /** * Jetpack Compatibility File. * * @link https://jetpack.me/ * * @package Bizlight */ /** * Add theme support for Infinite Scroll. * See: https://jetpack.me/support/infinite-scroll/ */ function bizlight_jetpack_setup() { add_theme_support( 'infinite-scroll', array( 'container' => 'main', 'render' => 'bizlight_infinite_scroll_render', 'footer' => 'page', ) ); } // end function bizlight_jetpack_setup add_action( 'after_setup_theme', 'bizlight_jetpack_setup' ); /** * Custom render function for Infinite Scroll. */ function bizlight_infinite_scroll_render() { while ( have_posts() ) { the_post(); get_template_part( 'template-parts/content', get_post_format() ); } } // end function bizlight_infinite_scroll_render
gpl-2.0
sirAndros/IdeaMarket
plugins/vmpayment/klarna/klarna.php
68616
<?php defined ('_JEXEC') or die(); /** * @version $Id: klarna.php 6541 2012-10-15 14:48:35Z alatak $ * * @author Valérie Isaksen * @package VirtueMart * @link http://www.virtuemart.net * @copyright Copyright (C) 2012 iStraxx - All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. */ if (!class_exists ('vmPSPlugin')) { require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'); } if (JVM_VERSION === 2) { require (JPATH_ROOT . DS . 'plugins' . DS . 'vmpayment' . DS . 'klarna' . DS . 'klarna' . DS . 'helpers' . DS . 'define.php'); } else { require (JPATH_ROOT . DS . 'plugins' . DS . 'vmpayment' . DS . 'klarna' . DS . 'helpers' . DS . 'define.php'); } if (!class_exists ('Klarna')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'klarna.php'); } if (!class_exists ('klarna_virtuemart')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarna_virtuemart.php'); } if (!class_exists ('PCStorage')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'pclasses' . DS . 'storage.intf.php'); } if (!class_exists ('KlarnaConfig')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'klarnaconfig.php'); } if (!class_exists ('KlarnaPClass')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'klarnapclass.php'); } if (!class_exists ('KlarnaCalc')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'klarnacalc.php'); } if (!class_exists ('KlarnaHandler')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnahandler.php'); } require_once (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'transport' . DS . 'xmlrpc-3.0.0.beta' . DS . 'lib' . DS . 'xmlrpc.inc'); require_once (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'transport' . DS . 'xmlrpc-3.0.0.beta' . DS . 'lib' . DS . 'xmlrpc_wrappers.inc'); if (is_file (VMKLARNA_CONFIG_FILE)) { require_once (VMKLARNA_CONFIG_FILE); } class plgVmPaymentKlarna extends vmPSPlugin { function __construct (& $subject, $config) { parent::__construct ($subject, $config); $this->_loggable = TRUE; $this->tableFields = array_keys ($this->getTableSQLFields ()); $this->_tablepkey = 'id'; $this->_tableId = 'id'; $varsToPush = $this->getVarsToPush (); $this->setConfigParameterable ($this->_configTableFieldName, $varsToPush); $jlang = JFactory::getLanguage (); $jlang->load ('plg_vmpayment_klarna', JPATH_ADMINISTRATOR, 'en-GB', TRUE); $jlang->load ('plg_vmpayment_klarna', JPATH_ADMINISTRATOR, $jlang->getDefault (), TRUE); $jlang->load ('plg_vmpayment_klarna', JPATH_ADMINISTRATOR, NULL, TRUE); } /** * @return string */ public function getVmPluginCreateTableSQL () { return $this->createTableSQL ('Payment Klarna Table'); } /** * @return array */ function getTableSQLFields () { $SQLfields = array( 'id' => 'int(11) UNSIGNED NOT NULL AUTO_INCREMENT', 'virtuemart_order_id' => 'int(1) UNSIGNED', 'order_number' => ' char(64)', 'virtuemart_paymentmethod_id' => 'mediumint(1) UNSIGNED', 'payment_name' => 'varchar(5000)', 'payment_order_total' => 'decimal(15,5) NOT NULL DEFAULT \'0.00000\'', 'payment_fee' => 'decimal(10,2)', 'tax_id' => 'smallint(1)', 'klarna_eid' => 'int(10)', 'klarna_status_code' => 'tinyint(4)', 'klarna_status_text' => 'varchar(255)', 'klarna_invoice_no' => 'varchar(255)', 'klarna_log' => 'varchar(255)', 'klarna_pclass' => 'int(1)', 'klarna_pdf_invoice' => 'varchar(512)', ); return $SQLfields; } /** * @param $name * @param $id * @param $data * @return bool */ function plgVmDeclarePluginParamsPayment ($name, $id, &$data) { return $this->declarePluginParams ('payment', $name, $id, $data); } /** * @param $name * @param $id * @param $table * @return bool */ function plgVmSetOnTablePluginParamsPayment ($name, $id, &$table) { return $this->setOnTablePluginParams ($name, $id, $table); } /** * @param $product * @param $productDisplay * @return bool */ function plgVmOnProductDisplayPayment ($product, &$productDisplay) { $vendorId = 1; if ($this->getPluginMethods ($vendorId) === 0) { return FALSE; } if (!class_exists ('klarna_productPrice')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarna_productprice.php'); } if (!class_exists ('VirtueMartCart')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); } $cart = VirtueMartCart::getCart (); foreach ($this->methods as $method) { $type = NULL; $cData = KlarnaHandler::getcData ($method, $this->getCartAddress ($cart, $type, FALSE)); if ($cData['active'] and in_array ('part', $cData['payments_activated'])) { //if (!empty($product->prices)) { // no price is set if (!empty($product->prices['salesPrice'])) { $productPrice = new klarna_productPrice($cData); if ($productViewData = $productPrice->showProductPrice ($product, $cart)) { $productDisplayHtml = $this->renderByLayout ('productprice_layout', $productViewData, $method->payment_element, 'payment'); $productDisplay[] = $productDisplayHtml; } } } } return TRUE; } /* * */ /** * @param $cart * @param $countryCode * @param $countryId * @param string $fld */ function _getCountryCode ($cart = NULL, &$countryCode, &$countryId, $fld = 'country_3_code') { if ($cart == '') { if (!class_exists ('VirtueMartCart')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); } $cart = VirtueMartCart::getCart (); } $type = NULL; $address = $this->getCartAddress ($cart, $type, FALSE); if (JRequest::getVar ('klarna_country_2_code') == 'se') { $countryId = ShopFunctions::getCountryIDByName ('se'); $countryCode = shopFunctions::getCountryByID ($countryId, $fld); } elseif (!isset($address['virtuemart_country_id']) or empty($address['virtuemart_country_id'])) { $countryCode = KlarnaHandler::getVendorCountry ($fld); $countryId = ShopFunctions::getCountryIDByName ($countryCode); } else { $countryId = $address['virtuemart_country_id']; $countryCode = shopFunctions::getCountryByID ($address['virtuemart_country_id'], $fld); } } /** * @param $cart * @param $type * @param bool $STsameAsBT * @return mixed */ function getCartAddress ($cart, &$type, $STsameAsBT = TRUE) { if (VMKLARNA_SHIPTO_SAME_AS_BILLTO) { $st = $cart->BT; $type = 'BT'; if ($STsameAsBT and $cart->ST and !$cart->STsameAsBT) { vmInfo (JText::_ ('VMPAYMENT_KLARNA_SHIPTO_SAME_AS_BILLTO')); $cart->STsameAsBT = 1; $cart->setCartIntoSession (); } } elseif ($cart->BT == 0 or empty($cart->BT)) { $st = $cart->BT; $type = 'BT'; } else { $st = $cart->ST; $type = 'ST'; } return $st; } /** * @param VirtueMartCart $cart * @param string $fld * @return null */ function _getCartAddressCountryId (VirtueMartCart $cart, $fld = 'country_3_code') { $type = ""; $address = $this->getCartAddress ($cart, $type, FALSE); if (!isset($address['virtuemart_country_id'])) { return NULL; } return $address['virtuemart_country_id']; } /** * @param $virtuemart_order_id * @param string $fld * @return string */ function getCountryCodeByOrderId ($virtuemart_order_id, $fld = 'country_3_code') { $db = JFactory::getDBO (); $q = 'SELECT `virtuemart_country_id`, `address_type` FROM #__virtuemart_order_userinfos WHERE virtuemart_order_id=' . $virtuemart_order_id; $db->setQuery ($q); $results = $db->loadObjectList (); if (count ($results) == 1) { $virtuemart_country_id = $results[0]->virtuemart_country_id; } else { foreach ($results as $result) { if ($result->address_type == 'ST') { $virtuemart_country_id = $result->virtuemart_country_id; break; } } } return shopFunctions::getCountryByID ($virtuemart_country_id, $fld); } /** * plgVmDisplayListFEPayment * This event is fired to display the plugin methods in the cart (edit shipment/payment) for example * * @param object $cart Cart object * @param integer $selected ID of the method selected * @return boolean True on success, false on failures, null when this plugin was not selected. * On errors, JError::raiseWarning (or JError::raiseError) must be used to set a message. * * @author Valerie Isaksen */ public function plgVmDisplayListFEPayment (VirtueMartCart $cart, $selected = 0, &$htmlIn) { $html = $this->displayListFEPayment ($cart, $selected); if (!empty($html)) { $htmlIn[] = $html; } } /** * @param VirtueMartCart $cart VirtueMartCart * @param $selected * @return array|bool */ protected function displayListFEPayment (VirtueMartCart $cart, $selected) { if (!class_exists ('Klarna_payments')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarna_payments.php'); } if ($this->getPluginMethods ($cart->vendorId) === 0) { if (empty($this->_name)) { $app = JFactory::getApplication (); $app->enqueueMessage (JText::_ ('COM_VIRTUEMART_CART_NO_' . strtoupper ($this->_psType))); return FALSE; } else { return FALSE; } } $html = array(); foreach ($this->methods as $method) { $temp = $this->getListFEPayment ($cart, $method); if (!empty($temp)) { $html[] = $temp; } } if (!empty($html)) { $this->loadScriptAndCss (); } return $html; } /** * @param VirtueMartCart $cart * @param $method * @return null|string */ protected function getListFEPayment (VirtueMartCart $cart, $method) { $cart_currency_code = ShopFunctions::getCurrencyByID ($cart->pricesCurrency, 'currency_code_3'); $country_code = NULL; $countryId = 0; $this->_getCountryCode ($cart, $country_code, $countryId); if (!($cData = $this->checkCountryCondition ($method, $country_code, $cart))) { return NULL; } try { $pclasses = KlarnaHandler::getPClasses (NULL, KlarnaHandler::getKlarnaMode ($method, $cData['country_code_3']), $cData); } catch (Exception $e) { vmError ($e->getMessage (), $e->getMessage ()); return NULL; } $specCamp = 0; $partPay = 0; $this->getNbPClasses ($pclasses, $specCamp, $partPay); $sessionKlarnaData = $this->getKlarnaSessionData (); $klarna_paymentmethod = ""; if (isset($sessionKlarnaData->klarna_paymentmethod)) { $klarna_paymentmethod = $sessionKlarnaData->klarna_paymentmethod; } $html = ''; $checked = 'checked="checked"'; $payments = new klarna_payments($cData, KlarnaHandler::getShipToAddress ($cart)); if (in_array ('invoice', $cData['payments_activated'])) { $payment_params = $payments->get_payment_params ($method, 'invoice', $cart); $payment_form = $this->renderByLayout ('payment_form', array('payment_params' => $payment_params, 'payment_currency_info' => $payment_params['payment_currency_info'],), 'klarna', 'payment'); $selected = ($klarna_paymentmethod == 'klarna_invoice' AND $method->virtuemart_paymentmethod_id == $cart->virtuemart_paymentmethod_id) ? $checked : ""; $html .= $this->renderByLayout ('displaypayment', array( 'stype' => 'invoice', 'id' => $payment_params['id'], 'module' => $payment_params['module'], 'klarna_form' => $payment_form, 'virtuemart_paymentmethod_id' => $method->virtuemart_paymentmethod_id, 'klarna_paymentmethod' => $klarna_paymentmethod, 'selected' => $selected )); } if (in_array ('part', $cData['payments_activated'])) { if (strtolower ($country_code) == 'nld') { // Since 12/09/12: merchants can sell goods with Klarna Invoice up to thousands of euros. So the price check has been moved here if (!KlarnaHandler::checkPartNLpriceCondition ($cart)) { // We can't show our payment options for Dutch customers // if price exceeds 250 euro. Will be replaced with ILT in // the future. $partPay = 0; } } if ($partPay > 0) { if ($payment_params = $payments->get_payment_params ($method, 'part', $cart, $cData['virtuemart_currency_id'], $cData['vendor_currency'])) { $payment_form = $this->renderByLayout ('payment_form', array('payment_params' => $payment_params, 'payment_currency_info' => $payment_params['payment_currency_info'],), 'klarna', 'payment'); $selected = ($klarna_paymentmethod == 'klarna_part' AND $method->virtuemart_paymentmethod_id == $cart->virtuemart_paymentmethod_id) ? $checked : ""; $html .= $this->renderByLayout ('displaypayment', array( 'stype' => 'part', 'id' => $payment_params['id'], 'module' => $payment_params['module'], 'klarna_form' => $payment_form, 'virtuemart_paymentmethod_id' => $method->virtuemart_paymentmethod_id, 'klarna_paymentmethod' => $klarna_paymentmethod, 'selected' => $selected )); } } } // not tested yet /* if ( $specCamp > 0) { if ($payment_params = $payments->get_payment_params ($method, 'spec', $cart, $cData['virtuemart_currency_id'])) { $payment_form = $this->renderByLayout ('payment_form', array('payment_params' => $payment_params, 'payment_currency_info' => $payment_params['payment_currency_info'],), 'klarna', 'payment'); $selected = ($klarna_paymentmethod == 'klarna_spec' AND $method->virtuemart_paymentmethod_id == $cart->virtuemart_paymentmethod_id) ? $checked : ""; $html .= $this->renderByLayout ('displaypayment', array( 'stype' => 'spec', 'id' => $payment_params['id'], 'module' => $payment_params['module'], 'klarna_form' => $payment_form, 'virtuemart_paymentmethod_id' => $method->virtuemart_paymentmethod_id, 'klarna_paymentmethod' => $klarna_paymentmethod, 'selected' => $selected )); } } */ return $html; } /** * Count the number of Payment Classes: Partial Payments, and Special campaigns * * @param $pClasses * @param $specCamp * @param $partPay */ function getNbPClasses ($pClasses, &$specCamp, &$partPay) { $specCamp = 0; $partPay = 0; foreach ($pClasses as $pClass) { if ($pClass->getType () == KlarnaPClass::SPECIAL) { $specCamp += 1; } if ($pClass->getType () == KlarnaPClass::CAMPAIGN || $pClass->getType () == KlarnaPClass::ACCOUNT || $pClass->getType () == KlarnaPClass::FIXED || $pClass->getType () == KlarnaPClass::DELAY ) { $partPay += 1; } } } /** * @return mixed|null */ function getKlarnaSessionData () { $session = JFactory::getSession (); $sessionKlarna = $session->get ('Klarna', 0, 'vm'); if ($sessionKlarna) { $sessionKlarnaData = unserialize ($sessionKlarna); return $sessionKlarnaData; } return NULL; } /** * @param $method * @param $country_code * @param $cart * @return array|bool|null */ function checkCountryCondition ($method, $country_code, $cart) { if (!class_exists ('CurrencyDisplay')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'); } $active_country = "klarna_active_" . strtolower ($country_code); if (!isset($method->$active_country) or !$method->$active_country) { return FALSE; } if (empty($country_code)) { $msg = JText::_ ('VMPAYMENT_KLARNA_GET_SWEDISH_ADDRESS'); $country_code = "swe"; vmWarn ($msg); //return false; } /* if (strtolower ($country_code) == 'nld') { if(! KlarnaHandler::checkPartNLpriceCondition ($cart)) { // We can't show our payment options for Dutch customers // if price exceeds 250 euro. Will be replaced with ILT in // the future. return FALSE; } } */ // Get the country settings if (!class_exists ('KlarnaHandler')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnahandler.php'); } $cData = KlarnaHandler::getCountryData ($method, $country_code); if ($cData['eid'] == '' || $cData['eid'] == 0) { return FALSE; } return $cData; } /** * @param $cart * @param $order * @return bool|null */ function plgVmConfirmedOrder ($cart, $order) { if (!($method = $this->getVmPluginMethod ($order['details']['BT']->virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement ($method->payment_element)) { return FALSE; } if (!class_exists ('VirtueMartModelOrders')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php'); } $sessionKlarnaData = $this->getKlarnaSessionData (); try { $result = KlarnaHandler::addTransaction ($method, $order, $sessionKlarnaData->KLARNA_DATA['pclass']); } catch (Exception $e) { $log = $e->getMessage (); vmError ($e->getMessage () . ' #' . $e->getCode (), $e->getMessage () . ' #' . $e->getCode ()); return; //KlarnaHandler::redirectPaymentMethod('error', $e->getMessage() . ' #' . $e->getCode()); } //vmdebug('addTransaction result', $result); // Delete all Klarna data //unset($sessionKlarnaData->KLARNA_DATA, $_SESSION['SSN_ADDR']); $shipTo = KlarnaHandler::getShipToAddress ($cart); $modelOrder = VmModel::getModel ('orders'); if ($result['status_code'] == KlarnaFlags::DENIED) { $order['customer_notified'] = 0; $order['order_status'] = $method->status_denied; $order['comments'] = JText::sprintf ('VMPAYMENT_KLARNA_PAYMENT_KLARNA_STATUS_DENIED'); if ($method->delete_order) { $order['comments'] .= "<br />" . $result['status_text']; } $modelOrder->updateStatusForOneOrder ($order['details']['BT']->virtuemart_order_id, $order, TRUE); vmdebug ('addTransaction remove order?', $method->delete_order); if ($method->delete_order) { $modelOrder->remove (array('virtuemart_order_id' => $order['details']['BT']->virtuemart_order_id)); } else { $dbValues['order_number'] = $order['details']['BT']->order_number; $dbValues['payment_name'] = $this->renderKlarnaPluginName ($method, $order['details']['BT']->virtuemart_country_id, $shipTo, $order['details']['BT']->order_total, $order['order_currency']); $dbValues['virtuemart_paymentmethod_id'] = $order['details']['BT']->virtuemart_paymentmethod_id; $dbValues['order_payment'] = $order['details']['BT']->order_payment; $dbValues['klarna_pclass'] = $sessionKlarnaData->KLARNA_DATA['PCLASS']; $dbValues['klarna_log'] = ''; $dbValues['klarna_status_code'] = $result['status_code']; $dbValues['klarna_status_text'] = $result['status_text']; $this->storePSPluginInternalData ($dbValues); } $app = JFactory::getApplication (); $app->enqueueMessage ($result['status_text']); $app->redirect (JRoute::_ ('index.php?option=com_virtuemart&view=cart&task=editpayment')); } else { $invoiceno = $result[1]; if ($invoiceno && is_numeric ($invoiceno)) { //Get address id used for this order. //$country = $sessionKlarnaData->KLARNA_DATA['country']; // $lang = KlarnaHandler::getLanguageForCountry($method, KlarnaHandler::convertToThreeLetterCode($country)); // $d['order_payment_name'] = $kLang->fetch('MODULE_INVOICE_TEXT_TITLE', $lang); // Add a note in the log $log = Jtext::sprintf ('VMPAYMENT_KLARNA_INVOICE_CREATED_SUCCESSFULLY', $invoiceno); // Prepare data that should be stored in the database $dbValues['order_number'] = $order['details']['BT']->order_number; $dbValues['payment_name'] = $this->renderKlarnaPluginName ($method, $order['details']['BT']->virtuemart_country_id, $shipTo, $order['details']['BT']->order_total, $order['details']['BT']->order_currency); $dbValues['virtuemart_paymentmethod_id'] = $order['details']['BT']->virtuemart_paymentmethod_id; $dbValues['order_payment'] = $order['details']['BT']->order_payment; $dbValues['order_payment_tax'] = $order['details']['BT']->order_payment_tax; $dbValues['klarna_pclass'] = $sessionKlarnaData->KLARNA_DATA['pclass']; $dbValues['klarna_invoice_no'] = $invoiceno; $dbValues['klarna_log'] = $log; $dbValues['klarna_eid'] = $result['eid']; $dbValues['klarna_status_code'] = $result['status_code']; $dbValues['klarna_status_text'] = $result['status_text']; $this->storePSPluginInternalData ($dbValues); /* * Klarna's order status * Integer - 1,2 or 3. * 1 = OK: KlarnaFlags::ACCEPTED * 2 = Pending: KlarnaFlags::PENDING * 3 = Denied: KlarnaFlags::DENIED */ if ($result['status_code'] == KlarnaFlags::PENDING) { /* if Klarna's order status is pending: add it in the history */ /* The order is under manual review and will be accepted or denied at a later stage. Use cronjob with checkOrderStatus() or visit Klarna Online to check to see if the status has changed. You should still show it to the customer as it was accepted, to avoid further attempts to fraud. */ $order['order_status'] = $method->status_pending; } else { $order['order_status'] = $method->status_success; } $order['customer_notified'] = 1; $order['comments'] = $log; $modelOrder->updateStatusForOneOrder ($order['details']['BT']->virtuemart_order_id, $order, TRUE); $html = $this->renderByLayout ('orderdone', array( 'payment_name' => $dbValues['payment_name'], 'klarna_invoiceno' => $invoiceno)); if ($result['eid'] == VMPAYMENT_KLARNA_MERCHANT_ID_DEMO) { $html .= "<br />" . JText::_ ('VMPAYMENT_KLARNA_WARNING') . "<br />"; } $session = JFactory::getSession (); $session->clear ('Klarna', 'vm'); //We delete the old stuff $cart->emptyCart (); JRequest::setVar ('html', $html); return TRUE; } else { vmError ('Error with invoice number'); } } } /** * @param $orderDetails * @param $data * @return null */ function plgVmOnUserInvoice ($orderDetails, &$data) { if (!($method = $this->getVmPluginMethod ($orderDetails['virtuemart_paymentmethod_id']))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement ($method->payment_element)) { return NULL; } $data['invoice_number'] = 'reservedByPayment_' . $orderDetails['order_number']; // Nerver send the invoice via email } /** * @param $virtuemart_paymentmethod_id * @param $paymentCurrencyId * @return bool|null */ function plgVmGetPaymentCurrency ($virtuemart_paymentmethod_id, &$paymentCurrencyId) { if (!($method = $this->getVmPluginMethod ($virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement ($method->payment_element)) { return FALSE; } $paymentCurrencyId = $this->getKlarnaPaymentCurrency ($method); } /** * @param $method * @return int */ function getKlarnaPaymentCurrency ($method) { if (!class_exists ('VirtueMartCart')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); } $cart = VirtueMartCart::getCart (FALSE); $country = NULL; $countryId = 0; $this->_getCountryCode ($cart, $country, $countryId); $cData = KlarnaHandler::countryData ($method, $country); return shopFunctions::getCurrencyIDByName ($cData['currency_code']); } /** * * An order gets cancelled, because order status='X' * * @param $order * @param $old_order_status * @return bool|null */ function plgVmOnCancelPayment ($order, $old_order_status) { if (!$this->selectedThisByMethodId ($order->virtuemart_paymentmethod_id)) { return NULL; // Another method was selected, do nothing } if (!($method = $this->getVmPluginMethod ($order->virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!($payments = $this->_getKlarnaInternalData ($order->virtuemart_order_id))) { vmError (JText::sprintf ('VMPAYMENT_KLARNA_ERROR_NO_DATA', $order->virtuemart_order_id)); return NULL; } // Status code is === 3==> active invoice. Cannot be be deleted // the invoice is active //if ($order->order_status == $method->status_success) { if ($invNo = $this->_getKlarnaInvoiceNo ($payments)) { //vmDebug('order',$order);return; $country = $this->getCountryCodeByOrderId ($order->virtuemart_order_id); $klarna = new Klarna_virtuemart(); $cData = KlarnaHandler::countryData ($method, $country); $klarna->config ($cData['eid'], $cData['secret'], $cData['country_code'], NULL, $cData['currency_code'], $cData['mode']); try { //remove a passive invoice from Klarna. $result = $klarna->deleteInvoice ($invNo); if ($result) { $message = Jtext::_ ('VMPAYMENT_KLARNA_INVOICE_DELETED') . ":" . $invNo; } else { $message = Jtext::_ ('VMPAYMENT_KLARNA_INVOICE_NOT_DELETED') . ":" . $invNo; } $dbValues['order_number'] = $order->order_number; $dbValues['virtuemart_order_id'] = $order->virtuemart_order_id; $dbValues['virtuemart_paymentmethod_id'] = $order->virtuemart_paymentmethod_id; $dbValues['klarna_invoice_no'] = 0; // it has been deleted $dbValues['klarna_pdf_invoice'] = 0; // it has been deleted $dbValues['klarna_log'] = $message; $dbValues['klarna_eid'] = $cData['eid']; $this->storePSPluginInternalData ($dbValues); VmInfo ($message); } catch (Exception $e) { $log = $e->getMessage () . " (#" . $e->getCode () . ")"; if ($e->getCode () == '8113') { VmError ('invoice_not_passive'); } if ($e->getCode () != 8101) { // unkown_order $this->_updateKlarnaInternalData ($order, $log, $invNo); VmError ($e->getMessage () . " (#" . $e->getCode () . ")"); return FALSE; } } } return TRUE; } /** * @param $payments * @param string $primaryKey * @return mixed */ function _getKlarnaInvoiceNo ($payments, &$primaryKey = '') { $nb = count ($payments); $primaryKey = $payments[$nb - 1]->id; return $payments[$nb - 1]->klarna_invoice_no; } /** * @param $payments * @return mixed */ function _getKlarnaPlcass ($payments) { $nb = count ($payments); return $payments[$nb - 1]->klarna_pclass; } /** * @param $payments * @return mixed */ function _getKlarnaStatusCode ($payments) { $nb = count ($payments); return $payments[$nb - 1]->klarna_status_code; } /** * @author Patrick Kohl * @param $type * @param $name * @param $render */ function plgVmOnSelfCallFE ($type, $name, &$render) { if ($name != $this->_name || $type != 'vmpayment') { return FALSE; } //Klarna Ajax require (JPATH_VMKLARNAPLUGIN . '/klarna/helpers/klarna_ajax.php'); if (!class_exists ('VmModel')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'vmmodel.php'); } $model = VmModel::getModel ('paymentmethod'); $payment = $model->getPayment (); if (!class_exists ('vmParameters')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'parameterparser.php'); } $parameters = new vmParameters($payment, $payment->payment_element, 'plugin', 'vmpayment'); $method = $parameters->getParamByName ('data'); $country = JRequest::getWord ('country'); $country = KlarnaHandler::convertToThreeLetterCode ($country); if (!class_exists ('klarna_virtuemart')) { require (JPATH_VMKLARNAPLUGIN . '/klarna/helpers/klarna_virtuemart.php'); } $settings = KlarnaHandler::getCountryData ($method, $country); $klarna = new Klarna_virtuemart(); $klarna->config ($settings['eid'], $settings['secret'], $settings['country'], $settings['language'], $settings['currency'], KlarnaHandler::getKlarnaMode ($method, $settings['country_code_3']), VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), TRUE); $SelfCall = new KlarnaAjax($klarna, (int)$settings['eid'], JPATH_VMKLARNAPLUGIN, Juri::base ()); $action = JRequest::getWord ('action'); $jlang = JFactory::getLanguage (); $currentLang = substr ($jlang->getDefault (), 0, 2); $newIso = JRequest::getWord ('newIso'); if ($currentLang != $newIso) { $iso = array( "sv" => "sv-SE", "da" => "da-DK", "en" => "en-GB", "de" => "de-DE", "nl" => "nl-NL", "nb" => "nb-NO", "fi" => "fi-FI"); if (array_key_exists ($newIso, $iso)) { $jlang->load ('plg_vmpayment_klarna', JPATH_ADMINISTRATOR, $iso[$newIso], TRUE); } } echo $SelfCall->$action(); jexit (); } /** * @author Patrick Kohl * @param $type * @param $name * @param $render */ function plgVmOnSelfCallBE ($type, $name, &$render) { if ($name != $this->_name || $type != 'vmpayment') { return FALSE; } // fetches PClasses From XML file $call = jrequest::getWord ('call'); $this->$call(); // jexit(); } /** * * Download Pdf Invoice * * @author Valérie Isaksen * */ /** * @return int|null|string */ function downloadInvoicePdf () { if (!class_exists ('VirtueMartModelOrders')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php'); } if (!class_exists ('JFile')) { require(JPATH_SITE . DS . 'libraries' . DS . 'joomla' . DS . 'filesystem' . DS . 'file.php'); } $payment_methodid = JRequest::getInt ('payment_methodid'); $orderNumber = JRequest::getString ('order_number'); $orderPass = JRequest::getString ('order_pass'); if (!($method = $this->getVmPluginMethod ($payment_methodid))) { return NULL; // Another method was selected, do nothing } $modelOrder = VmModel::getModel ('orders'); // If the user is not logged in, we will check the order number and order pass $virtuemart_order_id = $modelOrder->getOrderIdByOrderPass ($orderNumber, $orderPass); if (empty($virtuemart_order_id)) { VmError ('Invalid order_number/password ' . JText::_ ('COM_VIRTUEMART_RESTRICTED_ACCESS'), 'Invalid order_number/password ' . JText::_ ('COM_VIRTUEMART_RESTRICTED_ACCESS')); return 0; } if (!($payments = $this->_getKlarnaInternalData ($virtuemart_order_id))) { return ''; } foreach ($payments as $payment) { if (!empty($payment->klarna_pdf_invoice)) { $path = VmConfig::get ('forSale_path', 0); $path .= DS . 'invoices' . DS; $fileName = $path . $payment->klarna_pdf_invoice; break; } } if (file_exists ($fileName)) { header ("Cache-Control: public"); header ("Content-Transfer-Encoding: binary\n"); header ('Content-Type: application/pdf'); $contentDisposition = 'attachment'; $agent = strtolower ($_SERVER['HTTP_USER_AGENT']); if (strpos ($agent, 'msie') !== FALSE) { $fileName = preg_replace ('/\./', '%2e', $fileName, substr_count ($fileName, '.') - 1); } header ("Content-Disposition: $contentDisposition; filename=\"$payment->klarna_pdf_invoice\""); $contents = file_get_contents ($fileName); echo $contents; } return; } /* * @author Valérie Isaksen * * @return int|null */ function checkOrderStatus () { if (!class_exists ('VirtueMartModelOrders')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php'); } $payment_methodid = JRequest::getInt ('payment_methodid'); //$invNo = JRequest::getWord ('invNo'); $orderNumber = JRequest::getString ('order_number'); $orderPass = JRequest::getString ('order_pass'); if (!($method = $this->getVmPluginMethod ($payment_methodid))) { return NULL; // Another method was selected, do nothing } $modelOrder = VmModel::getModel ('orders'); // If the user is not logged in, we will check the order number and order pass $orderId = $modelOrder->getOrderIdByOrderPass ($orderNumber, $orderPass); if (empty($orderId)) { VmError ('Invalid order_number/password ' . JText::_ ('COM_VIRTUEMART_RESTRICTED_ACCESS'), 'Invalid order_number/password ' . JText::_ ('COM_VIRTUEMART_RESTRICTED_ACCESS')); return 0; } if (!($payments = $this->_getKlarnaInternalData ($orderId))) { return ''; } $invNo = $this->_getKlarnaInvoiceNo ($payments); $country = $this->getCountryCodeByOrderID ($orderId); $settings = KlarnaHandler::countryData ($method, $country); $klarna_order_status = KlarnaHandler::checkOrderStatus ($settings, KlarnaHandler::getKlarnaMode ($method, $settings['country_code_3']), $orderNumber); vmdebug ('Klarna status', $klarna_order_status, $invNo); if ($klarna_order_status == KlarnaFlags::ACCEPTED) { /* if Klarna's order status is pending: add it in the history */ /* The order is under manual review and will be accepted or denied at a later stage. Use cronjob with checkOrderStatus() or visit Klarna Online to check to see if the status has changed. You should still show it to the customer as it was accepted, to avoid further attempts to fraud. */ $order['order_status'] = $method->status_success; $order['comments'] = JText::_ ('VMPAYMENT_KLARNA_PAYMENT_ACCEPTED'); $order['customer_notified'] = 0; $dbValues['klarna_log'] = JText::_ ('VMPAYMENT_KLARNA_PAYMENT_ACCEPTED'); } elseif ($klarna_order_status == KlarnaFlags::DENIED) { $order['order_status'] = $method->status_denied; $order['customer_notified'] = 1; $dbValues['klarna_log'] = JText::_ ('VMPAYMENT_KLARNA_PAYMENT_NOT_ACCEPTED'); $order['comments'] = JText::_ ('VMPAYMENT_KLARNA_PAYMENT_NOT_ACCEPTED'); } else { if ($klarna_order_status == KlarnaFlags::PENDING) { $dbValues['klarna_log'] = JText::_ ('VMPAYMENT_KLARNA_PAYMENT_PENDING'); } else { $dbValues['klarna_log'] = $klarna_order_status; } $order['comments'] = $dbValues['klarna_log']; $order['customer_notified'] = 0; } $dbValues['order_number'] = $orderNumber; $dbValues['virtuemart_order_id'] = $orderId; $dbValues['virtuemart_paymentmethod_id'] = $payment_methodid; $dbValues['klarna_invoice_no'] = $invNo; $this->storePSPluginInternalData ($dbValues); $modelOrder->updateStatusForOneOrder ($orderId, $order, FALSE); $app = JFactory::getApplication (); $app->redirect ('index.php?option=com_virtuemart&view=orders&task=edit&virtuemart_order_id=' . $orderId); // jexit(); } /** * @param $virtuemart_order_id * @return mixed|string */ function _getTablepkeyValue ($virtuemart_order_id) { $db = JFactory::getDBO (); $q = 'SELECT ' . $this->_tablepkey . ' FROM `' . $this->_tablename . '` ' . 'WHERE `virtuemart_order_id` = ' . $virtuemart_order_id; $db->setQuery ($q); if (!($pkey = $db->loadResult ())) { JError::raiseWarning (500, $db->getErrorMsg ()); return ''; } return $pkey; } /** * Display stored payment data for an order * * @see components/com_virtuemart/helpers/vmPSPlugin::plgVmOnShowOrderBEPayment() */ function plgVmOnShowOrderBEPayment ($virtuemart_order_id, $payment_method_id, $order) { if (!($this->selectedThisByMethodId ($payment_method_id))) { return NULL; // Another method was selected, do nothing } if (!($payments = $this->_getKlarnaInternalData ($virtuemart_order_id))) { // JError::raiseWarning(500, $db->getErrorMsg()); return ''; } if (!($method = $this->getVmPluginMethod ($payment_method_id))) { return NULL; // Another method was selected, do nothing } $html = '<table class="adminlist" width="50%">' . "\n"; $html .= $this->getHtmlHeaderBE (); $code = "klarna_"; $class = 'class="row1"'; foreach ($payments as $payment) { $html .= '<tr class="row1"><td>' . JText::_ ('VMPAYMENT_KLARNA_DATE') . '</td><td align="left">' . $payment->created_on . '</td></tr>'; //$html .= $this->getHtmlRow('KLARNA_DATE', "<strong>".$payment->created_on."</strong>", $class); if ($payment->payment_name) { $html .= $this->getHtmlRowBE ('KLARNA_PAYMENT_NAME', $payment->payment_name); } foreach ($payment as $key => $value) { if ($value) { if (substr ($key, 0, strlen ($code)) == $code) { if ($key == 'klarna_pdf_invoice' and !empty($value)) { // backwards compatible if (false) { $invoicePdfLink = JURI::root () . 'administrator/index.php?option=com_virtuemart&view=plugin&type=vmpayment&name=klarna&call=downloadInvoicePdf&payment_methodid=' . (int)$payment_method_id . '&order_number=' . $order['details']['BT']->order_number . '&order_pass=' . $order['details']['BT']->order_pass; $value = '<a target="_blank" href="' . $invoicePdfLink . '">' . JText::_ ('VMPAYMENT_KLARNA_DOWNLOAD_INVOICE') . '</a>'; } else { $value = '<a target="_blank" href="' . $value . '">' . JText::_('VMPAYMENT_KLARNA_VIEW_INVOICE') . '</a>'; } } $html .= $this->getHtmlRowBE ($key, $value); } } } } if ($order['details']['BT']->order_status == $method->status_pending) { if (!class_exists ('VirtueMartModelOrders')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php'); } $country = $this->getCountryCodeByOrderId ($virtuemart_order_id); $invNo = $this->_getKlarnaInvoiceNo ($payments); vmDebug ('plgVmOnShowOrderBEPayment', $invNo); $checkOrderStatus = JURI::root () . 'administrator/index.php?option=com_virtuemart&view=plugin&type=vmpayment&name=klarna&call=checkOrderStatus&payment_methodid=' . (int)$payment_method_id . '&order_number=' . $order['details']['BT']->order_number . '&order_pass=' . $order['details']['BT']->order_pass . '&country=' . $country; $link = '<a href="' . $checkOrderStatus . '">' . JText::_ ('VMPAYMENT_KLARNA_GET_NEW_STATUS') . '</a>'; $html .= $this->getHtmlRowBE ('KLARNA_PAYMENT_CHECK_ORDER_STATUS', $link); } $html .= '</table>' . "\n"; return $html; } /** * @param $virtuemart_order_id * @param string $order_number * @return mixed|string */ function _getKlarnaInternalData ($virtuemart_order_id, $order_number = '') { $db = JFactory::getDBO (); $q = 'SELECT * FROM `' . $this->_tablename . '` WHERE '; if ($order_number) { $q .= " `order_number` = '" . $order_number . "'"; } else { $q .= ' `virtuemart_order_id` = ' . $virtuemart_order_id; } $db->setQuery ($q); if (!($payments = $db->loadObjectList ())) { return ''; } return $payments; } /** * @param VirtueMartCart $cart * @param $method * @param $cart_prices * @return int */ function getCosts (VirtueMartCart $cart, $method, $cart_prices) { $country_code = NULL; $countryId = 0; $this->_getCountryCode ($cart, $country_code, $countryId); return KlarnaHandler::getInvoiceFee ($method, $country_code); } /** * Save updated order data to the method specific table * * @param array $order Form data * @return mixed, True on success, false on failures (the rest of the save-process will be * skipped!), or null when this method is not actived. */ public function plgVmOnUpdateOrderPayment (&$order, $old_order_status) { if (!$this->selectedThisByMethodId ($order->virtuemart_paymentmethod_id)) { return NULL; // Another method was selected, do nothing } if (!($method = $this->getVmPluginMethod ($order->virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!($payments = $this->_getKlarnaInternalData ($order->virtuemart_order_id))) { vmError (JText::sprintf ('VMPAYMENT_KLARNA_ERROR_NO_DATA', $order->virtuemart_order_id)); return NULL; } if (!($invNo = $this->_getKlarnaInvoiceNo ($payments))) { return NULL; } // to activate the order if ($order->order_status == $method->status_shipped) { $country = $this->getCountryCodeByOrderId ($order->virtuemart_order_id); $klarna_vm = new Klarna_virtuemart(); $cData = KlarnaHandler::countryData ($method, $country); /* * The activateInvoice function is used to activate a passive invoice. * Please note that this function call cannot activate an invoice created in test mode. * It is however possible to manually activate that type of invoices. */ $force_emailInvoice = FALSE; $klarna_vm->config ($cData['eid'], $cData['secret'], $cData['country_code'], NULL, $cData['currency_code'], KlarnaHandler::getKlarnaMode ($method, $cData['country_code_3'])); try { //You can specify a new pclass ID if the customer wanted to change it before you activate. $klarna_vm->activateInvoice ($invNo); $invoice_url=$this->getInvoice($invNo, $invoice_url); //The url points to a PDF file for the invoice. //Invoice activated, proceed accordingly. } catch (Exception $e) { $log = $e->getMessage () . " (#" . $e->getCode () . ")"; if ($e->getCode () != 8111) { // (invoice_not_passive_or_frozen) $this->_updateKlarnaInternalData ($order, $log); VmError ($e->getMessage () . " (#" . $e->getCode () . ")"); return FALSE; } else { $force_emailInvoice = TRUE; } } $emailInvoice = $this->emailInvoice ($method, $klarna_vm, $invNo, $force_emailInvoice); $dbValues['order_number'] = $order->order_number; $dbValues['virtuemart_order_id'] = $order->virtuemart_order_id; $dbValues['virtuemart_paymentmethod_id'] = $order->virtuemart_paymentmethod_id; $dbValues['klarna_invoice_no'] = $invNo; $dbValues['klarna_log'] = Jtext::sprintf ('VMPAYMENT_KLARNA_ACTIVATE_INVOICE', $invNo); if ($emailInvoice) { $dbValues['klarna_log'] .= "<br />" . Jtext::sprintf ('VMPAYMENT_KLARNA_EMAIL_INVOICE', $invNo); } else { $dbValues['klarna_log'] .= "<br />" . Jtext::_ ('VMPAYMENT_KLARNA_EMAIL_INVOICE_NOT_SENT'); } $dbValues['klarna_eid'] = $cData['eid']; //$dbValues['klarna_status_code'] = KLARNA_INVOICE_ACTIVE; // Invoice is active //$dbValues['klarna_status_text'] = ''; $dbValues['klarna_pdf_invoice'] = $invoice_url; $this->storePSPluginInternalData ($dbValues); return TRUE; } return NULL; } /** * @param $klarna_invoice_pdf * @param $vm_invoice_name * @return bool */ function getInvoice ($invoice_number, &$vm_invoice_name) { //$klarna_invoice = explode ('/', $klarna_invoice_pdf); if ($this->method->server =='live') { $klarna_invoice_name = "https://online.klarna.com/invoices/" . $invoice_number . '.pdf'; } else { $klarna_invoice_name = "https://online.testdrive.klarna.com/invoices/" . $invoice_number . '.pdf'; } $vm_invoice_name = 'klarna_' . $invoice_number . '.pdf'; return $klarna_invoice_name; } private function emailInvoice ($method, $klarna_vm, $invNo, $force_emailInvoice) { if ($method->send_invoice or $force_emailInvoice) { try { $result = $klarna_vm->emailInvoice ($invNo); /* Invoice sent to customer via email, proceed accordingly. $result contains the invoice number of the emailed invoice. */ } catch (Exception $e) { //Something went wrong, print the message: VmError ($e->getMessage () . " (#" . $e->getCode () . ")"); } return TRUE; } return FALSE; } /** * @param $order * @param $log */ function _updateKlarnaInternalData ($order, $log) { $dbValues['virtuemart_order_id'] = $order->virtuemart_order_id; $dbValues['order_number'] = $order->order_number; $dbValues['klarna_log'] = $log; $this->storePSPluginInternalData ($dbValues); } /** * Create the table for this plugin if it does not yet exist. * This functions checks if the called plugin is active one. * When yes it is calling the standard method to create the tables * */ function plgVmOnStoreInstallPaymentPluginTable ($jplugin_id) { if ($jplugin_id != $this->_jid) { return FALSE; } if (!class_exists ('JFile')) { require(JPATH_SITE . DS . 'libraries' . DS . 'joomla' . DS . 'filesystem' . DS . 'file.php'); } /* * if the file Klarna.cfg does not exist, then create it */ $filename = VMKLARNA_CONFIG_FILE; if (!JFile::exists ($filename)) { $fileContents = "<?php defined('_JEXEC') or die(); define('VMKLARNA_SHIPTO_SAME_AS_BILLTO', '1'); define('VMKLARNA_SHOW_PRODUCTPRICE', '1'); ?>"; $result = JFile::write ($filename, $fileContents); if (!$result) { VmError (JText::sprintf ('VMPAYMENT_KLARNA_CANT_WRITE_CONFIG', $filename, $result)); } } $method = $this->getPluginMethod (JRequest::getInt ('virtuemart_paymentmethod_id')); if (KlarnaHandler::createKlarnaFolder ()) { $results = KlarnaHandler::fetchAllPClasses ($method); if (is_array ($results) and $results['msg']) { vmError ($results['msg']); } } vmDebug ('PClasses fetched for : ', $results['notice']); // we have to check that the following Shopper fields are there $required_shopperfields_vm = Klarnahandler::getKlarnaVMGenericShopperFields (); $required_shopperfields_bycountry = KlarnaHandler::getKlarnaSpecificShopperFields (); $userFieldsModel = VmModel::getModel ('UserFields'); $switches['published'] = TRUE; $userFields = $userFieldsModel->getUserFields ('', $switches); // TEST that all Vm shopperfields are there foreach ($userFields as $userField) { $fields_name_vm[] = $userField->name; } $result = array_intersect ($fields_name_vm, $required_shopperfields_vm); $vm_required_not_found = array_diff ($required_shopperfields_vm, $result); if (count ($vm_required_not_found)) { VmError (JText::sprintf ('VMPAYMENT_KLARNA_REQUIRED_USERFIELDS_NOT_FOUND', implode (", ", $vm_required_not_found))); } else { VmInfo (JText::_ ('VMPAYMENT_KLARNA_REQUIRED_USERFIELDS_OK')); } VmConfig::loadJLang('com_virtuemart_shoppers', true); $klarna_required_not_found = array(); // TEST that all required Klarna shopper fields are there, if not create them foreach ($required_shopperfields_bycountry as $key => $shopperfield_country) { $active = 'klarna_active_' . strtolower ($key); if ($method->$active) { $resultByCountry = array_intersect ($fields_name_vm, $shopperfield_country); $klarna_required_country_not_found = array_diff ($shopperfield_country, $resultByCountry); $klarna_required_not_found = array_merge ($klarna_required_country_not_found, $klarna_required_not_found); } } $klarna_required_not_found = array_unique ($klarna_required_not_found, SORT_STRING); if (count ($klarna_required_not_found)) { VmError (JText::sprintf ('VMPAYMENT_KLARNA_REQUIRED_USERFIELDS_NOT_FOUND', implode (", ", $klarna_required_not_found))); $shopperFieldsType = KlarnaHandler::getKlarnaShopperFieldsType (); $userfieldsModel = VmModel::getModel ('userfields'); $data['virtuemart_userfield_id'] = 0; $data['published'] = 1; $data['required'] = 0; $data['account'] = 1; $data['shipment'] = 0; $data['vNames'] = array(); $data['vValues'] = array(); VmConfig::loadJLang('com_virtuemart_shoppers', true); foreach ($klarna_required_not_found as $requiredfield) { $data['name'] = $requiredfield; $data['type'] = $shopperFieldsType[$requiredfield]; $data['title'] = strtoupper ('COM_VIRTUEMART_SHOPPER_FORM_' . $requiredfield); $ret = $userfieldsModel->store ($data); if (!$ret) { vmError (JText::_ ('VMPAYMENT_KLARNA_REQUIRED_USERFIELDS_ERROR_STORING') . $requiredfield); } else { vmInfo (JText::_ ('VMPAYMENT_KLARNA_REQUIRED_USERFIELDS_CREATE_OK') . $requiredfield); } } } else { VmInfo (JText::_ ('VMPAYMENT_KLARNA_REQUIRED_USERFIELDS_OK')); } $result = $this->onStoreInstallPluginTable ($jplugin_id); return $result; } /** * This event is fired after the payment method has been selected. It can be used to store * additional payment info in the cart. * * @author Valérie isaksen * * @param VirtueMartCart $cart: the actual cart * @return null if the payment was not selected, true if the data is valid, error message if the data is not vlaid * */ public function plgVmOnSelectCheckPayment (VirtueMartCart $cart, &$msg) { if (!$this->selectedThisByMethodId ($cart->virtuemart_paymentmethod_id)) { return NULL; // Another method was selected, do nothing } if (!($method = $this->getVmPluginMethod ($cart->virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!class_exists ('KlarnaAddr')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'klarnaaddr.php'); } $session = JFactory::getSession (); $sessionKlarna = new stdClass(); //$post = JRequest::get('post'); $errors = array(); $klarnaData_paymentmethod = JRequest::getVar ('klarna_paymentmethod', ''); if ($klarnaData_paymentmethod == 'klarna_invoice') { $sessionKlarna->klarna_option = 'invoice'; } elseif ($klarnaData_paymentmethod == 'klarna_partPayment') { $sessionKlarna->klarna_option = 'part'; } elseif ($klarnaData_paymentmethod == 'klarna_speccamp') { $sessionKlarna->klarna_option = 'spec'; } else { return NULL; } // Store payment_method_id so we can activate the // right payment in case something goes wrong. $sessionKlarna->virtuemart_payment_method_id = $cart->virtuemart_paymentmethod_id; $sessionKlarna->klarna_paymentmethod = $klarnaData_paymentmethod; $country3 = NULL; $countryId = 0; $this->_getCountryCode ($cart, $country3, $countryId, 'country_3_code'); // $country2= strtolower($country2); if (empty($country3)) { $country3 = "SWE"; $countryId = ShopFunctions::getCountryIDByName ($country3); } $cData = KlarnaHandler::countryData ($method, strtoupper ($country3)); $klarnaData = KlarnaHandler::getDataFromEditPayment (); if ($msg = KlarnaHandler::checkDataFromEditPayment ($klarnaData, $cData['country_code_3'])) { //vmInfo($msg); // meanwhile the red baloon works $session->set ('Klarna', serialize ($sessionKlarna), 'vm'); return FALSE; } $klarnaData['country'] = $cData['country_code']; $klarnaData['country3'] = $cData['country_code_3']; //$country = $cData['country_code']; //KlarnaHandler::convertCountry($method, $country2); //$lang = $cData['language_code']; //KlarnaHandler::getLanguageForCountry($method, $country); // Get the correct data //Removes spaces, tabs, and other delimiters. // If it is a swedish customer we use the information from getAddress if (strtolower ($cData['country_code']) == "se") { $swedish_addresses = KlarnaHandler::getAddresses ($klarnaData['socialNumber'], $cData, $method); if (empty($swedish_addresses)) { $msg = JText::_ ('VMPAYMENT_KLARNA_ERROR_TITLE_2'); $msg .= JText::_ ('VMPAYMENT_KLARNA_NO_GETADDRESS'); $session->set ('Klarna', serialize ($sessionKlarna), 'vm'); return FALSE; } //This example only works for GA_GIVEN. foreach ($swedish_addresses as $address) { if ($address->isCompany) { $klarnaData['company_name'] = $address->getCompanyName (); $klarnaData['first_name'] = "-"; $klarnaData['last_name'] = "-"; } else { $klarnaData['first_name'] = $address->getFirstName (); $klarnaData['last_name'] = $address->getLastName (); } $klarnaData['street'] = $address->getStreet (); $klarnaData['zip'] = $address->getZipCode (); $klarnaData['city'] = $address->getCity (); $klarnaData['country'] = $address->getCountryCode (); $countryId = $klarnaData['virtuemart_country_id'] = shopFunctions::getCountryIDByName ($klarnaData['country']); } foreach ($klarnaData as $key => $value) { $klarnaData[$key] = mb_convert_encoding ($klarnaData[$key], 'UTF-8', 'ISO-8859-1'); } } $address_type = NULL; $st = $this->getCartAddress ($cart, $address_type, TRUE); vmDebug ('getCartAddress', $st); if ($address_type == 'BT') { $prefix = ''; } else { $prefix = 'shipto_'; } // Update the Shipping Address to what is specified in the register. $update_data = array( $prefix . 'address_type_name' => 'Klarna', $prefix . 'company' => $klarnaData['company_name'], $prefix . 'title' => $klarnaData['title'], $prefix . 'first_name' => $klarnaData['first_name'], $prefix . 'middle_name' => $st['middle_name'], $prefix . 'last_name' => $klarnaData['last_name'], $prefix . 'address_1' => $klarnaData['street'], $prefix . 'address_2' => $klarnaData['house_ext'], $prefix . 'house_no' => $klarnaData['house_no'], $prefix . 'zip' => html_entity_decode ($klarnaData['zip']), $prefix . 'city' => $klarnaData['city'], $prefix . 'virtuemart_country_id' => $countryId, //$klarnaData['virtuemart_country_id'], $prefix . 'state' => '', $prefix . 'phone_1' => $klarnaData['phone'], $prefix . 'phone_2' => $st['phone_2'], $prefix . 'fax' => $st['fax'], //$prefix . 'birthday' => empty($klarnaData['birthday']) ? $st['birthday'] : $klarnaData['birthday'], //$prefix . 'socialNumber' => empty($klarnaData['pno']) ? $klarnaData['socialNumber'] : $klarnaData['pno'], 'address_type' => $address_type ); if ($address_type == 'BT') { $update_data ['email'] = $klarnaData['email']; } if (!empty($st)) { $update_data = array_merge ($st, $update_data); } // save address in cart if different // if (false) { $cart->saveAddressInCart ($update_data, $update_data['address_type'], TRUE); //vmdebug('plgVmOnSelectCheckPayment $cart',$cart); //vmInfo(JText::_('VMPAYMENT_KLARNA_ADDRESS_UPDATED_NOTICE')); // } //} // Store the Klarna data in a session variable so // we can retrevie it later when we need it //$klarnaData['pclass'] = ($klarnaData_paymentmethod == 'klarna_invoice' ? -1 : intval(JRequest::getVar($kIndex . "paymentPlan"))); $klarnaData['pclass'] = ($klarnaData_paymentmethod == 'klarna_invoice' ? -1 : intval (JRequest::getVar ("part_klarna_paymentPlan"))); $sessionKlarna->KLARNA_DATA = $klarnaData; // 2 letters small //$settings = KlarnaHandler::getCountryData($method, $cart_country2); try { $address = new KlarnaAddr( $klarnaData['email'], $klarnaData['phone'], "", //mobile $klarnaData['first_name'], $klarnaData['last_name'], '', $klarnaData['street'], $klarnaData['zip'], $klarnaData['city'], $klarnaData['country'], // $settings['country'], $klarnaData['house_no'], $klarnaData['house_ext'] ); } catch (Exception $e) { VmInfo ($e->getMessage ()); return FALSE; //KlarnaHandler::redirectPaymentMethod('message', $e->getMessage()); } if (isset($errors) && count ($errors) > 0) { $msg = JText::_ ('VMPAYMENT_KLARNA_ERROR_TITLE_1'); foreach ($errors as $error) { $msg .= "<li> -" . $error . "</li>"; } $msg .= JText::_ ('VMPAYMENT_KLARNA_ERROR_TITLE_2'); unset($errors); VmError ($msg); return FALSE; //KlarnaHandler::redirectPaymentMethod('error', $msg); } $session->set ('Klarna', serialize ($sessionKlarna), 'vm'); return TRUE; } /** * plgVmOnSelectedCalculatePricePayment * Calculate the price (value, tax_id) of the selected method * It is called by the calculator * This function does NOT to be reimplemented. If not reimplemented, then the default values from this function are taken. * * @author Valerie Isaksen * @param VirtueMartCart $cart * @param array $cart_prices * @param $cart_prices_name * @return bool|null */ public function plgVmOnSelectedCalculatePricePayment (VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) { return $this->onKlarnaSelectedCalculatePrice ($cart, $cart_prices, $cart_prices_name); } /** * @param VirtuemartViewUser $user * @param $html * @param string $from_cart * @return bool|null */ function plgVmDisplayLogin (VirtuemartViewUser $user, &$html, $from_cart = FALSE) { // only to display it in the cart, not in list orders view if (!$from_cart) { return NULL; } $vendorId = 1; if (!class_exists ('VirtueMartCart')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); } $cart = VirtueMartCart::getCart (); if ($cart->BT != 0 or $cart->virtuemart_paymentmethod_id) { return; } if ($this->getPluginMethods ($vendorId) === 0) { if (empty($this->_name)) { $app = JFactory::getApplication (); $app->enqueueMessage (JText::_ ('COM_VIRTUEMART_CART_NO_' . strtoupper ($this->_psType))); return FALSE; } else { return FALSE; } } //vmdebug('plgVmDisplayLogin', $user); //$html = $this->renderByLayout('displaylogin', array('klarna_pm' => $klarna_pm, 'virtuemart_paymentmethod_id' => $method->virtuemart_paymentmethod_id, 'klarna_paymentmethod' => $klarna_paymentmethod)); $link = JRoute::_ ('index.php?option=com_virtuemart&view=cart&task=editpayment&klarna_country_2_code=se'); foreach ($this->methods as $method) { if ($method->klarna_active_swe) { $html .= $this->renderByLayout ('displaylogin', array('editpayment_link' => $link)); } } } /** * @param VirtueMartCart $cart * @param array $cart_prices * @param $cart_prices_name * @return bool|null */ private function onKlarnaSelectedCalculatePrice (VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) { if (!($method = $this->selectedThisByMethodId ($cart->virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!($method = $this->getVmPluginMethod ($cart->virtuemart_paymentmethod_id))) { return NULL; } $sessionKlarnaData = $this->getKlarnaSessionData (); if (empty($sessionKlarnaData)) { return NULL; } $cart_prices_name = ''; $cart_prices[$this->_psType . '_tax_id'] = 0; $cart_prices['cost'] = 0; //vmdebug('cart prices', $cart_prices); $country_code = NULL; $countryId = 0; $this->_getCountryCode ($cart, $country_code, $countryId, 'country_2_code'); if (isset($sessionKlarnaData->KLARNA_DATA) AND strcasecmp ($country_code, $sessionKlarnaData->KLARNA_DATA['country']) != 0) { return FALSE; } //$paramsName = $this->_psType . '_params'; $type = NULL; $address = $this->getCartAddress ($cart, $type, FALSE); if (empty($address)) { return FALSE; } $shipTo = KlarnaHandler::getShipToAddress ($cart); $cart_prices_name = $this->renderKlarnaPluginName ($method, $address['virtuemart_country_id'], $shipTo, $cart_prices['withTax'], $cart->pricesCurrency); if (isset($sessionKlarnaData->klarna_option) AND $sessionKlarnaData->klarna_option == 'invoice') { $this->setCartPrices ($cart, $cart_prices, $method); } return TRUE; } /** * update the plugin cart_prices * * @author Valérie Isaksen * @param VirtueMartCart $cart * @param $cart_prices * @param $method */ function setCartPrices (VirtueMartCart $cart, &$cart_prices, $method) { $country = NULL; $countryId = 0; $this->_getCountryCode (NULL, $country, $countryId); $invoice_fee = KlarnaHandler::getInvoiceFee ($method, $country); $invoice_tax_id = KlarnaHandler::getInvoiceTaxId ($method, $country); $_psType = ucfirst ($this->_psType); $taxrules = array(); if (!empty($invoice_tax_id)) { $db = JFactory::getDBO (); $q = 'SELECT * FROM #__virtuemart_calcs WHERE `virtuemart_calc_id`="' . $invoice_tax_id . '" '; $db->setQuery ($q); $taxrules = $db->loadAssocList (); } if (!class_exists ('calculationHelper')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php'); } $calculator = calculationHelper::getInstance (); if (count ($taxrules) > 0) { $calculator->setRevert (TRUE); $invoiceFeeWithoutTax = $calculator->roundInternal ($calculator->executeCalculation ($taxrules, $invoice_fee)); $cart_prices['salesPricePayment'] = $invoice_fee; $cart_prices['paymentTax'] = $invoice_fee - $calculator->roundInternal ($invoiceFeeWithoutTax); $cart_prices['paymentValue'] = $invoiceFeeWithoutTax; $calculator->setRevert (FALSE); $cart_prices[$this->_psType . '_calc_id'] = $taxrules[0]['virtuemart_calc_id']; } else { $cart_prices['paymentValue'] = $invoice_fee; $cart_prices['salesPricePayment'] = $invoice_fee; $cart_prices['paymentTax'] = 0; $cart_prices[$this->_psType . '_calc_id'] = 0; } } /** * @param $method * @param $virtuemart_country_id * @param $shipTo * @param $total * @return string */ protected function renderKlarnaPluginName ($method, $virtuemart_country_id, $shipTo, $total, $cartPricesCurrency) { $session = JFactory::getSession (); $sessionKlarna = $session->get ('Klarna', 0, 'vm'); if (empty($sessionKlarna)) { return ''; } $sessionKlarnaData = unserialize ($sessionKlarna); $address['virtuemart_country_id'] = $virtuemart_country_id; $cData = KlarnaHandler::getcData ($method, $address); $country2 = strtolower (shopFunctions::getCountryByID ($virtuemart_country_id, 'country_2_code')); $text = ""; if (isset($sessionKlarnaData->klarna_option)) { switch ($sessionKlarnaData->klarna_option) { case 'invoice': $sType='invoice'; $image = '/klarna_invoice_' . $country2 . '.png'; //$logo = VMKLARNAPLUGINWEBASSETS . '/images/' . 'logo/klarna_' . $sType . '_' . $code2 . '.png'; $image ="https://cdn.klarna.com/public/images/".strtoupper($country2)."/badges/v1/". $sType ."/".$country2."_". $sType ."_badge_std_blue.png?height=55&eid=".$cData['eid']; $display_invoice_fee = NULL; $invoice_fee = 0; KlarnaHandler::getInvoiceFeeInclTax ($method, $cData['country_code_3'], $cartPricesCurrency, $cData['virtuemart_currency_id'], $display_invoice_fee, $invoice_fee); $text = JText::sprintf ('VMPAYMENT_KLARNA_INVOICE_TITLE_NO_PRICE', $display_invoice_fee); break; case 'partpayment': case 'part': $sType='account'; //$image = '/klarna_part_' . $country2 . '.png'; $image ="https://cdn.klarna.com/public/images/".strtoupper($country2)."/badges/v1/". $sType ."/".$country2."_". $sType ."_badge_std_blue.png?height=55&eid=".$cData['eid']; $address['virtuemart_country_id'] = $virtuemart_country_id; //$pclasses = KlarnaHandler::getPClasses(NULL, KlarnaHandler::getKlarnaMode($method), $cData); if (!class_exists ('Klarna_payments')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarna_payments.php'); } $payments = new klarna_payments($cData, $shipTo); //vmdebug('displaylogos',$cart_prices); $totalInPaymentCurrency = KlarnaHandler::convertPrice ($total, $cData['vendor_currency'], $cData['virtuemart_currency_id']); vmdebug ('totalInPaymentCurrency', $totalInPaymentCurrency); if (isset($sessionKlarnaData->KLARNA_DATA)) { $text = $payments->displayPclass ($sessionKlarnaData->KLARNA_DATA['pclass'], $totalInPaymentCurrency); // .' '.$total; } break; case 'speccamp': $image = 'klarna_logo.png'; $text = JText::_ ('VMPAYMENT_KLARNA_SPEC_TITLE'); break; default: $image = ''; $text = ''; break; } $plugin_name = $this->_psType . '_name'; $plugin_desc = $this->_psType . '_desc'; $payment_description = ''; if (!empty($method->$plugin_desc)) { $payment_description = $method->$plugin_desc; } $payment_name = $method->$plugin_name; $html = $this->renderByLayout ('payment_cart', array( 'logo' => $image, 'text' => $text, 'payment_description' => $payment_description, 'payment_name' => $payment_name )); return $html; } } /** * plgVmOnCheckAutomaticSelectedPayment * Checks how many plugins are available. If only one, the user will not have the choice. Enter edit_xxx page * The plugin must check first if it is the correct type * * @author Valerie Isaksen * @param VirtueMartCart cart: the cart object * @return null if no plugin was found, 0 if more then one plugin was found, virtuemart_xxx_id if only one plugin is found * */ function plgVmOnCheckAutomaticSelectedPayment (VirtueMartCart $cart, array $cart_prices = array(), &$paymentCounter) { $nbMethod = 0; if ($this->getPluginMethods ($cart->vendorId) === 0) { return NULL; } foreach ($this->methods as $method) { $type = NULL; $cData = KlarnaHandler::getcData ($method, $this->getCartAddress ($cart, $type, FALSE)); if ($cData) { if ($nb = (int)$this->checkCountryCondition ($method, $cData['country_code_3'], $cart)) { $nbMethod = $nbMethod + $nb; } } } $paymentCounter = $paymentCounter + $nbMethod; if ($nbMethod == 0) { return NULL; } else { return 0; } } /** * This method is fired when showing the order details in the frontend. * It displays the method-specific data. * * @param $virtuemart_order_id * @param $virtuemart_paymentmethod_id * @param $payment_name * @internal param int $order_id The order ID * @return mixed Null for methods that aren't active, text (HTML) otherwise * @author Valerie Isaksen */ public function plgVmOnShowOrderFEPayment ($virtuemart_order_id, $virtuemart_paymentmethod_id, &$payment_name) { if ($this->onShowOrderFE ($virtuemart_order_id, $virtuemart_paymentmethod_id, $payment_name)) { return FALSE; } return NULL; } function plgVmOnCheckoutAdvertise ($cart, &$payment_advertise) { $vendorId = 1; $loadScriptAndCss = FALSE; if (!class_exists ('Klarna_payments')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarna_payments.php'); } $country_code = NULL; $countryId = 0; if ($this->getPluginMethods ($cart->vendorId) === 0) { return FALSE; } $this->_getCountryCode ($cart, $country_code, $countryId); foreach ($this->methods as $method) { if ($cart->virtuemart_paymentmethod_id == $method->virtuemart_paymentmethod_id) { continue; } if (!($cData = $this->checkCountryCondition ($method, $country_code, $cart))) { return NULL; } if (strtolower ($country_code) == 'nld') { // Since 12/09/12: merchants can sell goods with Klarna Invoice up to thousands of euros. So the price check has been moved here if (!KlarnaHandler::checkPartNLpriceCondition ($cart)) { // We can't show our payment options for Dutch customers // if price exceeds 250 euro. Will be replaced with ILT in // the future. return NULL; } } $payments = new klarna_payments($cData, KlarnaHandler::getShipToAddress ($cart)); // TODO: change to there is a function in the API $sFee = $payments->getCheapestMonthlyCost ($cart, $cData); if ($sFee) { $payment_advertise[] = $this->renderByLayout ('cart_advertisement', array("sFee" => $sFee, "eid" => $cData['eid'], "country"=> $cData['country_code'] )); } } } /** * This method is fired when showing when printing an Order * It displays the the payment method-specific data. * * @param integer $order_number The order Number * @param integer $method_id method used for this order * @return mixed Null when for payment methods that were not selected, text (HTML) otherwise */ function plgVmOnShowOrderPrintPayment ($order_number, $method_id) { return $this->onShowOrderPrint ($order_number, $method_id); } /** * @return mixed */ function _getVendorCurrency () { if (!class_exists ('VirtueMartModelVendor')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php'); } $vendor_id = 1; $vendor_currency = VirtueMartModelVendor::getVendorCurrency ($vendor_id); return $vendor_currency->currency_code_3; } /** * */ function loadScriptAndCss () { static $loaded = false; if ($loaded) { return; } $assetsPath = VMKLARNAPLUGINWEBROOT . '/klarna/assets/'; JHTML::stylesheet ('style.css', $assetsPath . 'css/', FALSE); JHTML::stylesheet ('klarna.css', $assetsPath . 'css/', FALSE); JHTML::script ('klarna_general.js', $assetsPath . 'js/', FALSE); JHTML::script ('klarnaConsentNew.js', 'http://static.klarna.com/external/js/', FALSE); $document = JFactory::getDocument (); /* $document->addScriptDeclaration (' klarna.ajaxPath = "' . juri::root () . '/index.php?option=com_virtuemart&view=plugin&vmtype=vmpayment&name=klarna"; '); */ $loaded=true; } } // No closing tag
gpl-2.0
mambax7/smartfaq
assets/js/overlib/overlib_exclusive.js
3391
//\///// //\ overLIB Exclusive Plugin //\ This file requires overLIB 4.00 or later. //\ //\ overLIB 4.05 - You may not remove or change this notice. //\ Copyright Erik Bosrup 1998-2004. All rights reserved. //\ Contributors are listed on the homepage. //\ See http://www.bosrup.com/web/overlib/ for details. // $Revision: 1.2 $ $Date: 2005/08/15 16:52:04 $ //\///// //////// // PRE-INIT // Ignore these lines, configuration is below. //////// if (typeof olInfo == 'undefined' || olInfo.simpleversion < 400) alert('overLIB 4.00 or later is required for the Debug Plugin.'); registerCommands('exclusive,exclusivestatus,exclusiveoverride'); var olOverrideIsSet; // variable which tells if override is set //////// // DEFAULT CONFIGURATION // Settings you want everywhere are set here. All of this can also be // changed on your html page or through an overLIB call. //////// if (typeof ol_exclusive == 'undefined') var ol_exclusive = 0; if (typeof ol_exclusivestatus == 'undefined') var ol_exclusivestatus = 'Please close open popup first.'; //////// // END OF CONFIGURATION // Don't change anything below this line, all configuration is above. //////// //////// // INIT //////// // Runtime variables init. Don't change for config! var o3_exclusive = 0; var o3_exclusivestatus = ''; //////// // PLUGIN FUNCTIONS //////// // Set runtime variables function setExclusiveVariables() { o3_exclusive = ol_exclusive; o3_exclusivestatus = ol_exclusivestatus; } // Parses Exclusive Parameters function parseExclusiveExtras(pf, i, ar) { var k = i, v; olOverrideIsSet = false; // a global variable if (k < ar.length) { if (ar[k] == EXCLUSIVEOVERRIDE) { if (pf != 'ol_') olOverrideIsSet = true; return k; } if (ar[k] == EXCLUSIVE) { eval(pf + 'exclusive = (' + pf + 'exclusive == 0)? 1 : 0'); return k; } if (ar[k] == EXCLUSIVESTATUS) { eval(pf + "exclusivestatus = '" + escSglQuote(ar[++k]) + "'"); return k; } } return -1; } /////// // HELPER FUNCTIONS /////// // set status message and indicate whether popup is exclusive function isExclusive(args) { var rtnVal = false; if (args != null) rtnVal = hasCommand(args, EXCLUSIVEOVERRIDE); if (rtnVal) return false; else { self.status = (o3_exclusive) ? o3_exclusivestatus : ''; return o3_exclusive; } } // checks overlib argument list to see if it has a COMMAND argument function hasCommand(args, COMMAND) { var rtnFlag = false; for (var i = 0; i < args.length; i++) { if (typeof args[i] == 'number' && args[i] == COMMAND) { rtnFlag = true; break; } } return rtnFlag; } // makes sure exclusive setting is off function clearExclusive() { o3_exclusive = 0; } function setExclusive() { o3_exclusive = (o3_showingsticky && o3_exclusive); } function chkForExclusive() { if (olOverrideIsSet) o3_exclusive = 0; // turn it off in case it's been set. return true; } //////// // PLUGIN REGISTRATIONS //////// registerRunTimeFunction(setExclusiveVariables); registerCmdLineFunction(parseExclusiveExtras); registerPostParseFunction(chkForExclusive); registerHook("createPopup", setExclusive, FBEFORE); registerHook("hideObject", clearExclusive, FAFTER);
gpl-2.0
tstephen/srp-digital
wp-content/plugins/broken-link-checker/modules/containers/dummy.php
1577
<?php /* Plugin Name: Dummy Description: Version: 1.0 Author: Janis Elsts ModuleID: dummy ModuleCategory: container ModuleClassName: blcDummyManager ModuleAlwaysActive: true ModuleHidden: true */ /** * A "dummy" container class that can be used as a fallback when the real container class can't be found. * * * @package Broken Link Checker * @access public */ class blcDummyContainer extends blcContainer { function synch() { //Just mark it as synched so that it doesn't bother us anymore. $this->mark_as_synched(); } function edit_link( $field_name, $parser, $new_url, $old_url = '', $old_raw_url = '', $new_text = null ) { return new WP_Error( 'container_not_found', sprintf( __( "I don't know how to edit a '%1\$s' [%2\$d].", 'broken-link-checker' ), $this->container_type, $this->container_id ) ); } function unlink( $field_name, $parser, $url, $raw_url = '' ) { return new WP_Error( 'container_not_found', sprintf( __( "I don't know how to edit a '%1\$s' [%2\$d].", 'broken-link-checker' ), $this->container_type, $this->container_id ) ); } function ui_get_source( $container_field, $context = 'display' ) { return sprintf( '<em>Unknown source %s[%d]:%s</em>', $this->container_type, $this->container_id, $container_field ); } } /** * A dummy manager class. * * @package Broken Link Checker * @access public */ class blcDummyManager extends blcContainerManager { var $container_class_name = 'blcDummyContainer'; function resynch( $forced = false ) { //Do nothing. } }
gpl-2.0
ahsparrow/xcsoar_orig
src/Screen/GDI/Bitmap.cpp
3143
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2015 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "Screen/Bitmap.hpp" #include "Screen/Debug.hpp" #ifdef HAVE_AYGSHELL_DLL #include "OS/AYGShellDLL.hpp" #endif #ifdef HAVE_IMGDECMP_DLL #include "Screen/RootDC.hpp" #include "OS/ImgDeCmpDLL.hpp" #endif #include <assert.h> #ifdef HAVE_IMGDECMP_DLL static DWORD CALLBACK imgdecmp_get_data(LPSTR szBuffer, DWORD dwBufferMax, LPARAM lParam) { HANDLE file = (HANDLE)lParam; DWORD nbytes = 0; return ReadFile(file, szBuffer, dwBufferMax, &nbytes, nullptr) ? nbytes : 0; } static HBITMAP load_imgdecmp_file(const TCHAR *path) { ImgDeCmpDLL imgdecmp_dll; if (!imgdecmp_dll.IsDefined()) return false; HANDLE file = ::CreateFile(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) return false; BYTE buffer[1024]; HBITMAP bitmap; RootDC dc; DecompressImageInfo dii; dii.dwSize = sizeof(dii); dii.pbBuffer = buffer; dii.dwBufferMax = sizeof(buffer); dii.dwBufferCurrent = 0; dii.phBM = &bitmap; dii.ppImageRender = nullptr; dii.iBitDepth = GetDeviceCaps(dc, BITSPIXEL); dii.lParam = (LPARAM)file; dii.hdc = dc; dii.iScale = 100; dii.iMaxWidth = 10000; dii.iMaxHeight = 10000; dii.pfnGetData = imgdecmp_get_data; dii.pfnImageProgress = nullptr; dii.crTransparentOverride = (UINT)-1; HRESULT result = imgdecmp_dll.DecompressImageIndirect(&dii); ::CloseHandle(file); return SUCCEEDED(result) ? bitmap : nullptr; } #endif /* HAVE_IMGDECMP_DLL */ bool Bitmap::LoadFile(const TCHAR *path) { #ifdef HAVE_AYGSHELL_DLL AYGShellDLL ayg; bitmap = ayg.SHLoadImageFile(path); if (bitmap != nullptr) return true; #endif #ifdef HAVE_IMGDECMP_DLL bitmap = load_imgdecmp_file(path); if (bitmap != nullptr) return true; #endif return false; } void Bitmap::Reset() { if (bitmap != nullptr) { assert(IsScreenInitialized()); #ifndef NDEBUG bool success = #endif ::DeleteObject(bitmap); assert(success); bitmap = nullptr; } } const PixelSize Bitmap::GetSize() const { assert(IsDefined()); BITMAP bm; ::GetObject(bitmap, sizeof(bm), &bm); const PixelSize size = { bm.bmWidth, bm.bmHeight }; return size; }
gpl-2.0
sandrinr/XCSoar
src/Repository/Glue.cpp
1320
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2021 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "Glue.hpp" #include "net/http/DownloadManager.hpp" #include "system/Path.hpp" #include <tchar.h> #define REPOSITORY_URI "http://download.xcsoar.org/repository" static bool repository_downloaded = false; void EnqueueRepositoryDownload(bool force) { if (repository_downloaded && !force) return; repository_downloaded = true; Net::DownloadManager::Enqueue(REPOSITORY_URI, Path(_T("repository"))); }
gpl-2.0
zcwilt/zencart
includes/classes/split_page_results.php
9797
<?php /** * split_page_results Class. * * @copyright Copyright 2003-2020 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: mc12345678 2020 Sep 29 Modified in v1.5.7a $ */ if (!defined('IS_ADMIN_FLAG')) { die('Illegal Access'); } /** * Split Page Result Class * * An sql paging class, that allows for sql result to be shown over a number of pages using simple navigation system * Overhaul scheduled for subsequent release * */ class splitPageResults extends base { var $sql_query, $number_of_rows, $current_page_number, $number_of_pages, $number_of_rows_per_page, $page_name; /* class constructor */ function __construct($query, $max_rows, $count_key = '*', $page_holder = 'page', $debug = false, $countQuery = "") { global $db; $max_rows = ($max_rows == '' || $max_rows == 0) ? 20 : $max_rows; $this->sql_query = preg_replace("/\n\r|\r\n|\n|\r/", " ", $query); if ($countQuery != "") $countQuery = preg_replace("/\n\r|\r\n|\n|\r/", " ", $countQuery); $this->countQuery = ($countQuery != "") ? $countQuery : $this->sql_query; $this->page_name = $page_holder; if ($debug) { echo '<br /><br />'; echo 'original_query=' . $query . '<br /><br />'; echo 'original_count_query=' . $countQuery . '<br /><br />'; echo 'sql_query=' . $this->sql_query . '<br /><br />'; echo 'count_query=' . $this->countQuery . '<br /><br />'; } if (isset($_GET[$page_holder])) { $page = $_GET[$page_holder]; } elseif (isset($_POST[$page_holder])) { $page = $_POST[$page_holder]; } else { $page = ''; } if (empty($page) || !is_numeric($page)) $page = 1; $this->current_page_number = $page; $this->number_of_rows_per_page = $max_rows; $pos_to = strlen($this->countQuery); $query_lower = strtolower($this->countQuery); $pos_from = strpos($query_lower, ' from', 0); $pos_group_by = strpos($query_lower, ' group by', $pos_from); if (($pos_group_by < $pos_to) && ($pos_group_by != false)) $pos_to = $pos_group_by; $pos_having = strpos($query_lower, ' having', $pos_from); if (($pos_having < $pos_to) && ($pos_having != false)) $pos_to = $pos_having; $pos_order_by = strrpos($query_lower, ' order by', $pos_from); if (($pos_order_by < $pos_to) && ($pos_order_by != false)) $pos_to = $pos_order_by; if (strpos($query_lower, 'distinct') || strpos($query_lower, 'group by')) { $count_string = 'distinct ' . zen_db_input($count_key); } else { $count_string = zen_db_input($count_key); } $count_query = "select count(" . $count_string . ") as total " . substr($this->countQuery, $pos_from, ($pos_to - $pos_from)); if ($debug) { echo 'count_query=' . $count_query . '<br /><br />'; } $count = $db->Execute($count_query); $this->number_of_rows = $count->fields['total']; $this->number_of_pages = ceil($this->number_of_rows / $this->number_of_rows_per_page); if ($this->current_page_number > $this->number_of_pages) { $this->current_page_number = $this->number_of_pages; } $offset = ($this->number_of_rows_per_page * ($this->current_page_number - 1)); // fix offset error on some versions if ($offset <= 0) { $offset = 0; } $this->sql_query .= " limit " . ($offset > 0 ? $offset . ", " : '') . $this->number_of_rows_per_page; } /* class functions */ // display split-page-number-links function display_links($max_page_links, $parameters = '', $outputAsUnorderedList = false, $navElementLabel = '') { global $request_type; if ($max_page_links == '') $max_page_links = 1; if ($this->number_of_pages <= 1) return; $display_links_string = $ul_elements = ''; $counter_actual_page_links = 0; $class = ''; if (zen_not_null($parameters) && (substr($parameters, -1) != '&') && ($this->current_page_number > 1)) $parameters .= '&'; // previous button - not displayed on first page $link = '<a href="' . zen_href_link($_GET['main_page'], $parameters . ($this->current_page_number > 2 ? $this->page_name . '=' . ($this->current_page_number - 1) : ''), $request_type) . '" title="' . PREVNEXT_TITLE_PREVIOUS_PAGE . '">' . PREVNEXT_BUTTON_PREV . '</a>'; if ($this->current_page_number > 1) { $display_links_string .= $link . '&nbsp;&nbsp;'; $ul_elements .= ' <li class="pagination-previous" aria-label="' . ARIA_PAGINATION_PREVIOUS_PAGE . '">' . $link . '</li>' . "\n"; } else { // $ul_elements .= ' <li class="disabled pagination-previous">' . $link . '</li>' . "\n"; } // check if number_of_pages > $max_page_links $cur_window_num = intval($this->current_page_number / $max_page_links); if ($this->current_page_number % $max_page_links) $cur_window_num++; $max_window_num = intval($this->number_of_pages / $max_page_links); if ($this->number_of_pages % $max_page_links) $max_window_num++; // previous group of pages $link = '<a href="' . zen_href_link($_GET['main_page'], $parameters . ((($cur_window_num - 1) * $max_page_links) > 1 ? $this->page_name . '=' . (($cur_window_num - 1) * $max_page_links) : ''), $request_type) . '" title="' . sprintf(PREVNEXT_TITLE_PREV_SET_OF_NO_PAGE, $max_page_links) . '" aria-label="' . ARIA_PAGINATION_ELLIPSIS_PREVIOUS . '">...</a>'; if ($cur_window_num > 1) { $display_links_string .= $link; $ul_elements .= ' <li class="ellipsis">' . $link . '</li>' . "\n"; } else { // $ul_elements .= ' <li class="ellipsis" aria-hidden="true">' . $link . '</li>' . "\n"; } // page nn button for ($jump_to_page = 1 + (($cur_window_num - 1) * $max_page_links); ($jump_to_page <= ($cur_window_num * $max_page_links)) && ($jump_to_page <= $this->number_of_pages); $jump_to_page++) { if ($jump_to_page == $this->current_page_number) { $display_links_string .= '&nbsp;<strong class="current" aria-current="true" aria-label="' . ARIA_PAGINATION_CURRENT_PAGE . ', ' . sprintf(ARIA_PAGINATION_PAGE_NUM, $jump_to_page) . '">' . $jump_to_page . '</strong>&nbsp;'; $ul_elements .= ' <li class="current active">' . $jump_to_page . '</li>' . "\n"; $counter_actual_page_links++; } else { $link = '<a href="' . zen_href_link($_GET['main_page'], $parameters . ($jump_to_page > 1 ? $this->page_name . '=' . $jump_to_page : ''), $request_type) . '" title="' . sprintf(PREVNEXT_TITLE_PAGE_NO, $jump_to_page) . '" aria-label="' . ARIA_PAGINATION_GOTO . sprintf(ARIA_PAGINATION_PAGE_NUM, $jump_to_page) . '">' . $jump_to_page . '</a>'; $display_links_string .= '&nbsp;' . $link . '&nbsp;'; $ul_elements .= ' <li>' . $link . '</li>' . "\n"; $counter_actual_page_links++; } } // next group of pages if ($cur_window_num < $max_window_num) { $link = '<a href="' . zen_href_link($_GET['main_page'], $parameters . $this->page_name . '=' . (($cur_window_num) * $max_page_links + 1), $request_type) . '" title="' . sprintf(PREVNEXT_TITLE_NEXT_SET_OF_NO_PAGE, $max_page_links) . '" aria-label="' . ARIA_PAGINATION_ELLIPSIS_NEXT . '">...</a>'; $display_links_string .= $link . '&nbsp;'; $ul_elements .= ' <li class="ellipsis">' . $link . '</li>' . "\n"; } else { // $ul_elements .= ' <li class="ellipsis" aria-hidden="true">' . $link . '</li>' . "\n"; } // next button if (($this->current_page_number < $this->number_of_pages) && ($this->number_of_pages != 1)) { $link = '<a href="' . zen_href_link($_GET['main_page'], $parameters . 'page=' . ($this->current_page_number + 1), $request_type) . '" title="' . PREVNEXT_TITLE_NEXT_PAGE . '" aria-label="' . ARIA_PAGINATION_NEXT_PAGE . '">' . PREVNEXT_BUTTON_NEXT . '</a>'; $display_links_string .= '&nbsp;' . $link . '&nbsp;'; $ul_elements .= ' <li class="pagination-next">' . $link . '</li>' . "\n"; } else { // $ul_elements .= ' <li class="disabled pagination-next">' . $link . '</li>' . "\n"; } // if no pagination needed, return blank if ($counter_actual_page_links == 0) return; // return <nav><ul> format with a-hrefs wrapped in <li> // not setting role="navigation" because we're using a <nav> element already. if ($outputAsUnorderedList) { $aria_label = empty($navElementLabel) ? ARIA_PAGINATION_ROLE_LABEL_GENERAL : sprintf(ARIA_PAGINATION_ROLE_LABEL_FOR, zen_output_string_protected($navElementLabel)); $aria_label .= sprintf(ARIA_PAGINATION_CURRENTLY_ON, $this->current_page_number); return '<nav class="pagination" aria-label="' . $aria_label . '">' . "\n" . '<ul class="pagination">' . "\n" . $ul_elements . '</ul>' . "\n" . '</nav>'; } // return unformatted collection of a-hrefs return $display_links_string; } // display number of total products found function display_count($text_output) { $to_num = ($this->number_of_rows_per_page * $this->current_page_number); if ($to_num > $this->number_of_rows) $to_num = $this->number_of_rows; $from_num = ($this->number_of_rows_per_page * ($this->current_page_number - 1)); if ($to_num == 0) { $from_num = 0; } else { $from_num++; } if ($to_num <= 1) { // don't show count when 1 return ''; } else { return sprintf($text_output, $from_num, $to_num, $this->number_of_rows); } } public function getSqlQuery() { return $this->sql_query; } }
gpl-2.0
felopri/floristeriaabril
templates/gk_yourshop/layouts/blocks/tools/tools.php
204
<?php // No direct access. defined('_JEXEC') or die; ?> <div id="gkTools"> <a href="#" id="gkToolsInc">A+</a> <a href="#" id="gkToolsReset">A</a> <a href="#" id="gkToolsDec">A-</a> </div>
gpl-2.0
dezelin/virtualbox
src/VBox/Frontends/VirtualBox/src/wizards/newvd/UIWizardNewVDPageBasic2.cpp
6487
/* $Id$ */ /** @file * * VBox frontends: Qt4 GUI ("VirtualBox"): * UIWizardNewVDPageBasic2 class implementation */ /* * Copyright (C) 2006-2012 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /* Qt includes: */ #include <QVBoxLayout> #include <QButtonGroup> #include <QRadioButton> #include <QCheckBox> /* GUI includes: */ #include "UIWizardNewVDPageBasic2.h" #include "UIWizardNewVD.h" #include "QIRichTextLabel.h" /* COM includes: */ #include "CMediumFormat.h" UIWizardNewVDPage2::UIWizardNewVDPage2() { } qulonglong UIWizardNewVDPage2::mediumVariant() const { /* Initial value: */ qulonglong uMediumVariant = (qulonglong)KMediumVariant_Max; /* Exclusive options: */ if (m_pDynamicalButton->isChecked()) uMediumVariant = (qulonglong)KMediumVariant_Standard; else if (m_pFixedButton->isChecked()) uMediumVariant = (qulonglong)KMediumVariant_Fixed; /* Additional options: */ if (m_pSplitBox->isChecked()) uMediumVariant |= (qulonglong)KMediumVariant_VmdkSplit2G; /* Return options: */ return uMediumVariant; } void UIWizardNewVDPage2::setMediumVariant(qulonglong uMediumVariant) { /* Exclusive options: */ if (uMediumVariant & (qulonglong)KMediumVariant_Fixed) { m_pFixedButton->click(); m_pFixedButton->setFocus(); } else { m_pDynamicalButton->click(); m_pDynamicalButton->setFocus(); } /* Additional options: */ m_pSplitBox->setChecked(uMediumVariant & (qulonglong)KMediumVariant_VmdkSplit2G); } UIWizardNewVDPageBasic2::UIWizardNewVDPageBasic2() { /* Create widgets: */ QVBoxLayout *pMainLayout = new QVBoxLayout(this); { m_pDescriptionLabel = new QIRichTextLabel(this); m_pDynamicLabel = new QIRichTextLabel(this); m_pFixedLabel = new QIRichTextLabel(this); m_pSplitLabel = new QIRichTextLabel(this); QVBoxLayout *pVariantLayout = new QVBoxLayout; { m_pVariantButtonGroup = new QButtonGroup(this); { m_pDynamicalButton = new QRadioButton(this); { m_pDynamicalButton->click(); m_pDynamicalButton->setFocus(); } m_pFixedButton = new QRadioButton(this); m_pVariantButtonGroup->addButton(m_pDynamicalButton, 0); m_pVariantButtonGroup->addButton(m_pFixedButton, 1); } m_pSplitBox = new QCheckBox(this); pVariantLayout->addWidget(m_pDynamicalButton); pVariantLayout->addWidget(m_pFixedButton); pVariantLayout->addWidget(m_pSplitBox); } pMainLayout->addWidget(m_pDescriptionLabel); pMainLayout->addWidget(m_pDynamicLabel); pMainLayout->addWidget(m_pFixedLabel); pMainLayout->addWidget(m_pSplitLabel); pMainLayout->addLayout(pVariantLayout); pMainLayout->addStretch(); } /* Setup connections: */ connect(m_pVariantButtonGroup, SIGNAL(buttonClicked(QAbstractButton *)), this, SIGNAL(completeChanged())); connect(m_pSplitBox, SIGNAL(stateChanged(int)), this, SIGNAL(completeChanged())); /* Register fields: */ registerField("mediumVariant", this, "mediumVariant"); } void UIWizardNewVDPageBasic2::retranslateUi() { /* Translate page: */ setTitle(UIWizardNewVD::tr("Storage on physical hard drive")); /* Translate widgets: */ m_pDescriptionLabel->setText(UIWizardNewVD::tr("Please choose whether the new virtual hard drive file should grow as it is used " "(dynamically allocated) or if it should be created at its maximum size (fixed size).")); m_pDynamicLabel->setText(UIWizardNewVD::tr("<p>A <b>dynamically allocated</b> hard drive file will only use space " "on your physical hard drive as it fills up (up to a maximum <b>fixed size</b>), " "although it will not shrink again automatically when space on it is freed.</p>")); m_pFixedLabel->setText(UIWizardNewVD::tr("<p>A <b>fixed size</b> hard drive file may take longer to create on some " "systems but is often faster to use.</p>")); m_pSplitLabel->setText(UIWizardNewVD::tr("<p>You can also choose to <b>split</b> the hard drive file into several files " "of up to two gigabytes each. This is mainly useful if you wish to store the " "virtual machine on removable USB devices or old systems, some of which cannot " "handle very large files.")); m_pDynamicalButton->setText(UIWizardNewVD::tr("&Dynamically allocated")); m_pFixedButton->setText(UIWizardNewVD::tr("&Fixed size")); m_pSplitBox->setText(UIWizardNewVD::tr("&Split into files of less than 2GB")); } void UIWizardNewVDPageBasic2::initializePage() { /* Translate page: */ retranslateUi(); /* Setup visibility: */ CMediumFormat mediumFormat = field("mediumFormat").value<CMediumFormat>(); ULONG uCapabilities = mediumFormat.GetCapabilities(); bool fIsCreateDynamicPossible = uCapabilities & KMediumFormatCapabilities_CreateDynamic; bool fIsCreateFixedPossible = uCapabilities & KMediumFormatCapabilities_CreateFixed; bool fIsCreateSplitPossible = uCapabilities & KMediumFormatCapabilities_CreateSplit2G; m_pDynamicLabel->setHidden(!fIsCreateDynamicPossible); m_pDynamicalButton->setHidden(!fIsCreateDynamicPossible); m_pFixedLabel->setHidden(!fIsCreateFixedPossible); m_pFixedButton->setHidden(!fIsCreateFixedPossible); m_pSplitLabel->setHidden(!fIsCreateSplitPossible); m_pSplitBox->setHidden(!fIsCreateSplitPossible); } bool UIWizardNewVDPageBasic2::isComplete() const { /* Make sure medium variant is correct: */ return mediumVariant() != (qulonglong)KMediumVariant_Max; }
gpl-2.0
gemol/Ecommerce
MrCMS.Web/Apps/Ecommerce/Areas/Admin/Services/ISetETagService.cs
747
using MrCMS.Web.Apps.Ecommerce.Entities.ETags; using MrCMS.Web.Apps.Ecommerce.Entities.Products; namespace MrCMS.Web.Apps.Ecommerce.Areas.Admin.Services { public interface ISetETagService { void SetETag(ProductVariant productVariant, int eTag); } public class SetETagService : ISetETagService { private readonly IETagAdminService _eTagAdminService; public SetETagService(IETagAdminService eTagAdminService) { _eTagAdminService = eTagAdminService; } public void SetETag(ProductVariant productVariant, int eTag) { var tag = _eTagAdminService.GetById(eTag); if(tag != null) productVariant.ETag = tag; } } }
gpl-2.0
nizaranand/APC
apc-apps/apc-mlsdownload/common/rendering/statsFormatter.php
17001
<?php // Copyright (C) 2003-2010 National Association of REALTORS(R) // // All rights reserved. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished // to do so, provided that the above copyright notice(s) and this // permission notice appear in all copies of the Software and that // both the above copyright notice(s) and this permission notice // appear in supporting documentation. class StatsFormatter { var $STYLIST; function StatsFormatter() { $this->STYLIST = new Stylist(); } function render($model, $CONFIGURATION) { $perf_table = null; if ($CONFIGURATION->getBooleanValue("DISPLAY_PERFORMANCE")) { $perf_table = "\r\n" . "<!-- Performance Table -->\r\n" . $this->startTable("Performance Analysis") . " <tr align=\"center\">\r\n" . " <td>\r\n" . $this->renderRuntimeIdentification($CONFIGURATION) . "\r\n" . $this->renderRuntimePerformance($model) . "\r\n" . $this->STYLIST->formatColumnSeparation() . $this->renderSourceSettings($CONFIGURATION) . "\r\n" . $this->renderQuerySettings($CONFIGURATION) . "\r\n" . " </td>\r\n" . " </tr>\r\n" . $this->endTable() . "<!-- Performance Table -->\r\n"; } $display_table = null; if ($CONFIGURATION->getBooleanValue("DISPLAY_RETS")) { $display_table = "\r\n" . "<!-- RETS Table -->\r\n" . $this->startTable("RETS Transactions") . $this->renderRETS("LOGIN", $model) . $this->renderRETS("ACTION", $model) . $this->renderRETS("SEARCH", $model) . $this->renderRETS("GETMETADATA", $model) . $this->renderRETS("GETOBJECT", $model) . $this->renderRETS("LOGOUT", $model) . $this->endTable() . "<!-- RETS Table -->\r\n"; } $provider_table = null; if ($CONFIGURATION->getBooleanValue("DISPLAY_PROVIDER_NOTICE")) { $notice = $model->member->getNotice(); if (strlen($notice) > 0) { $BROWSER = new BrowserProxy(); $page = $BROWSER->render($notice); } else { $page = $this->STYLIST->formatBoldBuiltinText("No Provder Notice was Sent", BUILTIN_TABLE_TEXT_COLOR); } $provider_table = "\r\n" . "<!-- Provider Notice Table -->\r\n" . $this->startTable("Provider Notice") . " <tr align=\"center\">\r\n" . " <td>\r\n" . $page . " </td>\r\n" . " </tr>\r\n" . $this->endTable() . "<!-- Provider Notice Table -->\r\n"; } $account_table = null; if ($CONFIGURATION->getBooleanValue("DISPLAY_ACCOUNT")) { $account_table = "\r\n" . "<!-- Account Table -->\r\n" . $this->startTable("Provider Information") . " <tr align=\"center\">\r\n" . " <td>\r\n" . $this->startSubTable("Account Information") . $this->renderCellHeadings("Type", "Value") . $this->renderRETSCell("Account Number", $model->member->account, true) . $this->renderRETSCell("Member Name", $model->member->name, true) . $this->renderRETSCell("Agent ID", $model->member->agentID, true) . $this->renderRETSCell("Broker ID", $model->member->brokerID, true) . $this->renderRETSCell("User Agent", $model->getUserAgent(), true) . $this->endSubTable() . " </td>\r\n" . " </tr>\r\n" . $this->endTable() . "<!-- Account Table -->\r\n"; } return $perf_table . $display_table . $provider_table . $account_table; } function startTable($name) { return "<br/>\r\n" . "<table align=\"center\" cellspacing=\"" . BUILTIN_SPACING . "\" cellpadding=\"" . BUILTIN_PADDING . "\" border=\"" . BUILTIN_BORDER . "\" bgcolor=\"" . BUILTIN_BACK_COLOR . "\">\r\n" . " <tr align=\"center\">\r\n" . " <td colspan=\"2\" bgcolor=\"" . BUILTIN_HEADER_BACK_COLOR . "\">\r\n" . $this->STYLIST->formatBoldBuiltinText($name, BUILTIN_HEADER_TEXT_COLOR) . "\r\n" . " </td>\r\n" . " </tr>\r\n"; } function endTable() { return "</table>\r\n"; } function renderRETS($trans_type, $model) { if ($model->urls[$trans_type] && $model->rt[$trans_type] > 0) { // // get the arguments used for this call // $args = $model->getArgs($trans_type); $body = null; if (is_array($args)) { foreach ($args as $key => $val) { if (strlen($key) < 4) { $key = "ARGS CALL " . $key; } $body .= $this->renderRETSCell($key, urldecode($val)); } } else { $body .= $this->renderRETSCell("ARGS", $args); } return " <tr align=\"center\">\r\n" . " <td>\r\n" . $this->startSubTable($trans_type) . $this->renderCellHeadings("Type", "Value") . $this->renderRETSCell("URL", $model->urls[$trans_type]) . $body . $this->endSubTable() . " </td>\r\n" . " </tr>\r\n"; } return null; } function renderRETSCell($name, $value, $show_default = false) { if ($show_default & !$value) { $value = "n/a"; } if ($value) { return " <tr align=\"left\">\r\n" . " <td>\r\n" . $this->formatDisplayField($name, $value, BUILTIN_TABLE_TEXT_COLOR) . "\r\n" . " </td>\r\n" . " </tr>\r\n"; } return null; } function startSubTable($name) { return "<table align=\"center\" cellspacing=\"" . BUILTIN_SPACING . "\" cellpadding=\"" . BUILTIN_PADDING . "\">\r\n" . " <tr align=\"center\">\r\n" . " <td>\r\n" . $this->STYLIST->formatBoldBuiltinText($name, BUILTIN_TABLE_TEXT_COLOR) . "\r\n" . " </td>\r\n" . " </tr>\r\n" . " <tr align=\"center\">\r\n" . " <td>\r\n" . "<table align=\"center\" cellspacing=\"" . BUILTIN_SPACING . "\" cellpadding=\"" . BUILTIN_PADDING . "\" border=\"" . BUILTIN_BORDER . "\" bgcolor=\"" . BUILTIN_TABLE_BACK_COLOR . "\">\r\n"; } function endSubTable() { return "</table>\r\n" . " </td>\r\n" . " </tr>\r\n" . "</table>\r\n"; } function renderSourceSettings($CONFIGURATION) { return $this->startSubTable("Source Parameters") . $this->renderCellHeadings("Setting", "Value") . $this->renderBooleanCell($CONFIGURATION, "COMPACT_DECODED_FORMAT") . $this->renderBooleanCell($CONFIGURATION, "SIMULTANEOUS_LOGINS") . $this->renderBooleanCell($CONFIGURATION, "MEDIA_LOCATION") . $this->renderBooleanCell($CONFIGURATION, "MEDIA_MULTIPART") . $this->renderBooleanCell($CONFIGURATION, "TRANSLATE_DESCRIPTIONS") . $this->endSubTable(); } function renderQuerySettings($CONFIGURATION) { return $this->startSubTable("Query Parameters") . $this->renderCellHeadings("Setting", "Value") . $this->renderStringCell($CONFIGURATION, "UNIQUE_KEY") . $this->renderStringCell($CONFIGURATION, "DATE_VARIABLE") . $this->renderStringCell($CONFIGURATION, "OWNERSHIP_VARIABLE") . $this->renderStringCell($CONFIGURATION, "MEDIA_TYPE") . $this->renderStringCell($CONFIGURATION, "SELECTION_RESOURCE") . $this->renderStringCell($CONFIGURATION, "SELECTION_CLASS") . $this->endSubTable(); } function renderStringCell($CONFIGURATION, $name) { return " <tr align=\"left\">\r\n" . " <td>\r\n" . $this->formatDisplayField($name, $CONFIGURATION->getValue($name), BUILTIN_TABLE_TEXT_COLOR) . " </td>\r\n" . " </tr>\r\n"; } function renderBooleanCell($CONFIGURATION, $name) { $v = "FALSE"; if ($CONFIGURATION->getBooleanValue($name)) { $v = "TRUE"; } return " <tr align=\"left\">\r\n" . " <td>\r\n" . $this->formatDisplayField($name, $v, BUILTIN_TABLE_TEXT_COLOR) . " </td>\r\n" . " </tr>\r\n"; } function renderRuntimeIdentification($CONFIGURATION) { return $this->startSubTable("Server") . $this->renderCellHeadings("Attribute", "Description") . $this->renderStringCell($CONFIGURATION, "DETECTED_SERVER_NAME") . $this->renderStringCell($CONFIGURATION, "DETECTED_DEFAULT_RETS_VERSION") . $this->renderStringCell($CONFIGURATION, "DETECTED_MAXIMUM_RETS_VERSION") . $this->renderStringCell($CONFIGURATION, "DETECTED_STANDARD_NAMES") . $this->endSubTable(); } function renderRuntimePerformance($model) { return $this->startSubTable("Timestamps") . $this->renderCellHeadings("Function", "Time (ms)") . $this->renderRuntimeCell("Login", $model->rt["LOGIN"]) . $this->renderRuntimeCell("Action", $model->rt["ACTION"]) . $this->renderRuntimeCell("Search", $model->rt["SEARCH"]) . $this->renderRuntimeCell("GetMetadata", $model->rt["GETMETADATA"]) . $this->renderRuntimeCell("GetObject", $model->rt["GETOBJECT"]) . $this->renderRuntimeCell("Logout", $model->rt["LOGOUT"]) . $this->renderRuntimeCell("Total Execution", $model->rt["TOTAL"]) . $this->endSubTable(); } function renderRuntimeCell($name, $value) { if ($value > 0) { return " <tr align=\"left\">\r\n" . " <td>\r\n" . $this->formatDisplayField($name, number_format($value, 3), BUILTIN_TABLE_TEXT_COLOR) . " </td>\r\n" . " </tr>\r\n"; } return null; } function renderTextCell($name, $value) { return " <tr align=\"center\">\r\n" . " <td>\r\n" . $this->STYLIST->formatBuiltinText($name, BUILTIN_TABLE_TEXT_COLOR) . "\r\n" . $this->STYLIST->formatColumnSeparation() . $this->STYLIST->formatBuiltinText($value, BUILTIN_TABLE_TEXT_COLOR) . "\r\n" . " </td>\r\n" . " </tr>\r\n"; } function renderCellHeadings($name, $value) { return " <tr align=\"center\">\r\n" . " <td>\r\n" . $this->STYLIST->formatBoldBuiltinText($name, BUILTIN_TABLE_TEXT_COLOR) . "\r\n" . $this->STYLIST->formatColumnSeparation() . $this->STYLIST->formatBoldBuiltinText($value, BUILTIN_TABLE_TEXT_COLOR) . "\r\n" . " </td>\r\n" . " </tr>\r\n"; } function formatDisplayField($visible_name, $value, $override_color = null) { return $this->STYLIST->formatBoldBuiltinText($visible_name, $override_color) . "\r\n" . $this->STYLIST->formatColumnSeparation() . $this->STYLIST->formatBuiltinText($value, $override_color); } } ?>
gpl-2.0
EuroPlusFinance/Software
QuantLib-1.4/ql/handle.hpp
7366
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file handle.hpp \brief Globally accessible relinkable pointer */ #ifndef quantlib_handle_hpp #define quantlib_handle_hpp #include <ql/patterns/observable.hpp> namespace QuantLib { //! Shared handle to an observable /*! All copies of an instance of this class refer to the same observable by means of a relinkable smart pointer. When such pointer is relinked to another observable, the change will be propagated to all the copies. \pre Class T must inherit from Observable */ template <class T> class Handle { protected: class Link : public Observable, public Observer { public: explicit Link(const boost::shared_ptr<T>& h, bool registerAsObserver); void linkTo(const boost::shared_ptr<T>&, bool registerAsObserver); bool empty() const { return !h_; } const boost::shared_ptr<T>& currentLink() const { return h_; } void update() { notifyObservers(); } private: boost::shared_ptr<T> h_; bool isObserver_; }; boost::shared_ptr<Link> link_; public: /*! \name Constructors \warning <tt>registerAsObserver</tt> is left as a backdoor in case the programmer cannot guarantee that the object pointed to will remain alive for the whole lifetime of the handle---namely, it should be set to <tt>false</tt> when the passed shared pointer does not own the pointee (this should only happen in a controlled environment, so that the programmer is aware of it). Failure to do so can very likely result in a program crash. If the programmer does want the handle to register as observer of such a shared pointer, it is his responsibility to ensure that the handle gets destroyed before the pointed object does. */ //@{ explicit Handle(const boost::shared_ptr<T>& p = boost::shared_ptr<T>(), bool registerAsObserver = true) : link_(new Link(p,registerAsObserver)) {} /*! \deprecated */ QL_DEPRECATED explicit Handle(T* p, bool registerAsObserver = true) : link_(new Link(boost::shared_ptr<T>(p),registerAsObserver)) {} //@} //! dereferencing const boost::shared_ptr<T>& currentLink() const; const boost::shared_ptr<T>& operator->() const; const boost::shared_ptr<T>& operator*() const; //! checks if the contained shared pointer points to anything bool empty() const; //! allows registration as observable operator boost::shared_ptr<Observable>() const; //! equality test template <class U> bool operator==(const Handle<U>& other) { return link_==other.link_; } //! disequality test template <class U> bool operator!=(const Handle<U>& other) { return link_!=other.link_; } //! strict weak ordering template <class U> bool operator<(const Handle<U>& other) { return link_ < other.link_; } }; //! Relinkable handle to an observable /*! An instance of this class can be relinked so that it points to another observable. The change will be propagated to all handles that were created as copies of such instance. \pre Class T must inherit from Observable \warning see the Handle documentation for issues relatives to <tt>registerAsObserver</tt>. */ template <class T> class RelinkableHandle : public Handle<T> { public: explicit RelinkableHandle( const boost::shared_ptr<T>& p = boost::shared_ptr<T>(), bool registerAsObserver = true); explicit RelinkableHandle( T* p, bool registerAsObserver = true); void linkTo(const boost::shared_ptr<T>&, bool registerAsObserver = true); }; // inline definitions template <class T> inline Handle<T>::Link::Link(const boost::shared_ptr<T>& h, bool registerAsObserver) : isObserver_(false) { linkTo(h,registerAsObserver); } template <class T> inline void Handle<T>::Link::linkTo(const boost::shared_ptr<T>& h, bool registerAsObserver) { if ((h != h_) || (isObserver_ != registerAsObserver)) { if (h_ && isObserver_) unregisterWith(h_); h_ = h; isObserver_ = registerAsObserver; if (h_ && isObserver_) registerWith(h_); notifyObservers(); } } template <class T> inline const boost::shared_ptr<T>& Handle<T>::currentLink() const { QL_REQUIRE(!empty(), "empty Handle cannot be dereferenced"); return link_->currentLink(); } template <class T> inline const boost::shared_ptr<T>& Handle<T>::operator->() const { QL_REQUIRE(!empty(), "empty Handle cannot be dereferenced"); return link_->currentLink(); } template <class T> inline const boost::shared_ptr<T>& Handle<T>::operator*() const { QL_REQUIRE(!empty(), "empty Handle cannot be dereferenced"); return link_->currentLink(); } template <class T> inline bool Handle<T>::empty() const { return link_->empty(); } template <class T> inline Handle<T>::operator boost::shared_ptr<Observable>() const { return link_; } template <class T> inline RelinkableHandle<T>::RelinkableHandle(const boost::shared_ptr<T>& p, bool registerAsObserver) : Handle<T>(p,registerAsObserver) {} template <class T> inline RelinkableHandle<T>::RelinkableHandle(T* p, bool registerAsObserver) : Handle<T>(p,registerAsObserver) {} template <class T> inline void RelinkableHandle<T>::linkTo(const boost::shared_ptr<T>& h, bool registerAsObserver) { this->link_->linkTo(h,registerAsObserver); } } #endif
gpl-2.0
0svald/icingaweb2
modules/monitoring/application/controllers/DowntimeController.php
3967
<?php /* Icinga Web 2 | (c) 2015 Icinga Development Team | GPLv2+ */ namespace Icinga\Module\Monitoring\Controllers; use Icinga\Module\Monitoring\Controller; use Icinga\Module\Monitoring\Forms\Command\Object\DeleteDowntimeCommandForm; use Icinga\Module\Monitoring\Object\Host; use Icinga\Module\Monitoring\Object\Service; use Icinga\Web\Url; use Icinga\Web\Widget\Tabextension\DashboardAction; use Icinga\Web\Widget\Tabextension\MenuAction; /** * Display detailed information about a downtime */ class DowntimeController extends Controller { /** * The fetched downtime * * @var object */ protected $downtime; /** * Fetch the downtime matching the given id and add tabs */ public function init() { $downtimeId = $this->params->getRequired('downtime_id'); $query = $this->backend->select()->from('downtime', array( 'id' => 'downtime_internal_id', 'objecttype' => 'object_type', 'comment' => 'downtime_comment', 'author_name' => 'downtime_author_name', 'start' => 'downtime_start', 'scheduled_start' => 'downtime_scheduled_start', 'scheduled_end' => 'downtime_scheduled_end', 'end' => 'downtime_end', 'duration' => 'downtime_duration', 'is_flexible' => 'downtime_is_flexible', 'is_fixed' => 'downtime_is_fixed', 'is_in_effect' => 'downtime_is_in_effect', 'entry_time' => 'downtime_entry_time', 'name' => 'downtime_name', 'host_state', 'service_state', 'host_name', 'service_description', 'host_display_name', 'service_display_name' ))->where('downtime_internal_id', $downtimeId); $this->applyRestriction('monitoring/filter/objects', $query); if (false === $this->downtime = $query->fetchRow()) { $this->httpNotFound($this->translate('Downtime not found')); } $this->getTabs()->add( 'downtime', array( 'icon' => 'plug', 'label' => $this->translate('Downtime'), 'title' => $this->translate('Display detailed information about a downtime.'), 'url' =>'monitoring/downtimes/show' ) )->activate('downtime')->extend(new DashboardAction())->extend(new MenuAction()); } /** * Display the detail view for a downtime */ public function showAction() { $isService = isset($this->downtime->service_description); $this->view->downtime = $this->downtime; $this->view->isService = $isService; $this->view->listAllLink = Url::fromPath('monitoring/list/downtimes'); $this->view->showHostLink = Url::fromPath('monitoring/host/show')->setParam('host', $this->downtime->host_name); $this->view->showServiceLink = Url::fromPath('monitoring/service/show') ->setParam('host', $this->downtime->host_name) ->setParam('service', $this->downtime->service_description); $this->view->stateName = $isService ? Service::getStateText($this->downtime->service_state) : Host::getStateText($this->downtime->host_state); if ($this->hasPermission('monitoring/command/downtime/delete')) { $form = new DeleteDowntimeCommandForm(); $form ->populate(array( 'downtime_id' => $this->downtime->id, 'downtime_is_service' => $isService, 'downtime_name' => $this->downtime->name, 'redirect' => Url::fromPath('monitoring/list/downtimes'), )) ->handleRequest(); $this->view->delDowntimeForm = $form; } } }
gpl-2.0
sjarvela/mollify
backend/plugin/FileViewerEditor/viewers/Google/Google.viewer.php
852
<?php class GoogleViewer extends ViewerBase { public function getInfo($item) { return array( "embedded" => $this->getDataUrl($item, "embedded"), "full" => $this->getGoogleViewerUrl($item, TRUE) ); } public function processDataRequest($item, $path) { if (count($path) != 1 and $path[0] != 'embedded') throw $this->invalidRequestException(); $html = '<iframe id="google-viewer" src="'.$this->getGoogleViewerUrl($item, FALSE).'" style="border: none;"></iframe>'; $this->response()->success(array( "html" => $html, "resized_element_id" => "google-viewer", "size" => "600;400" )); } private function getGoogleViewerUrl($item, $full = FALSE) { $url = $this->getContentUrl($item, TRUE); return 'http://docs.google.com/viewer?url='.urlencode($url).($full ? '' : '&embedded=true'); } } ?>
gpl-2.0
elkuku/jfw-linkedin-api
src/OAuth.php
3603
<?php /** * Part of the Joomla Framework Linkedin Package * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Linkedin; use Joomla\OAuth1\Client; use Joomla\Registry\Registry; use Joomla\Http\Http; use Joomla\Http\Response; use Joomla\Input\Input; use Joomla\Application\AbstractWebApplication; /** * Joomla Framework class for generating Linkedin API access token. * * @since 1.0 */ class OAuth extends Client { /** * @var Registry Options for the \Joomla\Linkedin\OAuth object. * @since 1.0 */ protected $options; /** * Constructor. * * @param Registry $options OAuth options object. * @param Http $client The HTTP client object. * @param Input $input The Input object * @param AbstractWebApplication $application The application object. * * @since 1.0 */ public function __construct(Registry $options, Http $client, Input $input, AbstractWebApplication $application) { $this->options = $options; $this->options->def('accessTokenURL', 'https://www.linkedin.com/uas/oauth/accessToken'); $this->options->def('authenticateURL', 'https://www.linkedin.com/uas/oauth/authenticate'); $this->options->def('authoriseURL', 'https://www.linkedin.com/uas/oauth/authorize'); $this->options->def('requestTokenURL', 'https://www.linkedin.com/uas/oauth/requestToken'); // Call the OAuth1 Client constructor to setup the object. parent::__construct($this->options, $client, $input, $application); } /** * Method to verify if the access token is valid by making a request to an API endpoint. * * @return boolean Returns true if the access token is valid and false otherwise. * * @since 1.0 */ public function verifyCredentials() { $token = $this->getToken(); // Set parameters. $parameters = array( 'oauth_token' => $token['key'] ); $data['format'] = 'json'; // Set the API url. $path = 'https://api.linkedin.com/v1/people::(~)'; // Send the request. $response = $this->oauthRequest($path, 'GET', $parameters, $data); // Verify response if ($response->code == 200) { return true; } else { return false; } } /** * Method to validate a response. * * @param string $url The request URL. * @param Response $response The response to validate. * * @return void * * @since 1.0 * @throws \DomainException */ public function validateResponse($url, $response) { if (!$code = $this->getOption('success_code')) { $code = 200; } if (strpos($url, '::(~)') === false && $response->code != $code) { if ($error = json_decode($response->body)) { throw new \DomainException('Error code ' . $error->errorCode . ' received with message: ' . $error->message . '.'); } else { throw new \DomainException($response->body); } } } /** * Method used to set permissions. * * @param mixed $scope String or an array of string containing permissions. * * @return OAuth This object for method chaining * * @see https://developer.linkedin.com/documents/authentication * @since 1.0 */ public function setScope($scope) { $this->setOption('scope', $scope); return $this; } /** * Method to get the current scope * * @return string String or an array of string containing permissions. * * @since 1.0 */ public function getScope() { return $this->getOption('scope'); } }
gpl-2.0
yuuyama/vccw-wp-orange
wp-content/plugins/wp-total-hacks/wp-total-hacks.php
12558
<?php /* Plugin Name: WP Total Hacks Author: Takayuki Miyauchi Plugin URI: https://github.com/miya0001/wp-total-hacks Description: WP Total Hacks can customize your WordPress. Version: 1.9.2 Author URI: http://wpist.me/ Domain Path: /languages Text Domain: wp-total-hacks */ new TotalHacks(); class TotalHacks { private $option_params = array( 'wfb_google_analytics' => 'text', 'wfb_favicon' => 'url', 'wfb_admin_favicon' => 'bool', 'wfb_apple_icon' => 'url', 'wfb_apple_icon_precomposed' => 'bool', 'wfb_hide_version' => 'bool', 'wfb_google' => 'text', 'wfb_bing' => 'text', 'wfb_hide_custom_fields' => 'bool', 'wfb_revision' => 'int', 'wfb_selfping' => 'bool', 'wfb_widget' => 'array', 'wfb_custom_logo' => 'url', 'wfb_admin_footer_text' => 'html', 'wfb_login_logo' => 'url', 'wfb_login_url' => 'url', 'wfb_login_title' => 'text', 'wfb_webmaster' => 'bool', 'wfb_remove_xmlrpc' => 'bool', 'wfb_exclude_loggedin' => 'bool', 'wfb_adjacent_posts_rel_links' => 'bool', 'wfb_remove_more' => 'bool', 'wfb_pageexcerpt' => 'bool', 'wfb_postmetas' => 'array', 'wfb_pagemetas' => 'array', 'wfb_emailaddress' => 'email', 'wfb_sendername' => 'text', 'wfb_contact_methods' => 'array', 'wfb_remove_excerpt' => 'bool', 'wfb_update_notification' => 'bool', 'wfb_createpagefordraft' => 'bool', 'wfb_disallow_pingback' => 'bool', 'wfb_shortcode' => 'bool', 'wfb_oembed' => 'bool', ); public function __construct() { if (is_admin()) { require_once(dirname(__FILE__).'/includes/admin.php'); new TotalHacksAdmin( WP_PLUGIN_URL.'/'.dirname(plugin_basename(__FILE__)), $this->option_params ); } if (strlen($this->op('wfb_revision'))) { if (!defined('WP_POST_REVISIONS')) { define('WP_POST_REVISIONS', $this->op('wfb_revision')); } } add_action('init', array(&$this, 'init')); add_action('plugins_loaded', array(&$this, 'plugins_loaded')); add_action('get_header', array(&$this, 'get_header')); add_action('wp_head', array(&$this, 'wp_head')); add_action('admin_head', array(&$this, 'admin_head')); add_filter('admin_footer_text', array(&$this, 'admin_footer_text')); add_action('login_head', array(&$this, 'login_head')); add_action('admin_menu' , array(&$this, 'admin_menu')); add_filter('login_headerurl', array(&$this, 'login_headerurl')); add_filter('login_headertitle', array(&$this, 'login_headertitle')); add_action('pre_ping', array(&$this, 'pre_ping')); add_action('wp_dashboard_setup',array(&$this, 'wp_dashboard_setup')); add_filter('the_content_more_link', array(&$this, 'the_content_more_link')); add_filter('wp_mail_from', array(&$this, 'wp_mail_from')); add_filter('wp_mail_from_name', array(&$this, 'wp_mail_from_name')); add_filter('user_contactmethods', array(&$this, 'user_contactmethods')); add_filter('excerpt_more', array(&$this, 'excerpt_more')); add_filter('page_attributes_dropdown_pages_args', array(&$this, 'page_attributes_dropdown_pages_args')); add_action('save_post', array(&$this, 'save_post')); } public function save_post($id) { if ($this->op('wfb_createpagefordraft')) { $p = get_post($id); if ($p->post_type === 'page' && $p->post_status !== 'trash' && isset($p->post_parent)) { $parent_id = $p->post_parent; if ($parent_id) { $parent = get_post($parent_id); $status = array('draft', 'pending', 'future'); if (isset($parent->post_status) && in_array($parent->post_status, $status)) { remove_action('save_post', array(&$this, 'save_post')); $args = array( 'ID' => $id, 'post_status' => $parent->post_status, ); if ($parent->post_status === 'future') { $args['post_date'] = $parent->post_date; $args['post_date_gmt'] = $parent->post_date_gmt; } wp_update_post($args); add_action('save_post', array(&$this, 'save_post')); } } } } } public function page_attributes_dropdown_pages_args($args) { if ($this->op('wfb_createpagefordraft')) { $args['post_status'] = 'publish,private,draft,pending,future'; return $args; } return $args; } public function plugins_loaded() { load_plugin_textdomain( "wp-total-hacks", false, dirname(plugin_basename(__FILE__)).'/languages' ); if ($this->op('wfb_disallow_pingback')) { add_filter('xmlrpc_methods', array($this, 'xmlrpc_methods')); } if ($this->op('wfb_shortcode')) { add_filter('widget_text', 'do_shortcode'); } if ($this->op('wfb_oembed')) { global $wp_embed; add_filter( 'widget_text', array( $wp_embed, 'run_shortcode' ), 8 ); add_filter( 'widget_text', array( $wp_embed, 'autoembed'), 8 ); } } public function xmlrpc_methods($methods) { if ($this->op('wfb_disallow_pingback')) { unset($methods['pingback.ping']); } return $methods; } public function excerpt_more($str) { if ($this->op('wfb_remove_excerpt')) { return null; } return $str; } public function user_contactmethods($meth) { $del = $this->op('wfb_contact_methods'); if ($del && is_array($del)) { foreach ($meth as $m => $s) { if (in_array($m, $del)) { unset($meth[$m]); } } } return $meth; } public function wp_mail_from($str) { if ($this->op('wfb_emailaddress')) { if (preg_match("/^wordpress@/i", $str)) { return $this->op('wfb_emailaddress'); } } return $str; } public function wp_mail_from_name($str) { if ($this->op('wfb_sendername')) { if (preg_match("/^wordpress/i", $str)) { return $this->op('wfb_sendername'); } } return $str; } public function init() { if ($this->op("wfb_pageexcerpt")) { add_post_type_support('page', 'excerpt'); } } public function the_content_more_link($str) { if ($this->op('wfb_remove_more')) { $str = preg_replace('/#more-[0-9]+/i', '', $str); } return $str; } public function get_header() { if ($this->op('wfb_adjacent_posts_rel_links')) { if (is_page()) { remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); } } if ($this->op('wfb_remove_xmlrpc')) { if (!$this->op("enable_app") && !$this->op('enable_xmlrpc')) { remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'rsd_link'); } } if ($this->op('wfb_hide_version')) { remove_action('wp_head', 'wp_generator'); } } public function wp_dashboard_setup() { if ($w = $this->op('wfb_widget')) { global $wp_meta_boxes; foreach ( $wp_meta_boxes['dashboard'] as $position => $prio_boxes ) { foreach ( $prio_boxes as $priority => $boxes ) { foreach ( $boxes as $key => $array ) { if (in_array($key, $w)) { unset($wp_meta_boxes['dashboard'][$position][$priority][$key]); } } } } } } public function pre_ping(&$links) { if (!$this->op('wfb_selfping')) { return; } $home = $this->op( 'home' ); foreach ($links as $l => $link) { if (0 === strpos($link, $home)) { unset($links[$l]); } } } public function login_headerurl($url) { if ($op = $this->op('wfb_login_url')) { return $op; } else { return $url; } } public function login_headertitle($url) { if ($op = $this->op('wfb_login_title')) { return $op; } else { return $url; } } public function wp_head() { if ($this->op("wfb_google_analytics")) { if ($this->op("wfb_exclude_loggedin") && is_user_logged_in()) { } else { echo apply_filters( "wp_total_hacks_google_analytics", stripslashes( $this->op( "wfb_google_analytics" ) ) ); } } if ($this->op('wfb_favicon')) { $link = '<link rel="Shortcut Icon" type="image/x-icon" href="%s" />'."\n"; printf($link, $this->remove_scheme(esc_url($this->op("wfb_favicon")))); } if ($this->op('wfb_apple_icon')) { if ($this->op('wfb_apple_icon_precomposed')) { $link = '<link rel="apple-touch-icon-precomposed" href="%s" />'."\n"; } else { $link = '<link rel="apple-touch-icon" href="%s" />'."\n"; } printf($link, $this->remove_scheme(esc_url($this->op("wfb_apple_icon")))); } echo $this->get_meta('google-site-verification', $this->op('wfb_google')); echo $this->get_meta('msvalidate.01', $this->op('wfb_bing')); if (is_user_logged_in() && $this->op("wfb_custom_logo")) { $style = '<style type="text/css">'; $style .= '#wp-admin-bar-wp-logo > .ab-item .ab-icon{background-position: 0 0;}'; $style .= '#wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before {position: absolute; left: -1000%%;}'; $style .= '#wpadminbar > #wp-toolbar.quicklinks > #wp-admin-bar-root-default.ab-top-menu > #wp-admin-bar-wp-logo.menupop > .ab-item > .ab-icon {background-image: url(%s) !important; width: 16px; height: 16px; background-repeat: no-repeat; background-position: center center; background-size: auto; margin-top: 6px; left: 2px;}'; $style .= '</style>'; printf($style, $this->remove_scheme(esc_url($this->op("wfb_custom_logo")))); } } public function admin_head() { if ($this->op('wfb_favicon') && $this->op('wfb_admin_favicon')) { $link = '<link rel="Shortcut Icon" type="image/x-icon" href="%s" />'."\n"; printf($link, esc_url($this->op("wfb_favicon"))); } if (!$this->op("wfb_custom_logo")) { return; } $style = '<style type="text/css">'; $style .= '#wp-admin-bar-wp-logo > .ab-item .ab-icon{background-position: 0 0;}'; $style .= '#wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before {position: absolute; left: -1000%%;}'; $style .= '#wpadminbar > #wp-toolbar.quicklinks > #wp-admin-bar-root-default.ab-top-menu > #wp-admin-bar-wp-logo.menupop > .ab-item > .ab-icon {background-image: url(%s) !important; width: 16px; height: 16px; background-repeat: no-repeat; background-position: center center; background-size: auto; margin-top: 6px; left: 2px;}'; $style .= '</style>'; printf($style, $this->remove_scheme(esc_url($this->op("wfb_custom_logo")))); } private function get_meta($name, $content) { if ($name && $content) { return sprintf( '<meta name="%s" content="%s" />'."\n", $name, esc_attr($content) ); } } public function admin_footer_text($text) { if ($str = $this->op('wfb_admin_footer_text')) { return $str; } else { return $text; } } public function login_head() { if ($this->op("wfb_login_logo")) { printf( '<style type="text/css">h1 a {background-image: url(%s) !important;}#login h1 a { width: auto !important; background-size: auto !important; }</style>', $this->remove_scheme(esc_url($this->op('wfb_login_logo'))) ); } } public function admin_menu() { $metas = $this->op('wfb_postmetas'); if ($metas && is_array($metas)) { foreach ($metas as $meta) { remove_meta_box($meta, 'post', 'normal'); } } $metas = $this->op('wfb_pagemetas'); if ($metas && is_array($metas)) { foreach ($metas as $meta) { remove_meta_box($meta, 'page', 'normal'); } } if ($this->op('wfb_update_notification')) { global $user_login; get_currentuserinfo(); if (!current_user_can('update_plugins')) { remove_action('admin_notices', 'update_nag', 3); } } } private function op($key, $default = false) { $op = get_option($key, $default); if (is_array($op)) { return $op; } else { return trim(stripslashes($op)); } } private function remove_scheme($url) { return preg_replace("/^http:/", "", $url); } } ?>
gpl-2.0
btovar/cctools
parrot/src/pfs_service_s3.cc
9176
/* This software is distributed under the GNU General Public License. See the file COPYING for details. */ /* Theory of Operation: */ #include "pfs_service.h" extern "C" { #include "debug.h" #include "stringtools.h" #include "domain_name.h" #include "link.h" #include "file_cache.h" #include "password_cache.h" #include "full_io.h" #include "http_query.h" #include "hash_table.h" #include "xxmalloc.h" #include "macros.h" #include "sha1.h" #include "sleeptools.h" #include "s3client.h" #include "md5.h" } #include <unistd.h> #include <string.h> #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #include <sys/stat.h> #include <sys/statfs.h> #define HTTP_PORT 80 #define MD5_STRING_LENGTH 33 extern int pfs_main_timeout; extern int pfs_checksum_files; extern char pfs_temp_dir[]; extern struct file_cache * pfs_file_cache; extern struct password_cache * pfs_password_cache; extern void pfs_abort(); extern int pfs_cache_invalidate( pfs_name *name ); void s3_dirent_to_stat( struct s3_dirent_object *d, struct pfs_stat *s ) { s->st_dev = 1; s->st_ino = hash_string(d->key); s->st_mode = S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO; s->st_nlink = 1; s->st_uid = getuid(); s->st_gid = getgid(); s->st_rdev = 1; s->st_size = d->size; s->st_blksize = 4096; s->st_blocks = 1+d->size/512; s->st_atime = d->last_modified; s->st_mtime = d->last_modified; s->st_ctime = d->last_modified; } struct pfs_file_cache_data { char name[L_tmpnam]; unsigned char digest[MD5_STRING_LENGTH]; size_t size; }; class pfs_file_s3 : public pfs_file { private: char bucket[PFS_PATH_MAX]; char *username, *password; char *local_name; FILE *file; char modified; public: pfs_file_s3( pfs_name *n, char *ln, FILE *f ) : pfs_file(n) { local_name = ln; sscanf(name.hostport, "%[^:]:", bucket); username = strdup(pfs_password_cache->username); password = strdup(pfs_password_cache->password); modified = 0; file = f; } ~pfs_file_s3() { free(username); free(password); } virtual int close() { int result; if(!file) return -1; result = ::fclose(file); if(!result && modified) { file = NULL; return s3_put_file(local_name, name.rest, bucket, AMZ_PERM_PRIVATE, username, password); } else { return result; } } virtual pfs_ssize_t read( void *data, pfs_size_t length, pfs_off_t offset ) { pfs_ssize_t actual; fseek( file, offset, SEEK_SET ); actual = ::fread( data, 1, length, file ); return actual; } virtual pfs_ssize_t write( const void *data, pfs_size_t length, pfs_off_t offset ) { pfs_ssize_t actual; fseek( file, offset, SEEK_SET ); actual = ::fwrite( data, 1, length, file ); if(actual) modified = 1; return actual; } virtual int fstat( struct pfs_stat *buf ) { int result; struct s3_dirent_object d; result = s3_stat_file(name.rest, bucket, &d, username, password); if(!result) s3_dirent_to_stat(&d,buf); return result; } }; class pfs_service_s3 : public pfs_service { private: struct hash_table *s3_file_cache; public: pfs_service_s3() { char *endpoint; s3_file_cache = hash_table_create(0,NULL); if((endpoint = getenv("PARROT_S3_ENDPOINT"))) { s3_set_endpoint(endpoint); } } ~pfs_service_s3() { //Delete file_cache; } virtual int get_default_port() { return HTTP_PORT; } virtual pfs_file * open( pfs_name *name, int flags, mode_t mode ) { char bucket[PFS_PATH_MAX]; char path[MAX_KEY_LENGTH]; char *local_name; char local_exists; FILE *local_file = NULL; char *username, *password; if(!pfs_password_cache) { errno = EACCES; return NULL; } username = pfs_password_cache->username; password = pfs_password_cache->password; sscanf(name->hostport, "%[^:]:", bucket); sprintf(path, "%s:%s", bucket, name->rest); if( !(local_name = (char*)hash_table_lookup(s3_file_cache, path)) ) { int fd; local_name = new char[L_tmpnam]; strcpy(local_name, "local_name-XXXXXX"); fd = mkstemp(local_name); close(fd); // Ensures the local_name is reserved. hash_table_insert(s3_file_cache, path, local_name); local_exists = 1; } if(((char)(flags&O_ACCMODE) == (char)O_RDONLY) || ((char)(flags&O_ACCMODE) == (char)O_RDWR)) { struct s3_dirent_object dirent; if(local_exists) { unsigned char digest[MD5_DIGEST_LENGTH]; s3_stat_file(name->rest, bucket, &dirent, username, password); md5_file(local_name, digest); if(strcmp(dirent.digest, md5_string(digest))) local_exists = 0; } if(!local_exists) { local_exists = !s3_get_file(local_name, &dirent, name->rest, bucket, username, password); } } switch(flags&O_ACCMODE) { case O_RDONLY: if(!local_exists) local_file = NULL; else local_file = ::fopen(local_name, "rb+"); break; case O_WRONLY: local_file = ::fopen(local_name, "wb+"); break; case O_RDWR: if(!local_exists) local_file = ::fopen(local_name, "wb+"); else local_file = ::fopen(local_name, "rb+"); break; default: break; } if(local_file) { return new pfs_file_s3(name, local_name, local_file); } else { errno = EACCES; return NULL; } } pfs_dir * getdir( pfs_name *name ) { struct list *dirents; struct s3_dirent_object *d; char bucket[PFS_PATH_MAX]; if(!pfs_password_cache) { errno = EACCES; return NULL; } sscanf(name->hostport, "%[^:]:", bucket); pfs_dir *dir = new pfs_dir(name); dir->append("."); dir->append(".."); dirents = list_create(); if(s3_ls_bucket(bucket, dirents, pfs_password_cache->username, pfs_password_cache->password)) { list_delete(dirents); return dir; } while( (d = (struct s3_dirent_object*)list_pop_head(dirents)) ) { dir->append(d->key); free(d); } list_delete(dirents); return dir; } virtual int lstat( pfs_name *name, struct pfs_stat *info ) { struct s3_dirent_object d; char bucket[PFS_PATH_MAX]; if(!pfs_password_cache) { errno = EACCES; return -1; } sscanf(name->hostport, "%[^:]:", bucket); if( s3_stat_file(name->rest, bucket, &d, pfs_password_cache->username, pfs_password_cache->password) < 0 ) { errno = ENOENT; return -1; } s3_dirent_to_stat(&d,info); if(!strcmp(name->rest, "/")) info->st_mode = S_IFDIR; return 0; } virtual int stat( pfs_name *name, struct pfs_stat *info ) { struct s3_dirent_object d; char bucket[PFS_PATH_MAX]; if(!pfs_password_cache) { errno = EACCES; return -1; } sscanf(name->hostport, "%[^:]:", bucket); if( s3_stat_file(name->rest, bucket, &d, pfs_password_cache->username, pfs_password_cache->password) < 0 ) { errno = ENOENT; return -1; } s3_dirent_to_stat(&d,info); if(!strcmp(name->rest, "/")) info->st_mode = S_IFDIR; return 0; } virtual int unlink( pfs_name *name ) { char *local_name; char path[MAX_KEY_LENGTH]; int result; char bucket[PFS_PATH_MAX]; if(!pfs_password_cache) { errno = EACCES; return -1; } sscanf(name->hostport, "%[^:]:", bucket); sprintf(path, "%s:%s", bucket, name->rest); local_name = (char *)hash_table_lookup(s3_file_cache, path); if(local_name) { if(!::unlink(local_name)) { errno = EACCES; return -1; } delete local_name; hash_table_remove(s3_file_cache, path); result = s3_rm_file(name->rest, bucket, pfs_password_cache->username, pfs_password_cache->password); if(result) { errno = EACCES; return result; } return 0; } result = s3_rm_file(name->rest, bucket, pfs_password_cache->username, pfs_password_cache->password); if(result) { errno = EACCES; return result; } return 0; } virtual int access( pfs_name *name, mode_t mode ) { struct pfs_stat info; return this->stat(name,&info); } virtual int chmod( pfs_name *name, mode_t mode ) { errno = ENOSYS; return -1; } virtual int chown( pfs_name *name, uid_t uid, gid_t gid ) { errno = ENOSYS; return -1; } virtual int lchown( pfs_name *name, uid_t uid, gid_t gid ) { errno = ENOSYS; return -1; } virtual int truncate( pfs_name *name, pfs_off_t length ) { errno = ENOSYS; return -1; } virtual int utime( pfs_name *name, struct utimbuf *buf ) { errno = ENOSYS; return -1; } virtual int rename( pfs_name *oldname, pfs_name *newname ) { errno = ENOSYS; return -1; } virtual int chdir( pfs_name *name, char *newpath ) { struct pfs_stat info; if(this->stat(name,&info)==0) { if(S_ISDIR(info.st_mode)) { return 0; } else { errno = ENOTDIR; return -1; } } else { return -1; } } virtual int link( pfs_name *oldname, pfs_name *newname ) { errno = ENOSYS; return -1; } virtual int symlink( const char *linkname, pfs_name *newname ) { errno = ENOSYS; return -1; } virtual int readlink( pfs_name *name, char *buf, pfs_size_t bufsiz ) { errno = ENOSYS; return -1; } virtual int mkdir( pfs_name *name, mode_t mode ) { errno = ENOSYS; return -1; } virtual int rmdir( pfs_name *name ) { errno = ENOSYS; return -1; } }; static pfs_service_s3 pfs_service_s3_instance; pfs_service *pfs_service_s3 = &pfs_service_s3_instance; /* vim: set noexpandtab tabstop=4: */
gpl-2.0
bassmanpaul/joomla-cms
libraries/joomla/language/language.php
29592
<?php /** * @package Joomla.Platform * @subpackage Language * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Allows for quoting in language .ini files. */ define('_QQ_', '"'); /** * Languages/translation handler class * * @since 11.1 */ class JLanguage { /** * Array of JLanguage objects * * @var array * @since 11.1 */ protected static $languages = array(); /** * Debug language, If true, highlights if string isn't found. * * @var boolean * @since 11.1 */ protected $debug = false; /** * The default language, used when a language file in the requested language does not exist. * * @var string * @since 11.1 */ protected $default = 'en-GB'; /** * An array of orphaned text. * * @var array * @since 11.1 */ protected $orphans = array(); /** * Array holding the language metadata. * * @var array * @since 11.1 */ protected $metadata = null; /** * Array holding the language locale or boolean null if none. * * @var array|boolean * @since 11.1 */ protected $locale = null; /** * The language to load. * * @var string * @since 11.1 */ protected $lang = null; /** * A nested array of language files that have been loaded * * @var array * @since 11.1 */ protected $paths = array(); /** * List of language files that are in error state * * @var array * @since 11.1 */ protected $errorfiles = array(); /** * Translations * * @var array * @since 11.1 */ protected $strings = array(); /** * An array of used text, used during debugging. * * @var array * @since 11.1 */ protected $used = array(); /** * Counter for number of loads. * * @var integer * @since 11.1 */ protected $counter = 0; /** * An array used to store overrides. * * @var array * @since 11.1 */ protected $override = array(); /** * Name of the transliterator function for this language. * * @var string * @since 11.1 */ protected $transliterator = null; /** * Name of the pluralSuffixesCallback function for this language. * * @var callable * @since 11.1 */ protected $pluralSuffixesCallback = null; /** * Name of the ignoredSearchWordsCallback function for this language. * * @var callable * @since 11.1 */ protected $ignoredSearchWordsCallback = null; /** * Name of the lowerLimitSearchWordCallback function for this language. * * @var callable * @since 11.1 */ protected $lowerLimitSearchWordCallback = null; /** * Name of the uppperLimitSearchWordCallback function for this language. * * @var callable * @since 11.1 */ protected $upperLimitSearchWordCallback = null; /** * Name of the searchDisplayedCharactersNumberCallback function for this language. * * @var callable * @since 11.1 */ protected $searchDisplayedCharactersNumberCallback = null; /** * Constructor activating the default information of the language. * * @param string $lang The language * @param boolean $debug Indicates if language debugging is enabled. * * @since 11.1 */ public function __construct($lang = null, $debug = false) { $this->strings = array(); if ($lang == null) { $lang = $this->default; } $this->setLanguage($lang); $this->setDebug($debug); $filename = JPATH_BASE . "/language/overrides/$lang.override.ini"; if (file_exists($filename) && $contents = $this->parse($filename)) { if (is_array($contents)) { // Sort the underlying heap by key values to optimize merging ksort($contents, SORT_STRING); $this->override = $contents; } unset($contents); } // Look for a language specific localise class $class = str_replace('-', '_', $lang . 'Localise'); $paths = array(); if (defined('JPATH_SITE')) { // Note: Manual indexing to enforce load order. $paths[0] = JPATH_SITE . "/language/overrides/$lang.localise.php"; $paths[2] = JPATH_SITE . "/language/$lang/$lang.localise.php"; } if (defined('JPATH_ADMINISTRATOR')) { // Note: Manual indexing to enforce load order. $paths[1] = JPATH_ADMINISTRATOR . "/language/overrides/$lang.localise.php"; $paths[3] = JPATH_ADMINISTRATOR . "/language/$lang/$lang.localise.php"; } ksort($paths); $path = reset($paths); while (!class_exists($class) && $path) { if (file_exists($path)) { require_once $path; } $path = next($paths); } if (class_exists($class)) { /* Class exists. Try to find * -a transliterate method, * -a getPluralSuffixes method, * -a getIgnoredSearchWords method * -a getLowerLimitSearchWord method * -a getUpperLimitSearchWord method * -a getSearchDisplayCharactersNumber method */ if (method_exists($class, 'transliterate')) { $this->transliterator = array($class, 'transliterate'); } if (method_exists($class, 'getPluralSuffixes')) { $this->pluralSuffixesCallback = array($class, 'getPluralSuffixes'); } if (method_exists($class, 'getIgnoredSearchWords')) { $this->ignoredSearchWordsCallback = array($class, 'getIgnoredSearchWords'); } if (method_exists($class, 'getLowerLimitSearchWord')) { $this->lowerLimitSearchWordCallback = array($class, 'getLowerLimitSearchWord'); } if (method_exists($class, 'getUpperLimitSearchWord')) { $this->upperLimitSearchWordCallback = array($class, 'getUpperLimitSearchWord'); } if (method_exists($class, 'getSearchDisplayedCharactersNumber')) { $this->searchDisplayedCharactersNumberCallback = array($class, 'getSearchDisplayedCharactersNumber'); } } $this->load(); } /** * Returns a language object. * * @param string $lang The language to use. * @param boolean $debug The debug mode. * * @return JLanguage The Language object. * * @since 11.1 */ public static function getInstance($lang, $debug = false) { if (!isset(self::$languages[$lang . $debug])) { self::$languages[$lang . $debug] = new JLanguage($lang, $debug); } return self::$languages[$lang . $debug]; } /** * Translate function, mimics the php gettext (alias _) function. * * The function checks if $jsSafe is true, then if $interpretBackslashes is true. * * @param string $string The string to translate * @param boolean $jsSafe Make the result javascript safe * @param boolean $interpretBackSlashes Interpret \t and \n * * @return string The translation of the string * * @since 11.1 */ public function _($string, $jsSafe = false, $interpretBackSlashes = true) { // Detect empty string if ($string == '') { return ''; } $key = strtoupper($string); if (isset($this->strings[$key])) { $string = $this->debug ? '**' . $this->strings[$key] . '**' : $this->strings[$key]; // Store debug information if ($this->debug) { $caller = $this->getCallerInfo(); if (!array_key_exists($key, $this->used)) { $this->used[$key] = array(); } $this->used[$key][] = $caller; } } else { if ($this->debug) { $caller = $this->getCallerInfo(); $caller['string'] = $string; if (!array_key_exists($key, $this->orphans)) { $this->orphans[$key] = array(); } $this->orphans[$key][] = $caller; $string = '??' . $string . '??'; } } if ($jsSafe) { // Javascript filter $string = addslashes($string); } elseif ($interpretBackSlashes) { // Interpret \n and \t characters $string = str_replace(array('\\\\', '\t', '\n'), array("\\", "\t", "\n"), $string); } return $string; } /** * Transliterate function * * This method processes a string and replaces all accented UTF-8 characters by unaccented * ASCII-7 "equivalents". * * @param string $string The string to transliterate. * * @return string The transliteration of the string. * * @since 11.1 */ public function transliterate($string) { if ($this->transliterator !== null) { return call_user_func($this->transliterator, $string); } $string = JLanguageTransliterate::utf8_latin_to_ascii($string); $string = JString::strtolower($string); return $string; } /** * Getter for transliteration function * * @return callable The transliterator function * * @since 11.1 */ public function getTransliterator() { return $this->transliterator; } /** * Set the transliteration function. * * @param callable $function Function name or the actual function. * * @return callable The previous function. * * @since 11.1 */ public function setTransliterator($function) { $previous = $this->transliterator; $this->transliterator = $function; return $previous; } /** * Returns an array of suffixes for plural rules. * * @param integer $count The count number the rule is for. * * @return array The array of suffixes. * * @since 11.1 */ public function getPluralSuffixes($count) { if ($this->pluralSuffixesCallback !== null) { return call_user_func($this->pluralSuffixesCallback, $count); } else { return array((string) $count); } } /** * Getter for pluralSuffixesCallback function. * * @return callable Function name or the actual function. * * @since 11.1 */ public function getPluralSuffixesCallback() { return $this->pluralSuffixesCallback; } /** * Set the pluralSuffixes function. * * @param callable $function Function name or actual function. * * @return callable The previous function. * * @since 11.1 */ public function setPluralSuffixesCallback($function) { $previous = $this->pluralSuffixesCallback; $this->pluralSuffixesCallback = $function; return $previous; } /** * Returns an array of ignored search words * * @return array The array of ignored search words. * * @since 11.1 */ public function getIgnoredSearchWords() { if ($this->ignoredSearchWordsCallback !== null) { return call_user_func($this->ignoredSearchWordsCallback); } else { return array(); } } /** * Getter for ignoredSearchWordsCallback function. * * @return callable Function name or the actual function. * * @since 11.1 */ public function getIgnoredSearchWordsCallback() { return $this->ignoredSearchWordsCallback; } /** * Setter for the ignoredSearchWordsCallback function * * @param callable $function Function name or actual function. * * @return callable The previous function. * * @since 11.1 */ public function setIgnoredSearchWordsCallback($function) { $previous = $this->ignoredSearchWordsCallback; $this->ignoredSearchWordsCallback = $function; return $previous; } /** * Returns a lower limit integer for length of search words * * @return integer The lower limit integer for length of search words (3 if no value was set for a specific language). * * @since 11.1 */ public function getLowerLimitSearchWord() { if ($this->lowerLimitSearchWordCallback !== null) { return call_user_func($this->lowerLimitSearchWordCallback); } else { return 3; } } /** * Getter for lowerLimitSearchWordCallback function * * @return callable Function name or the actual function. * * @since 11.1 */ public function getLowerLimitSearchWordCallback() { return $this->lowerLimitSearchWordCallback; } /** * Setter for the lowerLimitSearchWordCallback function. * * @param callable $function Function name or actual function. * * @return callable The previous function. * * @since 11.1 */ public function setLowerLimitSearchWordCallback($function) { $previous = $this->lowerLimitSearchWordCallback; $this->lowerLimitSearchWordCallback = $function; return $previous; } /** * Returns an upper limit integer for length of search words * * @return integer The upper limit integer for length of search words (20 if no value was set for a specific language). * * @since 11.1 */ public function getUpperLimitSearchWord() { if ($this->upperLimitSearchWordCallback !== null) { return call_user_func($this->upperLimitSearchWordCallback); } else { return 20; } } /** * Getter for upperLimitSearchWordCallback function * * @return callable Function name or the actual function. * * @since 11.1 */ public function getUpperLimitSearchWordCallback() { return $this->upperLimitSearchWordCallback; } /** * Setter for the upperLimitSearchWordCallback function * * @param callable $function Function name or the actual function. * * @return callable The previous function. * * @since 11.1 */ public function setUpperLimitSearchWordCallback($function) { $previous = $this->upperLimitSearchWordCallback; $this->upperLimitSearchWordCallback = $function; return $previous; } /** * Returns the number of characters displayed in search results. * * @return integer The number of characters displayed (200 if no value was set for a specific language). * * @since 11.1 */ public function getSearchDisplayedCharactersNumber() { if ($this->searchDisplayedCharactersNumberCallback !== null) { return call_user_func($this->searchDisplayedCharactersNumberCallback); } else { return 200; } } /** * Getter for searchDisplayedCharactersNumberCallback function * * @return callable Function name or the actual function. * * @since 11.1 */ public function getSearchDisplayedCharactersNumberCallback() { return $this->searchDisplayedCharactersNumberCallback; } /** * Setter for the searchDisplayedCharactersNumberCallback function. * * @param callable $function Function name or the actual function. * * @return callable The previous function. * * @since 11.1 */ public function setSearchDisplayedCharactersNumberCallback($function) { $previous = $this->searchDisplayedCharactersNumberCallback; $this->searchDisplayedCharactersNumberCallback = $function; return $previous; } /** * Checks if a language exists. * * This is a simple, quick check for the directory that should contain language files for the given user. * * @param string $lang Language to check. * @param string $basePath Optional path to check. * * @return boolean True if the language exists. * * @since 11.1 */ public static function exists($lang, $basePath = JPATH_BASE) { static $paths = array(); // Return false if no language was specified if (!$lang) { return false; } $path = $basePath . '/language/' . $lang; // Return previous check results if it exists if (isset($paths[$path])) { return $paths[$path]; } // Check if the language exists $paths[$path] = is_dir($path); return $paths[$path]; } /** * Loads a single language file and appends the results to the existing strings * * @param string $extension The extension for which a language file should be loaded. * @param string $basePath The basepath to use. * @param string $lang The language to load, default null for the current language. * @param boolean $reload Flag that will force a language to be reloaded if set to true. * @param boolean $default Flag that force the default language to be loaded if the current does not exist. * * @return boolean True if the file has successfully loaded. * * @since 11.1 */ public function load($extension = 'joomla', $basePath = JPATH_BASE, $lang = null, $reload = false, $default = true) { // Load the default language first if we're not debugging and a non-default language is requested to be loaded // with $default set to true if (!$this->debug && ($lang != $this->default) && $default) { $this->load($extension, $basePath, $this->default, false, true); } if (!$lang) { $lang = $this->lang; } $path = self::getLanguagePath($basePath, $lang); $internal = $extension == 'joomla' || $extension == ''; $filename = $internal ? $lang : $lang . '.' . $extension; $filename = "$path/$filename.ini"; if (isset($this->paths[$extension][$filename]) && !$reload) { // This file has already been tested for loading. $result = $this->paths[$extension][$filename]; } else { // Load the language file $result = $this->loadLanguage($filename, $extension); // Check whether there was a problem with loading the file if ($result === false && $default) { // No strings, so either file doesn't exist or the file is invalid $oldFilename = $filename; // Check the standard file name $path = self::getLanguagePath($basePath, $this->default); $filename = $internal ? $this->default : $this->default . '.' . $extension; $filename = "$path/$filename.ini"; // If the one we tried is different than the new name, try again if ($oldFilename != $filename) { $result = $this->loadLanguage($filename, $extension, false); } } } return $result; } /** * Loads a language file. * * This method will not note the successful loading of a file - use load() instead. * * @param string $filename The name of the file. * @param string $extension The name of the extension. * * @return boolean True if new strings have been added to the language * * @see JLanguage::load() * @since 11.1 */ protected function loadLanguage($filename, $extension = 'unknown') { $this->counter++; $result = false; $strings = false; if (file_exists($filename)) { $strings = $this->parse($filename); } if ($strings) { if (is_array($strings)) { // Sort the underlying heap by key values to optimize merging ksort($strings, SORT_STRING); $this->strings = array_merge($this->strings, $strings); } if (is_array($strings) && count($strings)) { // Do not bother with ksort here. Since the originals were sorted, PHP will already have chosen the best heap. $this->strings = array_merge($this->strings, $this->override); $result = true; } } // Record the result of loading the extension's file. if (!isset($this->paths[$extension])) { $this->paths[$extension] = array(); } $this->paths[$extension][$filename] = $result; return $result; } /** * Parses a language file. * * @param string $filename The name of the file. * * @return array The array of parsed strings. * * @since 11.1 */ protected function parse($filename) { if ($this->debug) { // Capture hidden PHP errors from the parsing. $php_errormsg = null; $track_errors = ini_get('track_errors'); ini_set('track_errors', true); } $contents = file_get_contents($filename); $contents = str_replace('_QQ_', '"\""', $contents); $strings = @parse_ini_string($contents); if (!is_array($strings)) { $strings = array(); } if ($this->debug) { // Restore error tracking to what it was before. ini_set('track_errors', $track_errors); // Initialise variables for manually parsing the file for common errors. $blacklist = array('YES', 'NO', 'NULL', 'FALSE', 'ON', 'OFF', 'NONE', 'TRUE'); $regex = '/^(|(\[[^\]]*\])|([A-Z][A-Z0-9_\-\.]*\s*=(\s*(("[^"]*")|(_QQ_)))+))\s*(;.*)?$/'; $this->debug = false; $errors = array(); // Open the file as a stream. $file = new SplFileObject($filename); foreach ($file as $lineNumber => $line) { // Avoid BOM error as BOM is OK when using parse_ini if ($lineNumber == 0) { $line = str_replace("\xEF\xBB\xBF", '', $line); } // Check that the key is not in the blacklist and that the line format passes the regex. $key = strtoupper(trim(substr($line, 0, strpos($line, '=')))); // Workaround to reduce regex complexity when matching escaped quotes $line = str_replace('\"', '_QQ_', $line); if (!preg_match($regex, $line) || in_array($key, $blacklist)) { $errors[] = $lineNumber; } } // Check if we encountered any errors. if (count($errors)) { if (basename($filename) != $this->lang . '.ini') { $this->errorfiles[$filename] = $filename . JText::sprintf('JERROR_PARSING_LANGUAGE_FILE', implode(', ', $errors)); } else { $this->errorfiles[$filename] = $filename . '&#160;: error(s) in line(s) ' . implode(', ', $errors); } } elseif ($php_errormsg) { // We didn't find any errors but there's probably a parse notice. $this->errorfiles['PHP' . $filename] = 'PHP parser errors :' . $php_errormsg; } $this->debug = true; } return $strings; } /** * Get a metadata language property. * * @param string $property The name of the property. * @param mixed $default The default value. * * @return mixed The value of the property. * * @since 11.1 */ public function get($property, $default = null) { if (isset($this->metadata[$property])) { return $this->metadata[$property]; } return $default; } /** * Determine who called JLanguage or JText. * * @return array Caller information. * * @since 11.1 */ protected function getCallerInfo() { // Try to determine the source if none was provided if (!function_exists('debug_backtrace')) { return null; } $backtrace = debug_backtrace(); $info = array(); // Search through the backtrace to our caller $continue = true; while ($continue && next($backtrace)) { $step = current($backtrace); $class = @ $step['class']; // We're looking for something outside of language.php if ($class != 'JLanguage' && $class != 'JText') { $info['function'] = @ $step['function']; $info['class'] = $class; $info['step'] = prev($backtrace); // Determine the file and name of the file $info['file'] = @ $step['file']; $info['line'] = @ $step['line']; $continue = false; } } return $info; } /** * Getter for Name. * * @return string Official name element of the language. * * @since 11.1 */ public function getName() { return $this->metadata['name']; } /** * Get a list of language files that have been loaded. * * @param string $extension An optional extension name. * * @return array * * @since 11.1 */ public function getPaths($extension = null) { if (isset($extension)) { if (isset($this->paths[$extension])) { return $this->paths[$extension]; } return null; } else { return $this->paths; } } /** * Get a list of language files that are in error state. * * @return array * * @since 11.1 */ public function getErrorFiles() { return $this->errorfiles; } /** * Getter for the language tag (as defined in RFC 3066) * * @return string The language tag. * * @since 11.1 */ public function getTag() { return $this->metadata['tag']; } /** * Get the RTL property. * * @return boolean True is it an RTL language. * * @since 11.1 */ public function isRTL() { return (bool) $this->metadata['rtl']; } /** * Set the Debug property. * * @param boolean $debug The debug setting. * * @return boolean Previous value. * * @since 11.1 */ public function setDebug($debug) { $previous = $this->debug; $this->debug = (boolean) $debug; return $previous; } /** * Get the Debug property. * * @return boolean True is in debug mode. * * @since 11.1 */ public function getDebug() { return $this->debug; } /** * Get the default language code. * * @return string Language code. * * @since 11.1 */ public function getDefault() { return $this->default; } /** * Set the default language code. * * @param string $lang The language code. * * @return string Previous value. * * @since 11.1 */ public function setDefault($lang) { $previous = $this->default; $this->default = $lang; return $previous; } /** * Get the list of orphaned strings if being tracked. * * @return array Orphaned text. * * @since 11.1 */ public function getOrphans() { return $this->orphans; } /** * Get the list of used strings. * * Used strings are those strings requested and found either as a string or a constant. * * @return array Used strings. * * @since 11.1 */ public function getUsed() { return $this->used; } /** * Determines is a key exists. * * @param string $string The key to check. * * @return boolean True, if the key exists. * * @since 11.1 */ public function hasKey($string) { $key = strtoupper($string); return isset($this->strings[$key]); } /** * Returns a associative array holding the metadata. * * @param string $lang The name of the language. * * @return mixed If $lang exists return key/value pair with the language metadata, otherwise return NULL. * * @since 11.1 */ public static function getMetadata($lang) { $path = self::getLanguagePath(JPATH_BASE, $lang); $file = $lang . '.xml'; $result = null; if (is_file("$path/$file")) { $result = self::parseXMLLanguageFile("$path/$file"); } if (empty($result)) { return null; } return $result; } /** * Returns a list of known languages for an area * * @param string $basePath The basepath to use * * @return array key/value pair with the language file and real name. * * @since 11.1 */ public static function getKnownLanguages($basePath = JPATH_BASE) { $dir = self::getLanguagePath($basePath); $knownLanguages = self::parseLanguageFiles($dir); return $knownLanguages; } /** * Get the path to a language * * @param string $basePath The basepath to use. * @param string $language The language tag. * * @return string language related path or null. * * @since 11.1 */ public static function getLanguagePath($basePath = JPATH_BASE, $language = null) { $dir = $basePath . '/language'; if (!empty($language)) { $dir .= '/' . $language; } return $dir; } /** * Set the language attributes to the given language. * * Once called, the language still needs to be loaded using JLanguage::load(). * * @param string $lang Language code. * * @return string Previous value. * * @since 11.1 */ public function setLanguage($lang) { $previous = $this->lang; $this->lang = $lang; $this->metadata = $this->getMetadata($this->lang); return $previous; } /** * Get the language locale based on current language. * * @return array The locale according to the language. * * @since 11.1 */ public function getLocale() { if (!isset($this->locale)) { $locale = str_replace(' ', '', isset($this->metadata['locale']) ? $this->metadata['locale'] : ''); if ($locale) { $this->locale = explode(',', $locale); } else { $this->locale = false; } } return $this->locale; } /** * Get the first day of the week for this language. * * @return integer The first day of the week according to the language * * @since 11.1 */ public function getFirstDay() { return (int) (isset($this->metadata['firstDay']) ? $this->metadata['firstDay'] : 0); } /** * Get the weekends days for this language. * * @return string The weekend days of the week separated by a comma according to the language * * @since 3.2 */ public function getWeekEnd() { return (isset($this->metadata['weekEnd']) && $this->metadata['weekEnd']) ? $this->metadata['weekEnd'] : '0,6'; } /** * Searches for language directories within a certain base dir. * * @param string $dir directory of files. * * @return array Array holding the found languages as filename => real name pairs. * * @since 11.1 */ public static function parseLanguageFiles($dir = null) { $languages = array(); $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)); foreach ($iterator as $file) { $langs = array(); $fileName = $file->getFilename(); if (!$file->isFile() || !preg_match("/^([-_A-Za-z]*)\.xml$/", $fileName)) { continue; } try { $metadata = self::parseXMLLanguageFile($file->getRealPath()); if ($metadata) { $lang = str_replace('.xml', '', $fileName); $langs[$lang] = $metadata; } $languages = array_merge($languages, $langs); } catch (RuntimeException $e) { } } return $languages; } /** * Parse XML file for language information. * * @param string $path Path to the XML files. * * @return array Array holding the found metadata as a key => value pair. * * @since 11.1 * @throws RuntimeException */ public static function parseXMLLanguageFile($path) { if (!is_readable($path)) { throw new RuntimeException('File not found or not readable'); } // Try to load the file $xml = simplexml_load_file($path); if (!$xml) { return null; } // Check that it's a metadata file if ((string) $xml->getName() != 'metafile') { return null; } $metadata = array(); foreach ($xml->metadata->children() as $child) { $metadata[$child->getName()] = (string) $child; } return $metadata; } }
gpl-2.0
techspark/citybuilder
modules/mod_bt_sociallogin/admin/formfield/profilefield.php
8549
<?php /** * @package formfield * @version 2.0 * @created April 2012 * @author BowThemes * @email support@bowthems.com * @website http://bowthemes.com * @support Forum - http://bowthemes.com/forum/ * @copyright Copyright (C) 2011 Bowthemes. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL * */ // no direct access defined('_JEXEC') or die('Restricted access'); jimport('joomla.form.formfield'); jimport('joomla.html.parameter'); jimport( 'joomla.plugin.helper' ); class JFormFieldProfilefield extends JFormField { protected $type = 'profilefield'; protected function getLabel() { return null; } function getInput(){ $formRegistration = new JForm('com_users.registration'); $formProfile = new JForm('com_users.registration'); $plugin = JPluginHelper::getPlugin('user','profile'); //load language com_user and plugin profile $language = JFactory::getLanguage(); $language_tag = $language->getTag(); JFactory::getLanguage()->load('lib_joomla',JPATH_SITE,$language_tag,true); JFactory::getLanguage()->load('com_users',JPATH_SITE,$language_tag,true); JFactory::getLanguage()->load('plg_user_profile',JPATH_ADMINISTRATOR,$language_tag,true); // Add the registration fields to the form. $formRegistration->loadFile(JPATH_ROOT.'/components/com_users/models/forms/registration.xml', false); // remove unused fiels of registrer form $formRegistration->removeField('captcha'); $formRegistration->removeField('spacer'); $formRegistration->removeField('password1'); $formRegistration->removeField('password2'); $formRegistration->removeField('email2'); //setting list box $class = $this->element['class'] ? (string) $this->element['class'] : ''; $social = $this->element['social'] ? (string) $this->element['social'] : ''; $html = '<ul class="profile-fields '.$class.'" id="'.$this->id.'" version="'.JVERSION.'">'; $options = array(); switch($social){ case 'facebook': $options[] = JHtml::_('select.option', '', JText::_('JNONE')); $options[] = JHtml::_('select.option', 'id', JText::_('ID')); $options[] = JHtml::_('select.option', 'name', 'Name'); $options[] = JHtml::_('select.option', 'username', 'Username'); $options[] = JHtml::_('select.option', 'email', 'Email'); $options[] = JHtml::_('select.option', 'link', 'Profile link'); //$options[] = JHtml::_('select.option', 'picture', 'Profile Picture'); $options[] = JHtml::_('select.option', 'birthday', 'Date of birth'); $options[] = JHtml::_('select.option', 'location', 'Location'); $options[] = JHtml::_('select.option', 'hometown', 'Hometown'); $options[] = JHtml::_('select.option', 'website', 'Website'); $options[] = JHtml::_('select.option', 'bio', 'About me'); $options[] = JHtml::_('select.option', 'quotes', 'Favorite Quotes'); break; case 'google': $options[] = JHtml::_('select.option', '', JText::_('JNONE')); $options[] = JHtml::_('select.option', 'id', JText::_('ID')); $options[] = JHtml::_('select.option', 'name', 'Name'); $options[] = JHtml::_('select.option', 'username', 'Username'); $options[] = JHtml::_('select.option', 'email', 'Email'); $options[] = JHtml::_('select.option', 'link', 'Profile link'); //$options[] = JHtml::_('select.option', 'picture', 'Profile Picture'); $options[] = JHtml::_('select.option', 'birthday', 'Date of birth'); break; case 'twitter': $options[] = JHtml::_('select.option', '', JText::_('JNONE')); $options[] = JHtml::_('select.option', 'id', JText::_('ID')); $options[] = JHtml::_('select.option', 'name', 'Name'); $options[] = JHtml::_('select.option', 'username', 'Screen Name'); $options[] = JHtml::_('select.option', 'link', 'Profile link'); //$options[] = JHtml::_('select.option', 'picture', 'Profile Picture'); $options[] = JHtml::_('select.option', 'birthday', 'Date of birth'); $options[] = JHtml::_('select.option', 'location', 'Location'); $options[] = JHtml::_('select.option', 'website', 'Website'); $options[] = JHtml::_('select.option', 'bio', 'Description'); $options[] = JHtml::_('select.option', 'status', 'Status'); break; } //add field from register form foreach ($formRegistration->getFieldsets() as $fieldset){ $fields = $formRegistration->getFieldset($fieldset->name); if (count($fields)){ foreach($fields as $field){ $html .= '<li class="control-group">'.$field->getLabel(); if($field->fieldname == 'name'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="name control-group"' , 'value', 'text', 'name'); }elseif($field->fieldname == 'username'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="username control-group"' , 'value', 'text', $social=='google'?'email':'username'); }elseif($field->fieldname == 'email1'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="email1 control-group" disabled="disabled"' , 'value', 'text', 'email'); if($social=='twitter') $html.= '<br /><span style="color:red;line-height:200%">The Twitter API does not provide the user\'s email address. So if you turn off "editing email" the twitter users will have email type: screen_name@twitter.com</span>'; } } } } //load fields of plugin profile if($plugin != null){ $params = new JRegistry(); $params->loadString($plugin->params); $formProfile->loadFile(JPATH_ROOT.'/plugins/user/profile/profiles/profile.xml', false); $fields = array( 'address1', 'address2', 'city', 'region', 'country', 'postal_code', 'website', 'favoritebook', 'aboutme', 'dob', ); //remove field unused $formProfile->removeField('tos','profile'); //$formProfile->removeField('city','profile'); //$formProfile->removeField('region','profile'); //$formProfile->removeField('country','profile'); $formProfile->removeField('postal_code','profile'); $formProfile->removeField('favoritebook','profile'); $formProfile->removeField('phone','profile'); //remove field disable in profile form foreach ($fields as $field) { if ($params->get('register-require_' . $field, 1) > 0) { $formProfile->setFieldAttribute($field, 'required', ($params->get('register-require_' . $field) == 2) ? 'required' : '', 'profile'); } else { $formProfile->removeField($field, 'profile'); } } foreach ($formProfile->getFieldsets() as $fieldset){ $fields = $formProfile->getFieldset($fieldset->name); if (count($fields)){ $html .= '<li class="control-group"><h3 class="enable_profile_1">Profile plugin:</h3></li>'; foreach($fields as $field){ $html .= '<li class="control-group">'.$field->getLabel() ; if($field->fieldname == 'address1'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="profile_address1 enable_profile_1"' , 'value', 'text', 'location'); }elseif ($field->fieldname == 'address2'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="profile_address2 enable_profile_1"' , 'value', 'text', ''); } elseif($field->fieldname == 'city'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="profile_city enable_profile_1"' , 'value', 'text', 'hometown'); } elseif($field->fieldname == 'region'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="profile_region enable_profile_1"' , 'value', 'text', ''); } elseif($field->fieldname == 'country'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="profile_country enable_profile_1"' , 'value', 'text', ''); } elseif($field->fieldname == 'website'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="profile_website enable_profile_1"' , 'value', 'text', 'website'); }elseif($field->fieldname == 'aboutme'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="profile_aboutme enable_profile_1"' , 'value', 'text', 'bio'); }elseif($field->fieldname == 'dob'){ $html .= JHtml::_('select.genericlist', $options, '', 'class="profile_dob enable_profile_1"' , 'value', 'text', 'birthday'); } } } } } $html .="</ul>"; $html .= '<input class="socialinput" type="hidden" name="'.$this->name.'" value="'.$this->value.'" />'; return $html; } }
gpl-2.0
aestetix/pn-18
sites/all/modules/commerce_braintree/braintree_php/tests/integration/SubscriptionSearchTest.php
12606
<?php require_once realpath(dirname(__FILE__)) . '/../TestHelper.php'; require_once realpath(dirname(__FILE__)) . '/SubscriptionTestHelper.php'; class Braintree_SubscriptionSearchTest extends PHPUnit_Framework_TestCase { function testSearch_planIdIs() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $trialPlan = Braintree_SubscriptionTestHelper::trialPlan(); $trialSubscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $trialPlan['id'], 'price' => '1' ))->subscription; $triallessSubscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '1' ))->subscription; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::planId()->is('integration_trial_plan'), Braintree_SubscriptionSearch::price()->is('1') )); $this->assertTrue(Braintree_TestHelper::includes($collection, $trialSubscription)); $this->assertFalse(Braintree_TestHelper::includes($collection, $triallessSubscription)); } function test_noRequestsWhenIterating() { $resultsReturned = false; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::planId()->is('imaginary') )); foreach($collection as $transaction) { $resultsReturned = true; break; } $this->assertSame(0, $collection->maximumCount()); $this->assertEquals(false, $resultsReturned); } function testSearch_inTrialPeriod() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $trialPlan = Braintree_SubscriptionTestHelper::trialPlan(); $trialSubscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $trialPlan['id'], 'price' => '1' ))->subscription; $triallessSubscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '1' ))->subscription; $subscriptions_in_trial = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::inTrialPeriod()->is(true) )); $this->assertTrue(Braintree_TestHelper::includes($subscriptions_in_trial, $trialSubscription)); $this->assertFalse(Braintree_TestHelper::includes($subscriptions_in_trial, $triallessSubscription)); $subscriptions_not_in_trial = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::inTrialPeriod()->is(false) )); $this->assertTrue(Braintree_TestHelper::includes($subscriptions_not_in_trial, $triallessSubscription)); $this->assertFalse(Braintree_TestHelper::includes($subscriptions_not_in_trial, $trialSubscription)); } function testSearch_statusIsPastDue() { $found = false; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::status()->in(array(Braintree_Subscription::PAST_DUE)) )); foreach ($collection AS $item) { $found = true; $this->assertEquals(Braintree_Subscription::PAST_DUE, $item->status); } $this->assertTrue($found); } function testSearch_statusIsExpired() { $found = false; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::status()->in(array(Braintree_Subscription::EXPIRED)) )); foreach ($collection AS $item) { $found = true; $this->assertEquals(Braintree_Subscription::EXPIRED, $item->status); } $this->assertTrue($found); } function testSearch_billingCyclesRemaing() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $subscription_4 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'numberOfBillingCycles' => 4 ))->subscription; $subscription_8 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'numberOfBillingCycles' => 8 ))->subscription; $subscription_10 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'numberOfBillingCycles' => 10 ))->subscription; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::billingCyclesRemaining()->between(5, 10) )); $this->assertFalse(Braintree_TestHelper::includes($collection, $subscription_4)); $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_8)); $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_10)); } function testSearch_subscriptionId() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $rand_id = strval(rand()); $subscription_1 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'id' => 'subscription_123_id_' . $rand_id ))->subscription; $subscription_2 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'id' => 'subscription_23_id_' . $rand_id ))->subscription; $subscription_3 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'id' => 'subscription_3_id_' . $rand_id ))->subscription; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::id()->contains("23_id_") )); $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_1)); $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_2)); $this->assertFalse(Braintree_TestHelper::includes($collection, $subscription_3)); } function testSearch_merchantAccountId() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $rand_id = strval(rand()); $subscription_1 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'id' => strval(rand()) . '_subscription_' . $rand_id, 'price' => '2' ))->subscription; $subscription_2 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'id' => strval(rand()) . '_subscription_' . $rand_id, 'merchantAccountId' => Braintree_TestHelper::nonDefaultMerchantAccountId(), 'price' => '2' ))->subscription; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::id()->endsWith('subscription_' . $rand_id), Braintree_SubscriptionSearch::merchantAccountId()->in(array(Braintree_TestHelper::nonDefaultMerchantAccountId())), Braintree_SubscriptionSearch::price()->is('2') )); $this->assertFalse(Braintree_TestHelper::includes($collection, $subscription_1)); $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_2)); } function testSearch_daysPastDue() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $subscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'] ))->subscription; Braintree_Http::put('/subscriptions/' . $subscription->id . '/make_past_due', array('daysPastDue' => 5)); $found = false; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::daysPastDue()->between(2, 10) )); foreach ($collection AS $item) { $found = true; $this->assertTrue($item->daysPastDue <= 10); $this->assertTrue($item->daysPastDue >= 2); } $this->assertTrue($found); } function testSearch_price() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $subscription_850 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '8.50' ))->subscription; $subscription_851 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '8.51' ))->subscription; $subscription_852 = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '8.52' ))->subscription; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::price()->between('8.51', '8.52') )); $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_851)); $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_852)); $this->assertFalse(Braintree_TestHelper::includes($collection, $subscription_850)); } function testSearch_nextBillingDate() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $trialPlan = Braintree_SubscriptionTestHelper::trialPlan(); $triallessSubscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], ))->subscription; $trialSubscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $trialPlan['id'], ))->subscription; $fiveDaysFromNow = new DateTime(); $fiveDaysFromNow->modify("+5 days"); $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::nextBillingDate()->greaterThanOrEqualTo($fiveDaysFromNow) )); $this->assertTrue(Braintree_TestHelper::includes($collection, $triallessSubscription)); $this->assertFalse(Braintree_TestHelper::includes($collection, $trialSubscription)); } function testSearch_transactionId() { $creditCard = Braintree_SubscriptionTestHelper::createCreditCard(); $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan(); $matchingSubscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], ))->subscription; $nonMatchingSubscription = Braintree_Subscription::create(array( 'paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], ))->subscription; $collection = Braintree_Subscription::search(array( Braintree_SubscriptionSearch::transactionId()->is($matchingSubscription->transactions[0]->id) )); $this->assertTrue(Braintree_TestHelper::includes($collection, $matchingSubscription)); $this->assertFalse(Braintree_TestHelper::includes($collection, $nonMatchingSubscription)); } }
gpl-2.0
cidesa/roraima-comunal
web/reportes/reportes/contabilidad/pdfConBalGen.php
21902
<? require_once("../../lib/general/fpdf/fpdf.php"); require_once("../../lib/bd/basedatosAdo.php"); require_once("../../lib/general/cabecera.php"); require_once("../../lib/general/funcionescontabilidad.php"); /* AYUDA: Cell(with,healt,Texto,border,linea,align,fillm-Fondo,link) AddFont(family,style,file) ln() -> Salto de Linea */ class pdfreporte extends fpdf { var $bd; var $titulos; var $titulos2; var $anchos; var $ancho; var $campos; var $codcta1; var $codcta2; var $periodo; var $auxnivel; var $auxnivel2; var $nrorup; var $comodin; var $loniv1; var $fecha_ini; var $fecha_cie; var $nivel; var $fechainicio; var $total; var $saldo; var $cuenta_resultado; var $resultado; var $Total_Resultado; function pdfreporte() { $this->fpdf("p","mm","Letter"); $this->bd=new basedatosAdo(); $this->campos=array(); $this->anchos=array(); $this->titulos=array(); $this->codcta1=$_POST["codcta1"]; $this->codcta2=$_POST["codcta2"]; $this->periodo=$_POST["periodo"]; $this->auxnivel=$_POST["auxnivel"]; $this->auxnivel2=$_POST["auxnivel2"]; $this->comodin=$_POST["comodin"]; $this->nrorup=$_POST["nrorup"]; $this->nrorup2=$_POST["nrorup2"]; $this->p_fecha=$_POST["p_fecha"]; $this->auxnivel='7'; $this->auxnivel2='7'; $this->nrorup='7'; $this->nrorup2='7'; $this->obtenerFecha(); $this->sql="SELECT A.CODCTA,A.ORDEN, A.TITULO, A.CUENTA, A.NOMBRE, A.DEBITO, A.CREDITO, --(A.SALDO) as SALDO, (A.SALDO) as SALDO, A.CARGABLE FROM (SELECT A.CODCTA, RTRIM(A.CODCTA) AS ORDEN, A.CODCTA AS TITULO, A.CODCTA AS CUENTA, B.DESCTA AS NOMBRE, A.TOTDEB AS DEBITO, A.TOTCRE AS CREDITO, A.SALACT AS SALDO, B.CARGAB AS CARGABLE,'C' FROM CONTABB1 A, CONTABB B WHERE A.CODCTA=B.CODCTA AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = ('".$this->fecha_ini."') AND A.FECCIE = ('".$this->fecha_cie."') UNION ALL SELECT A.CODCTA,RTRIM(A.CODCTA)||'T' AS ORDEN,'TOTAL' AS TITULO, A.CODCTA AS CUENTA, B.DESCTA AS NOMBRE, A.TOTDEB AS DEBITO, A.TOTCRE AS CREDITO, A.SALACT AS SALDO, B.CARGAB AS CARGABLE,'C' FROM CONTABB1 A, CONTABB B WHERE A.CODCTA=B.CODCTA AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = ('".$this->fecha_ini."') AND A.FECCIE = ('".$this->fecha_cie."') AND B.CARGAB<>'C') A, CONTABA B WHERE A.SALDO <> 0 AND ( A.CUENTA LIKE (RTRIM(B.CODTESACT)||'%') OR A.CUENTA LIKE (RTRIM(B.CODTESPAS)||'%') OR A.CUENTA LIKE (RTRIM(B.CODCTA)||'%') OR A.CUENTA LIKE (RTRIM(B.CODCTD)||'%') ) ORDER BY A.ORDEN"; // print '<pre>'; print $this->sql; exit; $this->sql2="SELECT A.CODCTA, A.ORDEN, A.TITULO, A.CUENTA, A.NOMBRE, A.DEBITO, A.CREDITO, (A.SALDO) as SALDO, A.CARGABLE FROM (SELECT A.CODCTA,RTRIM(A.CODCTA) AS ORDEN, A.CODCTA AS TITULO, A.CODCTA AS CUENTA, B.DESCTA AS NOMBRE, A.TOTDEB AS DEBITO, A.TOTCRE AS CREDITO, A.SALACT AS SALDO, B.CARGAB AS CARGABLE,'C' FROM CONTABB1 A, CONTABB B WHERE A.CODCTA=B.CODCTA AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = ('".$this->fecha_ini."') AND A.FECCIE = ('".$this->fecha_cie."') UNION ALL SELECT A.CODCTA,RTRIM(A.CODCTA)||'T' AS ORDEN,'TOTAL' AS TITULO, A.CODCTA AS CUENTA, B.DESCTA AS NOMBRE, A.TOTDEB AS DEBITO, A.TOTCRE AS CREDITO, A.SALACT AS SALDO, B.CARGAB AS CARGABLE,'C' FROM CONTABB1 A, CONTABB B WHERE A.CODCTA=B.CODCTA AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = ('".$this->fecha_ini."') AND A.FECCIE = ('".$this->fecha_cie."') AND B.CARGAB<>'C') A, CONTABA B WHERE A.SALDO <> 0 AND ( A.CUENTA LIKE (RTRIM(B.CODORD)||'%') ) ORDER BY A.ORDEN"; // print '<pre>'; print $this->sql2; exit; //print $this->sql2; $this->llenartitulosmaestro(); $this->cab=new cabecera(); } function instr($palabra,$busqueda,$comienzo,$concurrencia){ $tamano=strlen($palabra); $cont=0; $cont_conc=0; for ($i=$comienzo;$i<=$tamano;$i++){ $cont=$cont+1; if ($palabra[$i]==$busqueda): $cont_conc=$cont_conc+1; if ($cont_conc==$concurrencia): $i=$tamano; endif; endif; } if ($concurrencia > $cont_conc ): $cont=0; else: $cont; endif; return $this->instr=$cont; } function obtenerFecha() { $tb3=$this->bd->select("select fecini as fechainic, forcta as forcta from contaba"); if (!$tb3->EOF){ $this->fechainicio=$tb3->fields["fechainic"]; $this->forcta=$tb3->fields["forcta"]; } $this->valor=instr($this->forcta,'-',0,1); // $tb4=$this->bd->select("SELECT coalesce(LENGTH(SUBSTR(FORCTA,1,position('-' in FORCTA)-1)), 0) as LONIV1, $tb4=$this->bd->select("SELECT coalesce(coalesce(LENGTH(SUBSTR(FORCTA,1,".$this->valor."))-1, 0), 0) as LONIV1, FECINI as fecha_ini, FECCIE as fecha_cie, CODRES as cuenta_resultado FROM CONTABA"); if (!$tb4->EOF) { $this->loniv1=$tb4->fields["loniv1"]; $this->fecha_ini=$tb4->fields["fecha_ini"]; $this->fecha_cie=$tb4->fields["fecha_cie"]; $this->cuenta_resultado=$tb4->fields["cuenta_resultado"]; } //EndIf $tbfecper=$this->bd->select("select FECDES as fecha_ini, FECHAS as fecha_cie FROM CONTABA1 where pereje='".$this->periodo."'"); if (!$tbfecper->EOF) { $this->fecha_iniper=$tbfecper->fields["fecha_ini"]; $this->fecha_cieper=$tbfecper->fields["fecha_cie"]; } //EndIf ////// AUXNIVEL 1 //////// if ($this->auxnivel==$this->nrorup) { $tb5=$this->bd->select("SELECT coalesce(LENGTH(RTRIM(FORCTA)), 0) as nivel FROM contaba"); if (!$tb5->EOF) { $this->nivel=$tb5->fields["nivel"]; } //EndIf } //EndIf else { $this->valor=instr($this->forcta,'-',0,$this->auxnivel); //$tb5=$this->bd->select("SELECT coalesce(LENGTH(SUBSTR(FORCTA,1,position('-' in FORCTA)-1)), 0) as nivel FROM contaba"); //SELECT NVL(LENGTH(SUBSTR(FORCTA,1,INSTR(FORCTA,'-',1,:AUXnivel)-1)), 0) INTO :Nivel FROM CONTABA; $tb5=$this->bd->select("SELECT coalesce(coalesce(LENGTH(SUBSTR(FORCTA,1,'".$this->valor."'))-1, 0), 0) as nivel FROM contaba"); if (!$tb5->EOF) { $this->nivel=$tb5->fields["nivel"]; } //EndIf } //EndIf ////// AUXNIVEL 2 //////// if ($this->auxnivel2==$this->nrorup) { $tb6=$this->bd->select("SELECT coalesce(LENGTH(RTRIM(FORCTA)), 0) as nivel2 FROM contaba"); if (!$tb6->EOF) { $this->nivel2=$tb6->fields["nivel2"]; } //EndIf } //EndIf else { $this->valor=instr($this->forcta,'-',0,$this->auxnivel2); $tb6=$this->bd->select("SELECT coalesce(LENGTH(SUBSTR(FORCTA,1,'".$this->valor."'))-1, 0) as nivel2 FROM contaba"); // SELECT NVL(LENGTH(SUBSTR(FORCTA,1,INSTR(FORCTA,'-',1,:AUXnivel2)-1)), 0) INTO :Nivel2 FROM CONTABA; //$tb6=$this->bd->select("SELECT coalesce(LENGTH(SUBSTR(FORCTA,1,position('-' in FORCTA)-1)), 0) as nivel2 FROM contaba"); if (!$tb6->EOF) { $this->nivel2=$tb6->fields["nivel2"]; } //EndIf } //EndIf } //Return function llenartitulosmaestro() { $this->anchos[0]=130; $this->anchos[1]=30; $this->anchos[2]=30; $this->anchos[3]=110; } function Header() { $this->cab->poner_cabecera($this,$_POST["titulo"],"p","s"); $this->setFont("Arial","B",9); $year = substr($this->fecha_ini,0,4); $mes = substr($this->fecha_ini,5,2); $dia = substr($this->fecha_ini,8,2); //$this->cell(40,10,"Desde: ".$dia."-".$mes."-".$year); /* $year = substr($this->fecha_cie,0,4); $mes = substr($this->fecha_cie,5,2); $dia = substr($this->fecha_cie,8,2); $this->cell(180,10,"Al ".$dia."-".$mes."-".$year,0,0,'C');*/ $year = substr($this->fecha_cieper,0,4); $mes = substr($this->fecha_cieper,5,2); $dia = substr($this->fecha_cieper,8,2); if ($this->p_fecha!=""){ $this->cell(180,10,"Al ".$this->p_fecha,0,0,'C'); } if ($this->fecha_p==""){ $this->cell(180,10,"Al ".$dia."-".$mes."-".$year,0,0,'C'); } $this->ln(); $this->cell(50,10,"Cuenta",0,0,'C'); $this->cell(80,10,"Descripción",0,0,'C'); $this->cell(35,10,"Saldo",0,0,'C'); $this->cell(35,10,"Totales",0,0,'C'); $this->Line(10,48,200,48); $this->ln(); } function Cuerpo() { for ($i=1;$i<2;$i++){ $this->Datos($i); } } function Datos($i){ if ($i==1){ $tb=$this->bd->select($this->sql); } else{ $tb=$this->bd->select($this->sql2); } $sw=1; while(!$tb->EOF) { if($tb->fields["titulo"]!=" ") { $this->setFont("Arial","",8); ///////////////////////////////////////////// $palabra=$tb->fields["cuenta"]; $tamano=strlen($palabra); $niv=1; for ($qi=0;$qi<=$tamano;$qi++){ if ($palabra[$qi]=='-'): $niv=$niv+1; endif; } //print " ".$niv." - "; //print $this->nrorup."<br>"; ///////////////////////////////////////////// $sw1=0; if (($niv == ($this->nrorup) and (trim($tb->fields["cargable"]=='C'))) ){ $sw1=1; } else{ if ((($niv == (($this->nrorup)-1) and (($this->nrorup)-1) >0) or ($niv == (($this->nrorup)-2) and (($this->nrorup)-2) >0) or ($niv == (($this->nrorup)-3) and (($this->nrorup)-3) >0) or ($niv == (($this->nrorup)-4) and (($this->nrorup)-4) >0) or ($niv == (($this->nrorup)-5) and (($this->nrorup)-5) >0) or ($niv == (($this->nrorup)-6) and (($this->nrorup)-6) >0) or ($niv == (($this->nrorup)-7) and (($this->nrorup)-7) >0)) ){ if ((strlen(rtrim($tb->fields["cuenta"]))) <= ($this->nivel2)){ $sw1=1; } } } //and (trim($tb->fields["saldo"]<>0))) ){ if ((ltrim(rtrim($tb->fields["titulo"]))=='TOTAL') and $sw1==1) { $this->setFont("Arial","B",8); // $descta=strtoupper(str_pad(' ',strlen(rtrim($tb->fields["cuenta"]))*2,' ',STR_PAD_RIGHT).$tb->fields["titulo"]." ".$tb->fields["nombre"]); $descta=strtoupper($tb->fields["titulo"]." ".substr($tb->fields["nombre"],0,30)); $this->cell($this->anchos[0],10,$descta); $sw=0; } elseif ($sw1==1) { $this->setFont("Arial","",8); //print $this->s=str_pad(' ',strlen(rtrim($tb->fields["cuenta"]))*2,' ',STR_PAD_RIGHT); // $descta=strtoupper(str_pad(' ',strlen(rtrim($tb->fields["cuenta"]))*2,' ',STR_PAD_RIGHT).$tb->fields["nombre"]); //$descta=($tb->fields["codcta"].$tb->fields["nombre"]); $y=$this->GetY(); $this->cell(50,10,$tb->fields["codcta"]); $this->cell(80,10,substr($tb->fields["nombre"],0,51)); // $this->SetXY(60,$y); // $this->multicell(50,0,$tb->fields["nombre"]); $sw=1; } //EndIF /* if ($sw1==1){ $descta=strtoupper(str_pad(' ',strlen(rtrim($tb->fields["cuenta"]))*2,' ',STR_PAD_RIGHT).$tb->fields["nombre"]); $this->cell($this->anchos[0],10,$descta); }*/ $this->CalcularIngresoYEgreso(); ///////////////////////////////////////////// $palabra=$tb->fields["cuenta"]; $tamano=strlen($palabra); $niv=1; for ($wi=0;$wi<=$tamano;$wi++){ if ($palabra[$wi]=='-'): $niv=$niv+1; endif; } //print " ".$niv." - "; //print $this->nrorup."<br>"; ///////////////////////////////////////////// $tb_temp=$this->bd->select("SELECT CARGAB as mov FROM CONTABB WHERE RTRIM(CODCTA)=RTRIM('".$tb->fields["cuenta"]."')"); if (!empty($tb_temp->fields["mov"])){ $mov=$tb_temp->fields["mov"]; } //$this->nrorup=(($this->nrorup)-1); if (($niv == ($this->nrorup) and (trim($tb->fields["cargable"]=='C')) and (trim($tb->fields["saldo"]<>0))) ){ $this->cell($this->anchos[1],10,number_format($tb->fields["saldo"],2,',','.'),0,0,'R'); //$this->Line($this->GetX(),$this->GetY()+2,200,$this->GetY()+2); } // $this->cell($this->anchos[1],10,number_format($tb->fields["saldo"],2,',','.'),0,0,'R'); if ((($niv == (($this->nrorup)-1) and (($this->nrorup)-1) >0) or ($niv == (($this->nrorup)-2) and (($this->nrorup)-2) >0) or ($niv == (($this->nrorup)-3) and (($this->nrorup)-3) >0) or ($niv == (($this->nrorup)-4) and (($this->nrorup)-4) >0) or ($niv == (($this->nrorup)-5) and (($this->nrorup)-5) >0) or ($niv == (($this->nrorup)-6) and (($this->nrorup)-6) >0) or ($niv == (($this->nrorup)-7) and (($this->nrorup)-7) >0) or (trim($tb->fields["titulo"]=='TOTAL')) ) and (trim($tb->fields["cargable"]=='C')) ) { //print $tb->fields["nombre"]."<br>"; ///$this->cell($this->anchos[1],10," "); ///$this->cell($this->anchos[2],10,number_format($tb->fields["saldo"],2,',','.'),0,0,'R'); if ((strlen(rtrim($tb->fields["cuenta"]))) <= ($this->nivel2)){ $this->cell($this->anchos[1],10," "); $this->cell($this->anchos[2],10,number_format($tb->fields["saldo"],2,',','.'),0,0,'R'); } } if ((trim($tb->fields["titulo"]=='TOTAL')) and (trim($tb->fields["saldo"]<>0 )) ){ $this->cell($this->anchos[1],10," "); $this->cell($this->anchos[2],10,number_format($tb->fields["saldo"],2,',','.'),0,0,'R'); $this->Line($this->GetX()+3,$this->GetY()+2,$this->GetX()-30,$this->GetY()+2); } if (( ($niv == (($this->nrorup)-2) and (($this->nrorup)-2) >0) or ($niv == (($this->nrorup)-3) and (($this->nrorup)-3) >0) or ($niv == (($this->nrorup)-4) and (($this->nrorup)-4) >0) or ($niv == (($this->nrorup)-5) and (($this->nrorup)-5) >0) or ($niv == (($this->nrorup)-6) and (($this->nrorup)-6) >0) or ($niv == (($this->nrorup)-7) and (($this->nrorup)-7) >0) or ($niv == (($this->nrorup)-8) and (($this->nrorup)-8) >0)) and ($mov<>'C') and (trim($tb->fields["titulo"]=='TOTAL')) ) //print $tb->fields["cuenta"]." - ".$tb->fields["nombre"]." - ".$this->saldo." -".strlen(rtrim($tb->fields["cuenta"]))." - ".$this->nivel2."<br>"; if ((strlen(rtrim($tb->fields["cuenta"]))) <= ($this->nivel2)){ // $this->Line($this->GetX()+3,$this->GetY()+2,$this->GetX()-30,$this->GetY()+2); } if ( ($niv == (($this->nrorup)-1)) and ((($this->nrorup)-1) >0) and ($mov<>'C') and (trim($tb->fields["titulo"]=='TOTAL')) ){ //print $tb->fields["cuenta"]." - ".$tb->fields["nombre"]." - ".$this->saldo." -".strlen(rtrim($tb->fields["cuenta"]))." - ".$this->nivel2."<br>"; //$this->Line($this->GetX()-70,$this->GetY()+2,$this->GetX()-10,$this->GetY()+2); } if ($tb->fields["orden"]=='2T'){ $this->total_pasivo=$tb->fields["saldo"]; } if ($tb->fields["orden"]=='3T'){ $this->total_patriminio=$tb->fields["saldo"]; } /*if ($sw==0){ // $this->ln(4); $this->cell($this->anchos[1],10," "); $this->cell($this->anchos[2],10,number_format($tb->fields["saldo"],2,',','.'),0,0,'R'); $this->Line($this->GetX(),$this->GetY()+2,200,$this->GetY()+2); } else { if ($tb->fields["cargable"]=='C') { $this->cell($this->anchos[1],10,number_format($tb->fields["saldo"],2,',','.'),0,0,'R'); } }*/ $this->ln(5); } //EndIF $tb->MoveNext(); } //OJO LO VOY A COMENTAR YA QUE NO ESTA MOSTRANDO ESTE RESULTADO if ($i==1){ $this->setFont("Arial","B",8); $this->cell($this->anchos[0],10,"Resultado del Ejercicio"); $this->CalcularResultado(); $this->cell($this->anchos[1]+30,10,number_format($this->total,2,',','.'),0,0,'R'); $this->ln(4); $this->Line(165,$this->GetY()+3,200,$this->GetY()+3); } if ($i==1){ $this->ln(10); $this->setFont("Arial","B",8); //$this->cell($this->anchos[0],10,"TOTAL PASIVO + PATRIMONIO ".abs($this->total_pasivo).' '.abs($this->total_patriminio)); $this->cell($this->anchos[0],10,"TOTAL PASIVO + PATRIMONIO"); $this->cell($this->anchos[1]+30,10,number_format(($this->total_pasivo)+($this->total_patriminio)+($this->total),2,',','.'),0,0,'R'); $this->total_pasivo=0; $this->total_patriminio=0; $this->ln(4); $this->Line(165,$this->GetY()+3,200,$this->GetY()+3); $this->ln(4); $this->Line(165,$this->GetY(),200,$this->GetY()); } } function CalcularResultado(){ $tb99=$this->bd->select("SELECT CODTESPAS as CUENTA_PASIVOS, CODCTA as CUENTA_CAPITAL, CODRESANT as CUENTA_RESULTADO FROM CONTABA WHERE CODEMP= '001'"); if (!$tb99->EOF){ $cuenta_pasivo=$tb99->fields["cuenta_pasivo"]; $cuenta_capital=$tb99->fields["cuenta_capital"]; $cuenta_resultado=$tb99->fields["cuenta_resultado"]; } $tb990=$this->bd->select("SELECT (A.SALACT) as PASIVO FROM CONTABB1 A, CONTABA B WHERE RTRIM(A.CODCTA)=RTRIM(B.CODTESPAS) AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = B.FECINI AND A.FECCIE = B.FECCIE"); if (!$tb990->EOF) { if (rtrim($cuenta_capital)==rtrim($cuenta_pasivo)) { $capital= 0; } else { $tb99=$this->bd->select("SELECT A.SALACT as capital FROM CONTABB1 A, CONTABA B WHERE A.CODCTA=rpad(B.CODCTA,32,' ') AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = B.FECINI AND A.FECCIE = B.FECCIE"); $capital=$tb99->fields["capital"]; } $tb99=$this->bd->select("SELECT A.SALACT as INGRESO FROM CONTABB1 A, CONTABA B WHERE A.CODCTA=rpad(B.CODIND,32,' ') AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = B.FECINI AND A.FECCIE = B.FECCIE"); $ingreso=$tb99->fields["ingreso"]; $tb99=$this->bd->select("SELECT (A.SALACT) as EGRESO FROM CONTABB1 A, CONTABA B WHERE A.CODCTA=rpad(B.CODEGD,32,' ') AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = B.FECINI AND A.FECCIE = B.FECCIE"); $egreso=$tb99->fields["egreso"]; if ((rtrim($cuenta_resultado)==rtrim($cuenta_pasivo))) { $resultado = 0; } else { $tb99=$this->bd->select("SELECT A.SALACT as resultado FROM CONTABB1 A, CONTABA B WHERE A.CODCTA=rpad(B.CODCTD,32,' ') AND A.PEREJE = ('".$this->periodo."') AND A.FECINI = B.FECINI AND A.FECCIE = B.FECCIE"); $resultado=$tb99->fields["resultado"]; } if (($ingreso) > ($egreso)) { $this->Total_Resultado=(($pasivo+$capital+$resultado-(($ingreso)-($egreso)))); } else { $this->Total_Resultado=(($pasivo+$capital+$resultado-(abs($ingreso)-abs($egreso)))); } } } function CalcularIngresoYEgreso(){ $tb50=$this->bd->select("SELECT A.SALACT as INGRESO FROM CONTABB1 A, CONTABA B WHERE RTRIM(A.CODCTA) = RTRIM(B.CODIND) AND A.PEREJE = '".$this->periodo."' AND A.FECINI = B.FECINI AND A.FECCIE = B.FECCIE"); if (!$tb50->EOF){ $Tingreso=$tb50->fields["ingreso"]; } $tb50=$this->bd->select("SELECT A.SALACT as EGRESO FROM CONTABB1 A, CONTABA B WHERE RTRIM(A.CODCTA) = RTRIM(B.CODEGD) AND A.PEREJE = '".$this->periodo."' AND A.FECINI = B.FECINI AND A.FECCIE = B.FECCIE"); if (!$tb50->EOF){ $Tegreso=$tb50->fields["egreso"]; } $this->total=abs(($Tingreso)+($Tegreso))*-1; $this->saldo=$this->saldo + ((abs($Tingreso)-abs($Tegreso))*-1); /* SET SALDO = SALDO + (ABS(INGRESOS) - ABS(EGRESOS))*(-1) WHERE RTRIM(CUENTA)>=SUBSTR(CUENTA_RESULTADO,1,INSTR(CUENTA_RESULTADO,'-',1,1)-1) AND RTRIM(CUENTA)<=RTRIM(CUENTA_RESULTADO) AND INSTR(RTRIM(CUENTA_RESULTADO),RTRIM(CUENTA))<>0; */ } } ?>
gpl-2.0
SuriyaaKudoIsc/wikia-app-test
skins/campfire/modules/CampfireController.class.php
7487
<?php class CampfireController extends WikiaController { private static $extraBodyClasses = array(); private $printStyles; /** * Add extra CSS classes to <body> tag * @author: Inez Korczyński */ public static function addBodyClass($className) { self::$extraBodyClasses[] = $className; } public function init() { $skinVars = $this->app->getSkinTemplateObj()->data; $this->pagetitle = $skinVars['pagetitle']; $this->displaytitle = $skinVars['displaytitle']; $this->mimetype = $skinVars['mimetype']; $this->charset = $skinVars['charset']; $this->body_ondblclick = $skinVars['body_ondblclick']; $this->dir = $skinVars['dir']; $this->lang = $skinVars['lang']; $this->pageclass = $skinVars['pageclass']; $this->pagecss = $skinVars['pagecss']; $this->skinnameclass = $skinVars['skinnameclass']; $this->bottomscripts = $skinVars['bottomscripts']; // initialize variables $this->comScore = null; $this->quantServe = null; } public function executeIndex($params) { global $wgOut, $wgUser, $wgTitle, $wgRequest, $wgCityId, $wgAllInOne, $wgContLang, $wgJsMimeType; $allInOne = $wgAllInOne; // macbre: let extensions modify content of the page (e.g. EditPageLayout) $this->body = !empty($params['body']) ? $params['body'] : F::app()->renderView('CampfireBody', 'Index'); // generate list of CSS classes for <body> tag $this->bodyClasses = array('mediawiki', $this->dir, $this->pageclass); $this->bodyClasses = array_merge($this->bodyClasses, self::$extraBodyClasses); $this->bodyClasses[] = $this->skinnameclass; if(Wikia::isMainPage()) { $this->bodyClasses[] = 'mainpage'; } // add skin theme name $skin = $wgUser->getSkin(); if(!empty($skin->themename)) { $this->bodyClasses[] = "oasis-{$skin->themename}"; } $this->setupJavaScript(); $this->printStyles = array(); // render CSS <link> tags $this->headlinks = $wgOut->getHeadLinks(); $this->pagetitle = htmlspecialchars( $this->pagetitle ); $this->displaytitle = htmlspecialchars( $this->displaytitle ); $this->mimetype = htmlspecialchars( $this->mimetype ); $this->charset = htmlspecialchars( $this->charset ); $this->globalVariablesScript = Skin::makeGlobalVariablesScript($this->app->getSkinTemplateObj()->data); // printable CSS (to be added at the bottom of the page) // If this is an anon article view, use the combined version of the print files. if($allInOne){ // Create the combined URL. global $parserMemc, $wgStyleVersion; $cb = $parserMemc->get(wfMemcKey('wgMWrevId')); global $wgDevelEnvironment; if(empty($wgDevelEnvironment)){ $prefix = "__wikia_combined/"; } else { global $wgWikiaCombinedPrefix; $prefix = $wgWikiaCombinedPrefix; } // no print styles $this->printStyles = array(); } $this->printableCss = $this->renderPrintCSS(); // The HTML for the CSS links (whether async or not). // setup loading of JS/CSS using WSL (WikiaScriptLoader) $this->loadJs(); // FIXME: create separate module for stats stuff? // load Google Analytics code $this->googleAnalytics = AnalyticsEngine::track('GA_Urchin', AnalyticsEngine::EVENT_PAGEVIEW); // onewiki GA $this->googleAnalytics .= AnalyticsEngine::track('GA_Urchin', 'onewiki', array($wgCityId)); // track page load time $this->googleAnalytics .= AnalyticsEngine::track('GA_Urchin', 'pagetime', array('oasis')); // track browser height $this->googleAnalytics .= AnalyticsEngine::track('GA_Urchin', 'browser-height'); // record which varnish this page was served by $this->googleAnalytics .= AnalyticsEngine::track('GA_Urchin', 'varnish-stat'); $this->googleAnalytics .= AnalyticsEngine::track('GA_Urchin', 'noads'); $this->googleAnalytics .= AnalyticsEngine::track('GA_Urchin', 'abtest'); // Add important Gracenote analytics for reporting needed for licensing on LyricWiki. if (43339 == $wgCityId){ $this->googleAnalytics .= AnalyticsEngine::track('GA_Urchin', 'lyrics'); } // macbre: RT #25697 - hide Comscore & QuantServe tags on edit pages if(!in_array($wgRequest->getVal('action'), array('edit', 'submit'))) { $this->comScore = AnalyticsEngine::track('Comscore', AnalyticsEngine::EVENT_PAGEVIEW); $this->quantServe = AnalyticsEngine::track('QuantServe', AnalyticsEngine::EVENT_PAGEVIEW); } $this->mainsassfile = 'skins/campfire/css/campfire.scss'; } // end executeIndex() private function renderPrintCSS() { return ''; } private function setupJavaScript() { global $wgJsMimeType, $wgUser; wfProfileIn(__METHOD__); $this->jsFiles = ''; $srcs = AssetsManager::getInstance()->getGroupCommonURL('oasis_shared_js'); $srcs = array_merge($srcs, AssetsManager::getInstance()->getGroupCommonURL('oasis_extensions_js')); $srcs = array_merge($srcs, AssetsManager::getInstance()->getGroupLocalURL($wgUser->isLoggedIn() ? 'oasis_user_js' : 'oasis_anon_js')); foreach($srcs as $src) { $this->jsFiles .= "<script type=\"$wgJsMimeType\" src=\"$src\"></script>"; } wfProfileOut(__METHOD__); } // TODO: implement as a separate module? private function loadJs() { global $wgTitle, $wgOut, $wgJsMimeType, $wgUser; wfProfileIn(__METHOD__); // decide where JS should be placed (only add JS at the top for special and edit pages) if ($wgTitle->getNamespace() == NS_SPECIAL || BodyController::isEditPage()) { $this->jsAtBottom = false; } else { $this->jsAtBottom = true; } //store AssetsManager output and reset jsFiles $jsAssets = $this->jsFiles; $this->jsFiles = ''; // load WikiaScriptLoader $this->wikiaScriptLoader = ''; $wslFiles = AssetsManager::getInstance()->getGroupCommonURL( 'wsl' ); foreach($wslFiles as $wslFile) { $this->wikiaScriptLoader .= "<script type=\"$wgJsMimeType\" src=\"$wslFile\"></script>"; } // get JS files from <script> tags returned by AssetsManager // TODO: get AssetsManager package (and other JS files to be loaded) here preg_match_all("/src=\"([^\"]+)/", $jsAssets, $matches, PREG_SET_ORDER); foreach($matches as $scriptSrc) { $jsReferences[] = str_replace('&amp;', '&', $scriptSrc[1]);; } // move JS files added to OutputPage to list of files to be loaded using WSL $scripts = $wgUser->getSkin()->getScripts(); foreach ( $scripts as $s ) { //add inline scripts to jsFiles and move non-inline to WSL queue if ( !empty( $s['url'] ) ) { $jsReferences[] = $s['url']; } else { $this->jsFiles .= $s['tag']; } } // add user JS (if User:XXX/wikia.js page exists) // copied from Skin::getHeadScripts if($wgUser->isLoggedIn()){ wfProfileIn(__METHOD__ . '::checkForEmptyUserJS'); $userJS = $wgUser->getUserPage()->getPrefixedText() . '/wikia.js'; $userJStitle = Title::newFromText( $userJS ); if ( $userJStitle->exists() ) { global $wgSquidMaxage; $siteargs = array( 'action' => 'raw', 'maxage' => $wgSquidMaxage, ); $userJS = Skin::makeUrl( $userJS, wfArrayToCGI( $siteargs ) ); $jsReferences[] = Skin::makeUrl( $userJS, wfArrayToCGI( $siteargs ) );; } wfProfileOut(__METHOD__ . '::checkForEmptyUserJS'); } // generate code to load JS files $jsReferences = json_encode($jsReferences); $jsLoader = "<script type=\"text/javascript\">/*<![CDATA[*/ (function(){ wsl.loadScript({$jsReferences}); })(); /*]]>*/</script>"; // use loader script instead of separate JS files $this->jsFiles = $jsLoader . $this->jsFiles; wfProfileOut(__METHOD__); } }
gpl-2.0
sharpmachine/framework
wp-content/plugins/jetpack/modules/custom-css/custom-css.php
32746
<?php /** * Migration routine for moving safecss from wp_options to wp_posts to support revisions * * @return void */ function migrate() { $css = get_option( 'safecss' ); // Check if CSS is stored in wp_options if ( $css ) { // Remove the async actions from publish_post remove_action( 'publish_post', 'queue_publish_post' ); $post = array(); $post['post_content'] = $css; $post['post_title'] = 'safecss'; $post['post_status'] = 'publish'; $post['post_type'] = 'safecss'; // Insert the CSS into wp_posts $post_id = wp_insert_post( $post ); // Check for errors if ( !$post_id or is_wp_error( $post_id ) ) die( $post_id->get_error_message() ); // Delete safecss option delete_option( 'safecss' ); } unset( $css ); // Check if we have already done this if ( !get_option( 'safecss_revision_migrated' ) ) { define( 'DOING_MIGRATE', true ); // Get hashes of safecss post and current revision $safecss_post = get_safecss_post(); if ( empty( $safecss_post ) ) return; $safecss_post_hash = md5( $safecss_post['post_content'] ); $current_revision = get_current_revision(); if ( null == $current_revision ) return; $current_revision_hash = md5( $current_revision['post_content'] ); // If hashes are not equal, set safecss post with content from current revision if ( $safecss_post_hash !== $current_revision_hash ) { save_revision( $current_revision['post_content'] ); // Reset post_content to display the migrated revsion $safecss_post['post_content'] = $current_revision['post_content']; } // Set option so that we dont keep doing this update_option( 'safecss_revision_migrated', time() ); } $newest_safecss_post = get_current_revision(); if ( $newest_safecss_post ) { if ( get_option( 'safecss_content_width' ) ) { // Add the meta to the post and the latest revision. update_post_meta( $newest_safecss_post['ID'], 'content_width', get_option( 'safecss_content_width' ) ); update_metadata( 'post', $newest_safecss_post['ID'], 'content_width', get_option( 'safecss_content_width' ) ); delete_option( 'safecss_content_width' ); } if ( get_option( 'safecss_add' ) ) { update_post_meta( $newest_safecss_post['ID'], 'custom_css_add', get_option( 'safecss_add' ) ); update_metadata( 'post', $newest_safecss_post['ID'], 'custom_css_add', get_option( 'safecss_add' ) ); delete_option( 'safecss_add' ); } } } function safecss_revision_redirect( $redirect ) { global $post; if ( 'safecss' == $post->post_type ) { if ( strstr( $redirect, 'action=edit' ) ) { return 'themes.php?page=editcss'; } if ( 'edit.php' == $redirect ) { return ''; } } return $redirect; } // Add safecss to allowed post_type's for revision add_filter('revision_redirect', 'safecss_revision_redirect'); function safecss_revision_post_link( $post_link, $post_id, $context ) { if ( !$post_id = (int) $post_id ) { return $post_link; } if ( !$post = get_post( $post_id ) ) { return $post_link; } if ( 'safecss' != $post->post_type ) { return $post_link; } $post_link = admin_url( 'themes.php?page=editcss' ); if ( 'display' == $context ) { return esc_url( $post_link ); } return esc_url_raw( $post_link ); } // Override the edit link, the default link causes a redirect loop add_filter( 'get_edit_post_link', 'safecss_revision_post_link', 10, 3 ); /** * Get the published custom CSS post. * * @return array */ function get_safecss_post() { $custom_css_post_id = custom_css_post_id(); if ( $custom_css_post_id ) return get_post( $custom_css_post_id, ARRAY_A ); return array(); } /** * Get the post ID of the published custom CSS post. * * @return int|bool The post ID if it exists; false otherwise. */ function custom_css_post_id() { $custom_css_post_id = wp_cache_get( 'custom_css_post_id' ); if ( false === $custom_css_post_id ) { $custom_css_post = array_shift( get_posts( array( 'posts_per_page' => 1, 'post_type' => 'safecss', 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC' ) ) ); if ( $custom_css_post ) $custom_css_post_id = $custom_css_post->ID; else $custom_css_post_id = 0; // Save post_id=0 to note that no safecss post exists. wp_cache_set( 'custom_css_post_id', $custom_css_post_id ); } if ( ! $custom_css_post_id ) return false; return $custom_css_post_id; } /** * Get the current revision of the original safecss record * * @return object */ function get_current_revision() { $safecss_post = get_safecss_post(); if ( empty( $safecss_post ) ) { return false; } $revisions = wp_get_post_revisions( $safecss_post['ID'], array( 'posts_per_page' => 1, 'orderby' => 'date', 'order' => 'DESC' ) ); // Empty array if no revisions exist if ( empty( $revisions ) ) { // Return original post return $safecss_post; } else { // Return the first entry in $revisions, this will be the current revision $current_revision = get_object_vars( array_shift( $revisions ) ); return $current_revision; } } /** * Save new revision of CSS * Checks to see if content was modified before really saving * * @param string $css * @param bool $is_preview * @return bool|int If nothing was saved, returns false. If a post * or revision was saved, returns the post ID. */ function save_revision( $css, $is_preview = false ) { $safecss_post = get_safecss_post(); $compressed_css = custom_css_minify( $css ); // If null, there was no original safecss record, so create one if ( null == $safecss_post ) { if ( ! $css ) return false; $post = array(); $post['post_content'] = $css; $post['post_title'] = 'safecss'; $post['post_status'] = 'publish'; $post['post_type'] = 'safecss'; $post['post_content_filtered'] = $compressed_css; // Set excerpt to current theme, for display in revisions list if ( function_exists( 'wp_get_theme' ) ) { $current_theme = wp_get_theme(); $post['post_excerpt'] = $current_theme->Name; } else { $post['post_excerpt'] = get_current_theme(); } // Insert the CSS into wp_posts $post_id = wp_insert_post( $post ); wp_cache_set( 'custom_css_post_id', $post_id ); return $post_id; } // Update CSS in post array with new value passed to this function $safecss_post['post_content'] = $css; $safecss_post['post_content_filtered'] = $compressed_css; // Set excerpt to current theme, for display in revisions list if ( function_exists( 'wp_get_theme' ) ) { $current_theme = wp_get_theme(); $safecss_post['post_excerpt'] = $current_theme->Name; } else { $safecss_post['post_excerpt'] = get_current_theme(); } // Don't carry over last revision's timestamps, otherwise revisions all have matching timestamps unset( $safecss_post['post_date'] ); unset( $safecss_post['post_date_gmt'] ); unset( $safecss_post['post_modified'] ); unset( $safecss_post['post_modified_gmt'] ); // Do not update post if we are only saving a preview if ( false === $is_preview ) { $post_id = wp_update_post( $safecss_post ); wp_cache_set( 'custom_css_post_id', $post_id ); return $post_id; } else if ( !defined( 'DOING_MIGRATE' ) ) { return _wp_put_post_revision( $safecss_post ); } } function safecss_skip_stylesheet() { if ( custom_css_is_customizer_preview() ) return false; else { if ( safecss_is_preview() ) { $safecss_post = get_current_revision(); return (bool) ( get_option('safecss_preview_add') == 'no' || get_post_meta( $safecss_post['ID'], 'custom_css_add', true ) == 'no' ); } else { $custom_css_post_id = custom_css_post_id(); return (bool) ( get_option('safecss_add') == 'no' || ( $custom_css_post_id && get_post_meta( $custom_css_post_id, 'custom_css_add', true ) == 'no' ) ); } } } function safecss_init() { define( 'SAFECSS_USE_ACE', ! jetpack_is_mobile() && ! Jetpack_User_Agent_Info::is_ipad() && apply_filters( 'safecss_use_ace', true ) ); // Register safecss as a custom post_type // Explicit capability definitions are largely unnecessary because the posts are manipulated in code via an options page, managing CSS revisions does check the capabilities, so let's ensure that the proper caps are checked. register_post_type( 'safecss', array( // These are the defaults // 'exclude_from_search' => true, // 'public' => false, // 'publicly_queryable' => false, // 'show_ui' => false, 'supports' => array( 'revisions' ), 'label' => 'Custom CSS', 'can_export' => false, 'rewrite' => false, 'capabilities' => array( 'edit_post' => 'edit_theme_options', 'read_post' => 'read', 'delete_post' => 'edit_theme_options', 'edit_posts' => 'edit_theme_options', 'edit_others_posts' => 'edit_theme_options', 'publish_posts' => 'edit_theme_options', 'read_private_posts' => 'read' ) ) ); // Short-circuit WP if this is a CSS stylesheet request if ( isset( $_GET['custom-css'] ) ) { header( 'Content-Type: text/css', true, 200 ); header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 31536000) . ' GMT' ); // 1 year safecss_print(); exit; } if ( isset( $_GET['page'] ) && 'editcss' == $_GET['page'] && is_admin() ) { // Do migration routine if necessary migrate(); do_action( 'safecss_migrate_post' ); } add_action( 'wp_head', 'safecss_style', 101 ); if ( !current_user_can('switch_themes') && !is_super_admin() ) return; add_action('admin_menu', 'safecss_menu'); if ( isset($_POST['safecss']) && false == strstr( $_SERVER[ 'REQUEST_URI' ], 'options.php' ) ) { check_admin_referer('safecss'); // Remove wp_filter_post_kses, this causes CSS escaping issues remove_filter( 'content_save_pre', 'wp_filter_post_kses' ); remove_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' ); remove_all_filters( 'content_save_pre' ); do_action( 'safecss_save_pre' ); $warnings = array(); safecss_class(); $csstidy = new csstidy(); $csstidy->optimise = new safecss($csstidy); $csstidy->set_cfg( 'remove_bslash', false ); $csstidy->set_cfg( 'compress_colors', false ); $csstidy->set_cfg( 'compress_font-weight', false ); $csstidy->set_cfg( 'optimise_shorthands', 0 ); $csstidy->set_cfg( 'remove_last_;', false ); $csstidy->set_cfg( 'case_properties', false ); $csstidy->set_cfg( 'discard_invalid_properties', true ); $csstidy->set_cfg( 'css_level', 'CSS3.0' ); $csstidy->set_cfg( 'preserve_css', true ); $csstidy->set_cfg( 'template', dirname( __FILE__ ) . '/csstidy/wordpress-standard.tpl' ); $css = $orig = stripslashes($_POST['safecss']); $css = preg_replace('/\\\\([0-9a-fA-F]{4})/', '\\\\\\\\$1', $prev = $css); if ( $css != $prev ) $warnings[] = 'preg_replace found stuff'; // Some people put weird stuff in their CSS, KSES tends to be greedy $css = str_replace( '<=', '&lt;=', $css ); // Why KSES instead of strip_tags? Who knows? $css = wp_kses_split($prev = $css, array(), array()); $css = str_replace( '&gt;', '>', $css ); // kses replaces lone '>' with &gt; // Why both KSES and strip_tags? Because we just added some '>'. $css = strip_tags( $css ); if ( $css != $prev ) $warnings[] = 'kses found stuff'; do_action( 'safecss_parse_pre', $csstidy, $css ); $csstidy->parse($css); do_action( 'safecss_parse_post', $csstidy, $warnings ); $css = $csstidy->print->plain(); if ( isset( $_POST['custom_content_width'] ) && intval($_POST['custom_content_width']) > 0 ) $custom_content_width = intval($_POST['custom_content_width']); else $custom_content_width = false; if ( $_POST['add_to_existing'] == 'true' ) $add_to_existing = 'yes'; else $add_to_existing = 'no'; if ( $_POST['action'] == 'preview' || safecss_is_freetrial() ) { // Save the CSS $safecss_revision_id = save_revision( $css, true ); // Cache Buster update_option('safecss_preview_rev', intval( get_option('safecss_preview_rev') ) + 1); update_metadata( 'post', $safecss_revision_id, 'custom_css_add', $add_to_existing ); update_metadata( 'post', $safecss_revision_id, 'content_width', $custom_content_width ); if ( $_POST['action'] == 'preview' ) { wp_safe_redirect( add_query_arg( 'csspreview', 'true', get_option('home') ) ); exit; } do_action( 'safecss_save_preview_post' ); } // Save the CSS $safecss_post_id = save_revision( $css ); $safecss_post_revision = get_current_revision(); update_option( 'safecss_rev', intval( get_option( 'safecss_rev' ) ) + 1 ); update_post_meta( $safecss_post_id, 'custom_css_add', $add_to_existing ); update_post_meta( $safecss_post_id, 'content_width', $custom_content_width ); update_metadata( 'post', $safecss_post_revision['ID'], 'custom_css_add', $add_to_existing ); update_metadata( 'post', $safecss_post_revision['ID'], 'content_width', $custom_content_width ); add_action('admin_notices', 'safecss_saved'); } // Modify all internal links so that preview state persists if ( safecss_is_preview() ) ob_start('safecss_buffer'); } add_action('init', 'safecss_init'); function safecss_is_preview() { return isset($_GET['csspreview']) && $_GET['csspreview'] === 'true'; } /* * safecss_is_freetrial() is false when the site has the Custom Design upgrade. * Used only on WordPress.com. */ function safecss_is_freetrial() { return apply_filters( 'safecss_is_freetrial', false ); } function safecss( $compressed = false ) { $default_css = apply_filters( 'safecss_get_css_error', false ); if ( $default_css !== false ) return $default_css; $option = ( safecss_is_preview() || safecss_is_freetrial() ) ? 'safecss_preview' : 'safecss'; if ( 'safecss' == $option ) { if ( get_option( 'safecss_revision_migrated' ) ) { $safecss_post = get_safecss_post(); $css = ( $compressed && $safecss_post['post_content_filtered'] ) ? $safecss_post['post_content_filtered'] : $safecss_post['post_content']; } else { $current_revision = get_current_revision(); if ( false === $current_revision ) { $css = ''; } else { $css = ( $compressed && $current_revision['post_content_filtered'] ) ? $current_revision['post_content_filtered'] : $current_revision['post_content']; } } // Fix for un-migrated Custom CSS if ( empty( $safecss_post ) ) { $_css = get_option( 'safecss' ); if ( !empty( $_css ) ) { $css = $_css; } } } else if ( 'safecss_preview' == $option ) { $safecss_post = get_current_revision(); $css = $safecss_post['post_content']; $css = stripslashes( $css ); $css = custom_css_minify( $css ); } $css = str_replace( array( '\\\00BB \\\0020', '\0BB \020', '0BB 020' ), '\00BB \0020', $css ); if ( empty( $css ) ) { $css = "/*\n" . wordwrap( apply_filters( 'safecss_default_css', __( "Welcome to Custom CSS!\n\nCSS (Cascading Style Sheets) is a kind of code that tells the browser how to render a web page. You may delete these comments and get started with your customizations.\n\nBy default, your stylesheet will be loaded after the theme stylesheets, which means that your rules can take precedence and override the theme CSS rules. Just write here what you want to change, you don't need to copy all your theme's stylesheet content.", 'jetpack' ) ) ) . "\n*/"; } $css = apply_filters( 'safecss_css', $css ); return $css; } function safecss_print() { do_action( 'safecss_print_pre' ); echo safecss( true ); } function safecss_style() { global $blog_id, $current_blog; if ( apply_filters( 'safecss_style_error', false ) ) return; if ( ! is_super_admin() && isset( $current_blog ) && ( 1 == $current_blog->spam || 1 == $current_blog->deleted ) ) return; if ( custom_css_is_customizer_preview() ) return; $option = safecss_is_preview() ? 'safecss_preview' : 'safecss'; if ( 'safecss' == $option ) { if ( get_option( 'safecss_revision_migrated' ) ) { $safecss_post = get_safecss_post(); $css = $safecss_post['post_content']; } else { $current_revision = get_current_revision(); $css = $current_revision['post_content']; } // Fix for un-migrated Custom CSS if ( empty( $safecss_post ) ) { $_css = get_option( 'safecss' ); if ( !empty( $_css ) ) { $css = $_css; } } } if ( 'safecss_preview' == $option ) { $safecss_post = get_current_revision(); $css = $safecss_post['post_content']; } $css = str_replace( array( '\\\00BB \\\0020', '\0BB \020', '0BB 020' ), '\00BB \0020', $css ); if ( $css == '' ) return; $href = trailingslashit( site_url() ); $href = add_query_arg( 'custom-css', 1, $href ); $href = add_query_arg( 'csblog', $blog_id, $href ); $href = add_query_arg( 'cscache', 6, $href ); $href = add_query_arg( 'csrev', (int) get_option( $option . '_rev' ), $href ); $href = apply_filters( 'safecss_href', $href, $blog_id ); if ( safecss_is_preview() ) $href = add_query_arg( 'csspreview', 'true', $href ); ?> <link rel="stylesheet" type="text/css" href="<?php echo esc_url( $href ); ?>" /> <?php } function safecss_style_filter( $current ) { if ( safecss_is_freetrial() && ( !safecss_is_preview() || !current_user_can('switch_themes') ) ) return $current; else if ( safecss_skip_stylesheet() ) return apply_filters( 'safecss_style_filter_url', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content/plugins/safecss/blank.css' ); return $current; } add_filter( 'stylesheet_uri', 'safecss_style_filter' ); function safecss_buffer($html) { $html = str_replace('</body>', safecss_preview_flag(), $html); return preg_replace_callback('!href=([\'"])(.*?)\\1!', 'safecss_preview_links', $html); } function safecss_preview_links( $matches ) { if ( 0 !== strpos( $matches[2], get_option( 'home' ) ) ) return $matches[0]; $link = wp_specialchars_decode( $matches[2] ); $link = add_query_arg( 'csspreview', 'true', $link ); $link = esc_url( $link ); return "href={$matches[1]}$link{$matches[1]}"; } // Places a black bar above every preview page function safecss_preview_flag() { if ( is_admin() ) return; $message = esc_html__( 'Preview: changes must be saved or they will be lost', 'jetpack' ); $message = apply_filters( 'safecss_preview_message', $message ); $preview_flag_js = "var flag = document.createElement('div'); flag.innerHTML = " . json_encode( $message ) . "; flag.style.background = 'black'; flag.style.color = 'white'; flag.style.textAlign = 'center'; flag.style.fontSize = '15px'; flag.style.padding = '1px'; document.body.style.paddingTop = '32px'; document.body.insertBefore(flag, document.body.childNodes[0]); "; $preview_flag_js = apply_filters( 'safecss_preview_flag_js', $preview_flag_js ); if ( $preview_flag_js ) { $preview_flag_js = '<script type="text/javascript"> // <![CDATA[ ' . $preview_flag_js . ' // ]]> </script>'; } return $preview_flag_js; } function safecss_menu() { $parent = 'themes.php'; $title = __( 'Edit CSS', 'jetpack' ); $hook = add_theme_page( $title, $title, 'edit_theme_options', 'editcss', 'safecss_admin' ); add_action( "admin_print_scripts-$hook", 'safe_css_enqueue_scripts' ); add_action( "admin_head-$hook", 'safecss_admin_head' ); add_action( "load-revision.php", 'safecss_prettify_post_revisions' ); add_action( "load-$hook", 'update_title' ); } /** * Adds a menu item in the appearance section for this plugin's administration * page. Also adds hooks to enqueue the CSS and JS for the admin page. */ function update_title() { global $title; $title = __( 'CSS', 'jetpack' ); } function safecss_prettify_post_revisions() { add_filter( 'the_title', 'safecss_post_title', 10, 2 ); add_action( 'admin_head', 'safecss_remove_title_excerpt_from_revisions' ); } function safecss_remove_title_excerpt_from_revisions() { global $post; if ( !$post ) { return; } if ( 'safecss' != $post->post_type ) { return; } ?> <style type="text/css"> #revision-field-post_title, #revision-field-post_excerpt { display: none; } </style> <?php } function safecss_post_title( $title, $post_id ) { if ( !$post_id = (int) $post_id ) { return $title; } if ( !$post = get_post( $post_id ) ) { return $title; } if ( 'safecss' != $post->post_type ) { return $title; } return __( 'Custom CSS Stylesheet', 'jetpack' ); } function safe_css_enqueue_scripts() { wp_enqueue_script( 'postbox' ); if ( defined('SAFECSS_USE_ACE') && SAFECSS_USE_ACE ) { $url = plugins_url( 'safecss/js/', __FILE__ ); wp_enqueue_script( 'jquery.spin' ); wp_enqueue_script( 'safecss-ace', $url . 'ace/ace.js', array(), false, true ); wp_enqueue_script( 'safecss-ace-css', $url . 'ace/mode-css.js', array( 'safecss-ace' ), false, true ); wp_enqueue_script( 'safecss-ace-use', $url . 'safecss-ace.js', array( 'jquery', 'safecss-ace-css' ), false, true ); } } function safecss_class() { // Wrapped so we don't need the parent class just to load the plugin if ( class_exists('safecss') ) return; require_once( 'csstidy/class.csstidy.php' ); class safecss extends csstidy_optimise { function safecss( &$css ) { return $this->csstidy_optimise( $css ); } function postparse() { do_action( 'csstidy_optimize_postparse', $this ); return parent::postparse(); } function subvalue() { do_action( 'csstidy_optimize_subvalue', $this ); return parent::subvalue(); } } } function safecss_admin_head() { ?> <style type="text/css"> .wrap form.safecss { margin-right: 10px; } .wrap textarea#safecss { min-height: 250px; width: 100%; } p.submit { margin: 0 auto; overflow: hidden; padding: 5px 0 25px; width: 65%; } p.submit span { float: right; padding-right: 1.5em; text-align: right; } p.css-support { color: #777; font-size: 15px; font-weight: 300; margin: -10px 0 15px; } textarea#safecss { background: #f9f9f9; color: #444; font-family: Consolas, Monaco, Courier, monospace; font-size: 12px; line-height: 16px; outline: none; padding: 16px; } #poststuff .inside p.css-settings { margin-top: 15px; } #safecssform .button, #safecssform .button-primary { padding: 7px 12px; margin-left: 6px; } <?php if ( defined( 'SAFECSS_USE_ACE' ) && SAFECSS_USE_ACE ) : ?> #safecss-container { position: relative; width: 99.5%; height: 400px; border: 1px solid #dfdfdf; border-radius: 3px; } #safecss-container .ace_editor { font-family: Consolas, Monaco, Courier, monospace; } #safecss-ace { width: 100%; height: 100%; display: none; /* Hide on load otherwise it looks weird */ } #safecss-ace.ace_editor { display: block; } #safecss-container .ace-tm .ace_gutter { background-color: #ededed; } <?php endif; // ace ?> </style> <script type="text/javascript"> /*<![CDATA[*/ var safecssResize, safecssInit; (function($){ var safe, win; safecssResize = function() { safe.height( win.height() - safe.offset().top - 250 ); }; safecssInit = function() { safe = $('#safecss'); win = $(window); postboxes.add_postbox_toggles('editcss'); safecssResize(); var button = document.getElementById('preview'); button.onclick = function(event) { //window.open('<?php echo add_query_arg('csspreview', 'true', get_option('home')); ?>'); <?php // hack for now for previewing. // TODO: move all of this JS into its own file. if ( defined( 'SAFECSS_USE_ACE' ) && SAFECSS_USE_ACE ) { echo "\t\taceSyncCSS();\n"; } ?> document.forms["safecssform"].target = "csspreview"; document.forms["safecssform"].action.value = 'preview'; document.forms["safecssform"].submit(); document.forms["safecssform"].target = ""; document.forms["safecssform"].action.value = 'save'; event = event || window.event; if ( event.preventDefault ) event.preventDefault(); return false; } }; window.onresize = safecssResize; addLoadEvent(safecssInit); })(jQuery); /*]]>*/ </script> <?php } function safecss_saved() { echo '<div id="message" class="updated fade"><p><strong>' . __( 'Stylesheet saved.', 'jetpack' ) . '</strong></p></div>'; } function safecss_admin() { ?> <div class="wrap"> <?php do_action( 'custom_design_header' ); ?> <div id="poststuff" class="has-right-sidebar metabox-holder"> <h2><?php _e( 'CSS Stylesheet Editor', 'jetpack' ); ?></h2> <p class="css-support"><?php echo apply_filters( 'safecss_intro_text', __( 'New to CSS? Start with a <a href="http://www.htmldog.com/guides/cssbeginner/">beginner tutorial</a>. Questions? Ask in the <a href="http://wordpress.org/support/forum/themes-and-templates">Themes and Templates forum</a>.', 'jetpack' ) ); ?></p> <form id="safecssform" action="" method="post"> <?php if ( defined( 'SAFECSS_USE_ACE' ) && SAFECSS_USE_ACE ) : ?> <div id="safecss-container"> <div id="safecss-ace"></div> </div> <script type="text/javascript"> jQuery.fn.spin && jQuery("#safecss-container").spin( 'large' ); </script> <textarea id="safecss" name="safecss" class="hide-if-js"><?php echo esc_textarea( safecss() ); ?></textarea> <div class="clear"></div> <?php else : ?> <p><textarea id="safecss" name="safecss"><?php echo str_replace('</textarea>', '&lt;/textarea&gt', safecss()); ?></textarea></p> <?php endif; ?> <p class="submit"> <span> <input type="hidden" name="action" value="save" /> <?php wp_nonce_field( 'safecss' ) ?> <input type="button" class="button" id="preview" name="preview" value="<?php esc_attr_e( 'Preview', 'jetpack' ) ?>" /> <input type="submit" class="button-primary" id="save" name="save" value="<?php ( safecss_is_freetrial() ) ? esc_attr_e( 'Save Stylesheet &amp; Buy Upgrade', 'jetpack' ) : esc_attr_e( 'Save Stylesheet', 'jetpack' ); ?>" /> <?php wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false ); ?> </span> </p> <?php add_meta_box( 'settingsdiv', __( 'CSS Settings', 'jetpack' ), 'custom_css_meta_box', 'editcss', 'normal' ); ?> <?php $safecss_post = get_safecss_post(); if ( ! empty( $safecss_post ) && 0 < $safecss_post['ID'] && wp_get_post_revisions( $safecss_post['ID'] ) ) { echo '<div id="side-info-column" class="inner-sidebar">'; add_meta_box( 'revisionsdiv', __( 'CSS Revisions', 'jetpack' ), 'custom_css_post_revisions_meta_box', 'editcss', 'side' ); do_meta_boxes( 'editcss', 'side', $safecss_post ); echo '</div>'; echo '<div id="post-body"><div id="post-body-content">'; do_meta_boxes( 'editcss', 'normal', $safecss_post ); echo '</div></div>'; echo '<div class="clear"></div>'; } else { do_meta_boxes( 'editcss', 'normal', $safecss_post ); } ?> </form> </div> </div> <?php } /** * Render CSS Settings metabox * Called by `safecss_admin` * * @uses get_option, checked, __, get_current_theme, apply_filters, get_stylesheet_uri, _e, esc_attr, wp_get_theme * @return string */ function custom_css_meta_box() { if ( function_exists( 'wp_get_theme' ) ) { $current_theme = wp_get_theme(); $current_theme = $current_theme->Name; } else { $current_theme = get_current_theme(); } $safecss_post = get_current_revision(); ?> <p class="css-settings"> <label><input type="radio" name="add_to_existing" value="true" <?php checked( get_post_meta( $safecss_post['ID'], 'custom_css_add', true ) != 'no' ); ?> /> <?php printf( __( 'Add my CSS to <strong>%s&apos;s</strong> CSS stylesheet.', 'jetpack' ), $current_theme ); ?></label><br /> <label><input type="radio" name="add_to_existing" value="false" <?php checked( get_post_meta( $safecss_post['ID'], 'custom_css_add', true ) == 'no' ); ?> /> <?php printf( __( 'Don&apos;t use <strong>%s&apos;s</strong> CSS, and replace everything with my own CSS.', 'jetpack' ), $current_theme ); ?></label> </p> <p><?php printf( __( '<a href="%s">View the original stylesheet</a> for the %s theme. Use this as a reference and do not copy and paste all of it into the CSS Editor.', 'jetpack' ), apply_filters( 'safecss_theme_stylesheet_url', get_stylesheet_uri() ), $current_theme ); ?></p> <?php do_action( 'custom_css_meta_fields' ); } /** * Render metabox listing CSS revisions and the themes that correspond to the revisions. * Called by `safecss_admin` * * @param array $safecss_post * @global $post * @uses WP_Query, wp_post_revision_title, esc_html, add_query_arg, menu_page_url, wp_reset_query * @return string */ function custom_css_post_revisions_meta_box( $safecss_post ) { $max_revisions = defined( 'WP_POST_REVISIONS' ) && is_numeric( WP_POST_REVISIONS ) ? (int) WP_POST_REVISIONS : 25; $posts_per_page = isset( $_GET['show_all_rev'] ) ? $max_revisions : 6; $revisions = new WP_Query( array( 'posts_per_page' => $posts_per_page, 'post_type' => 'revision', 'post_status' => 'inherit', 'post_parent' => $safecss_post['ID'], 'orderby' => 'date', 'order' => 'DESC' ) ); if ( $revisions->have_posts() ) : ?> <ul class="post-revisions"><?php global $post; while ( $revisions->have_posts() ) : $revisions->the_post(); ?><li> <?php echo wp_post_revision_title( $post ); if ( ! empty( $post->post_excerpt ) ) echo ' (' . esc_html( $post->post_excerpt ) . ')'; ?> </li><?php endwhile; ?></ul><?php if ( $revisions->found_posts > 6 ) : ?> <br> <a href="<?php echo add_query_arg( 'show_all_rev', 'true', menu_page_url( 'editcss', false ) ); ?>">Show more</a> <?php endif; // "Show more" endif; // have_posts(); wp_reset_query(); } if ( !function_exists( 'safecss_filter_attr' ) ) { function safecss_filter_attr($css, $element = 'div') { safecss_class(); $css = $element . ' {' . $css . '}'; $csstidy = new csstidy(); $csstidy->optimise = new safecss($csstidy); $csstidy->set_cfg('remove_bslash', false); $csstidy->set_cfg('compress_colors', false); $csstidy->set_cfg('compress_font-weight', false); $csstidy->set_cfg('discard_invalid_properties', true); $csstidy->set_cfg('merge_selectors', false); $csstidy->set_cfg('remove_last_;', false); $csstidy->set_cfg('css_level', 'CSS3.0'); $css = preg_replace('/\\\\([0-9a-fA-F]{4})/', '\\\\\\\\$1', $css); $css = wp_kses_split($css, array(), array()); $csstidy->parse($css); $css = $csstidy->print->plain(); $css = str_replace(array("\n","\r","\t"), '', $css); preg_match("/^{$element}\s*{(.*)}\s*$/", $css, $matches); if ( empty($matches[1]) ) return ''; return $matches[1]; } } // hook on init at priority 11 function disable_safecss_style() { remove_action( 'wp_head', 'safecss_style', 101 ); remove_filter( 'stylesheet_uri', 'safecss_style_filter' ); } /** * Reset all aspects of Custom CSS on a theme switch so that changing * themes is a sure-fire way to get a clean start. */ function custom_css_reset() { $safecss_post_id = save_revision( '' ); $safecss_revision = get_current_revision(); update_option( 'safecss_rev', intval( get_option( 'safecss_rev' ) ) + 1 ); update_post_meta( $safecss_post_id, 'custom_css_add', 'yes' ); update_post_meta( $safecss_post_id, 'content_width', false ); update_metadata( 'post', $safecss_revision['ID'], 'custom_css_add', 'yes' ); update_metadata( 'post', $safecss_revision['ID'], 'content_width', false ); } add_action( 'switch_theme', 'custom_css_reset' ); function custom_css_is_customizer_preview() { if ( isset ( $GLOBALS['wp_customize'] ) ) return ! $GLOBALS['wp_customize']->is_theme_active(); return false; } function custom_css_minify( $css ) { if ( ! $css ) return ''; safecss_class(); $csstidy = new csstidy(); $csstidy->optimise = new safecss( $csstidy ); $csstidy->set_cfg( 'remove_bslash', false ); $csstidy->set_cfg( 'compress_colors', true ); $csstidy->set_cfg( 'compress_font-weight', true ); $csstidy->set_cfg( 'remove_last_;', true ); $csstidy->set_cfg( 'case_properties', true ); $csstidy->set_cfg( 'discard_invalid_properties', true ); $csstidy->set_cfg( 'css_level', 'CSS3.0' ); $csstidy->set_cfg( 'template', 'highest'); $csstidy->parse( $css ); return $csstidy->print->plain(); } /** * When restoring a SafeCSS post revision, also copy over the * content_width and custom_css_add post metadata. */ function custom_css_restore_revision( $_post_id, $_revision_id ) { $_post = get_post( $_post_id ); if ( 'safecss' != $_post->post_type ) return; $safecss_revision = get_current_revision(); $content_width = get_post_meta( $_revision_id, 'content_width', true ); $custom_css_add = get_post_meta( $_revision_id, 'custom_css_add', true ); update_metadata( 'post', $safecss_revision['ID'], 'content_width', $content_width ); update_metadata( 'post', $safecss_revision['ID'], 'custom_css_add', $custom_css_add ); update_post_meta( $_post->ID, 'content_width', $content_width ); update_post_meta( $_post->ID, 'custom_css_add', $custom_css_add ); } add_action( 'wp_restore_post_revision', 'custom_css_restore_revision', 10, 2 );
gpl-2.0
GiGa-Emulator/Aion-Core-v4.7.5
AC-Tools/powerweb30/framework/web/CPagination.php
7411
<?php /** * CPagination class file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2011 Yii Software LLC * @license http://www.yiiframework.com/license/ */ /** * CPagination represents information relevant to pagination. * * When data needs to be rendered in multiple pages, we can use CPagination to * represent information such as {@link getItemCount total item count}, * {@link getPageSize page size}, {@link getCurrentPage current page}, etc. * These information can be passed to {@link CBasePager pagers} to render * pagination buttons or links. * * Example: * * Controller action: * <pre> * function actionIndex(){ * $criteria = new CDbCriteria(); * $count=Article::model()->count($criteria); * $pages=new CPagination($count); * * // results per page * $pages->pageSize=10; * $pages->applyLimit($criteria); * $models = Post::model()->findAll($criteria); * * $this->render('index', array( * 'models' => $models, * 'pages' => $pages * )); * } * </pre> * * View: * <pre> * <?php foreach($models as $model): ?> * // display a model * <?php endforeach; ?> * * // display pagination * <?php $this->widget('CLinkPager', array( * 'pages' => $pages, * )) ?> * </pre> * * @property integer $pageSize Number of items in each page. Defaults to 10. * @property integer $item_count Total number of items. Defaults to 0. * @property integer $pageCount Number of pages. * @property integer $currentPage The zero-based index of the current page. Defaults to 0. * @property integer $offset The offset of the data. This may be used to set the * OFFSET value for a SQL statement for fetching the current page of data. * @property integer $limit The limit of the data. This may be used to set the * LIMIT value for a SQL statement for fetching the current page of data. * This returns the same value as {@link pageSize}. * * @author Qiang Xue <qiang.xue@gmail.com> * @version $Id: CPagination.php 3515 2011-12-28 12:29:24Z mdomba $ * @package system.web * @since 1.0 */ class CPagination extends CComponent { /** * The default page size. */ const DEFAULT_PAGE_SIZE=10; /** * @var string name of the GET variable storing the current page index. Defaults to 'page'. */ public $pageVar='page'; /** * @var string the route (controller ID and action ID) for displaying the paged contents. * Defaults to empty string, meaning using the current route. */ public $route=''; /** * @var array of parameters (name=>value) that should be used instead of GET when generating pagination URLs. * Defaults to null, meaning using the currently available GET parameters. */ public $params; /** * @var boolean whether to ensure {@link currentPage} is returning a valid page number. * When this property is true, the value returned by {@link currentPage} will always be between * 0 and ({@link pageCount}-1). Because {@link pageCount} relies on the correct value of {@link item_count}, * it means you must have knowledge about the total number of data items when you want to access {@link currentPage}. * This is fine for SQL-based queries, but may not be feasible for other kinds of queries (e.g. MongoDB). * In those cases, you may set this property to be false to skip the validation (you may need to validate yourself then). * Defaults to true. * @since 1.1.4 */ public $validateCurrentPage=true; private $_pageSize=self::DEFAULT_PAGE_SIZE; private $_item_count=0; private $_currentPage; /** * Constructor. * @param integer $item_count total number of items. */ public function __construct($item_count=0) { $this->setItemCount($item_count); } /** * @return integer number of items in each page. Defaults to 10. */ public function getPageSize() { return $this->_pageSize; } /** * @param integer $value number of items in each page */ public function setPageSize($value) { if(($this->_pageSize=$value)<=0) $this->_pageSize=self::DEFAULT_PAGE_SIZE; } /** * @return integer total number of items. Defaults to 0. */ public function getItemCount() { return $this->_item_count; } /** * @param integer $value total number of items. */ public function setItemCount($value) { if(($this->_item_count=$value)<0) $this->_item_count=0; } /** * @return integer number of pages */ public function getPageCount() { return (int)(($this->_item_count+$this->_pageSize-1)/$this->_pageSize); } /** * @param boolean $recalculate whether to recalculate the current page based on the page size and item count. * @return integer the zero-based index of the current page. Defaults to 0. */ public function getCurrentPage($recalculate=true) { if($this->_currentPage===null || $recalculate) { if(isset($_GET[$this->pageVar])) { $this->_currentPage=(int)$_GET[$this->pageVar]-1; if($this->validateCurrentPage) { $pageCount=$this->getPageCount(); if($this->_currentPage>=$pageCount) $this->_currentPage=$pageCount-1; } if($this->_currentPage<0) $this->_currentPage=0; } else $this->_currentPage=0; } return $this->_currentPage; } /** * @param integer $value the zero-based index of the current page. */ public function setCurrentPage($value) { $this->_currentPage=$value; $_GET[$this->pageVar]=$value+1; } /** * Creates the URL suitable for pagination. * This method is mainly called by pagers when creating URLs used to * perform pagination. The default implementation is to call * the controller's createUrl method with the page information. * You may override this method if your URL scheme is not the same as * the one supported by the controller's createUrl method. * @param CController $controller the controller that will create the actual URL * @param integer $page the page that the URL should point to. This is a zero-based index. * @return string the created URL */ public function createPageUrl($controller,$page) { $params=$this->params===null ? $_GET : $this->params; if($page>0) // page 0 is the default $params[$this->pageVar]=$page+1; else unset($params[$this->pageVar]); return $controller->createUrl($this->route,$params); } /** * Applies LIMIT and OFFSET to the specified query criteria. * @param CDbCriteria $criteria the query criteria that should be applied with the limit */ public function applyLimit($criteria) { $criteria->limit=$this->getLimit(); $criteria->offset=$this->getOffset(); } /** * @return integer the offset of the data. This may be used to set the * OFFSET value for a SQL statement for fetching the current page of data. * @since 1.1.0 */ public function getOffset() { return $this->getCurrentPage()*$this->getPageSize(); } /** * @return integer the limit of the data. This may be used to set the * LIMIT value for a SQL statement for fetching the current page of data. * This returns the same value as {@link pageSize}. * @since 1.1.0 */ public function getLimit() { return $this->getPageSize(); } }
gpl-2.0
jackyhong/esper
esper/src/main/java/com/espertech/esper/pattern/EvalRootStateNode.java
5092
/************************************************************************************** * Copyright (C) 2006-2015 EsperTech Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * **************************************************************************************/ package com.espertech.esper.pattern; import com.espertech.esper.client.EventBean; import com.espertech.esper.metrics.instrumentation.InstrumentationHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Set; /** * This class is always the root node in the evaluation state tree representing any activated event expression. * It hold the handle to a further state node with subnodes making up a whole evaluation state tree. */ public class EvalRootStateNode extends EvalStateNode implements Evaluator, PatternStopCallback, EvalRootState { protected EvalNode rootSingleChildNode; protected EvalStateNode topStateNode; private PatternMatchCallback callback; /** * Constructor. * @param rootSingleChildNode is the root nodes single child node */ public EvalRootStateNode(EvalNode rootSingleChildNode) { super(null); this.rootSingleChildNode = rootSingleChildNode; } @Override public EvalNode getFactoryNode() { return rootSingleChildNode; } /** * Hands the callback to use to indicate matching events. * @param callback is invoked when the event expressions turns true. */ public final void setCallback(PatternMatchCallback callback) { this.callback = callback; } public void startRecoverable(boolean startRecoverable, MatchedEventMap beginState) { start(beginState); } public final void start(MatchedEventMap beginState) { if (InstrumentationHelper.ENABLED) { InstrumentationHelper.get().qPatternRootStart(beginState);} topStateNode = rootSingleChildNode.newState(this, null, 0L); topStateNode.start(beginState); if (InstrumentationHelper.ENABLED) { InstrumentationHelper.get().aPatternRootStart();} } public final void stop() { quit(); } public void quit() { if (InstrumentationHelper.ENABLED) { InstrumentationHelper.get().qPatternRootQuit();} if (topStateNode != null) { topStateNode.quit(); handleQuitEvent(); } topStateNode = null; if (InstrumentationHelper.ENABLED) { InstrumentationHelper.get().aPatternRootQuit();} } public void handleQuitEvent() { // no action } public void handleChildQuitEvent() { // no action } public void handleEvaluateFalseEvent() { // no action } public final void evaluateTrue(MatchedEventMap matchEvent, EvalStateNode fromNode, boolean isQuitted) { if (InstrumentationHelper.ENABLED) { InstrumentationHelper.get().qPatternRootEvaluateTrue(matchEvent);} if (isQuitted) { topStateNode = null; handleChildQuitEvent(); } callback.matchFound(matchEvent.getMatchingEventsAsMap()); if (InstrumentationHelper.ENABLED) { InstrumentationHelper.get().aPatternRootEvaluateTrue(topStateNode == null);} } public final void evaluateFalse(EvalStateNode fromNode, boolean restartable) { if (InstrumentationHelper.ENABLED) { InstrumentationHelper.get().qPatternRootEvalFalse();} if (topStateNode != null) { topStateNode.quit(); topStateNode = null; handleEvaluateFalseEvent(); } if (InstrumentationHelper.ENABLED) { InstrumentationHelper.get().aPatternRootEvalFalse();} } public final void accept(EvalStateNodeVisitor visitor) { visitor.visitRoot(this); if (topStateNode != null) { topStateNode.accept(visitor); } } public boolean isFilterStateNode() { return false; } public boolean isNotOperator() { return false; } public boolean isFilterChildNonQuitting() { return false; } public boolean isObserverStateNodeNonRestarting() { return false; } public final String toString() { return "EvalRootStateNode topStateNode=" + topStateNode; } public EvalStateNode getTopStateNode() { return topStateNode; } public void removeMatch(Set<EventBean> matchEvent) { if (topStateNode != null) { topStateNode.removeMatch(matchEvent); } } private static final Log log = LogFactory.getLog(EvalRootStateNode.class); }
gpl-2.0
neeravbm/trial
tests/vendor/brianium/habitat/src/Habitat/Parser/ParserInterface.php
231
<?php namespace Habitat\Parser; interface ParserInterface { /** * Parse the environment variables into an associative array * * @param $content * @return array */ public function parse($content); }
gpl-2.0
opennms-forge/poc-nms-core
opennms-icmp/opennms-icmp-jna/src/main/java/org/opennms/netmgt/icmp/jna/JnaPingRequestId.java
4290
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.icmp.jna; import java.net.InetAddress; import org.opennms.core.utils.InetAddressComparator; /** * <p>JnaPingRequestId class.</p> * * @author ranger * @version $Id: $ */ public class JnaPingRequestId { private InetAddress m_addr; private int m_identifier; private int m_sequenceNumber; private long m_threadId; /** * <p>Constructor for JnaPingRequestId.</p> * * @param addr a {@link java.net.InetAddress} object. * @param identifier a long. * @param seqId a short. */ public JnaPingRequestId(InetAddress addr, int identifier, int sequenceNumber, long threadId) { m_addr = addr; m_identifier = identifier; m_sequenceNumber = sequenceNumber; m_threadId = threadId; } /** * <p>Constructor for JnaPingRequestId.</p> * * @param reply a {@link org.opennms.netmgt.icmp.spi.JnaPingReply.PingReply} object. */ public JnaPingRequestId(JnaPingReply reply) { this(reply.getAddress(), reply.getIdentifier(), reply.getSequenceNumber(), reply.getThreadId()); } /** * <p>getAddress</p> * * @return a {@link java.net.InetAddress} object. */ public InetAddress getAddress() { return m_addr; } /** * <p>getTid</p> * * @return a long. */ public int getIdentifier() { return m_identifier; } /** * <p>getSequenceId</p> * * @return a short. */ public int getSequenceNumber() { return m_sequenceNumber; } public long getThreadId() { return m_threadId; } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof JnaPingRequestId) { JnaPingRequestId id = (JnaPingRequestId)obj; return (new InetAddressComparator().compare(getAddress(), id.getAddress()) == 0) && getIdentifier() == id.getIdentifier() && getSequenceNumber() == id.getSequenceNumber() && getThreadId() == id.getThreadId(); } return false; } /** {@inheritDoc} */ @Override public int hashCode() { int hash = 1; hash = hash * 31 + m_addr.hashCode(); hash = hash * 31 + m_identifier; hash = hash * 31 + m_sequenceNumber; hash = hash * 31 + (int)(m_threadId >>> 32); hash = hash * 31 + (int)(m_threadId); return hash; } /** * <p>toString</p> * * @return a {@link java.lang.String} object. */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(getClass().getSimpleName()); buf.append('['); buf.append("addr = ").append(m_addr); buf.append(", "); buf.append("ident = ").append(m_identifier); buf.append(", "); buf.append("seqNum = ").append(m_sequenceNumber); buf.append(", "); buf.append("tId = ").append(m_threadId); buf.append(']'); return buf.toString(); } }
gpl-2.0
MAN-IN-WAN/Kob-Eye
Skins/VetoccitanT3/ReactSrc/node_modules/react-redux/lib/alternate-renderers.js
1239
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports.batch = void 0; var _Provider = _interopRequireDefault(require("./components/Provider")); exports.Provider = _Provider["default"]; var _connectAdvanced = _interopRequireDefault(require("./components/connectAdvanced")); exports.connectAdvanced = _connectAdvanced["default"]; var _Context = require("./components/Context"); exports.ReactReduxContext = _Context.ReactReduxContext; var _connect = _interopRequireDefault(require("./connect/connect")); exports.connect = _connect["default"]; var _useDispatch = require("./hooks/useDispatch"); exports.useDispatch = _useDispatch.useDispatch; var _useSelector = require("./hooks/useSelector"); exports.useSelector = _useSelector.useSelector; var _useStore = require("./hooks/useStore"); exports.useStore = _useStore.useStore; var _batch = require("./utils/batch"); var _shallowEqual = _interopRequireDefault(require("./utils/shallowEqual")); exports.shallowEqual = _shallowEqual["default"]; // For other renderers besides ReactDOM and React Native, use the default noop batch function var batch = (0, _batch.getBatch)(); exports.batch = batch;
gpl-2.0
davidvossel/pacemaker
cts/environment.py
27612
''' Classes related to producing and searching logs ''' __copyright__=''' Copyright (C) 2014 Andrew Beekhof <andrew@beekhof.net> Licensed under the GNU GPL. ''' # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. import sys, time, os, socket, random from cts.remote import * class Environment: def __init__(self, args): self.data = {} self.Nodes = [] self["DeadTime"] = 300 self["StartTime"] = 300 self["StableTime"] = 30 self["tests"] = [] self["IPagent"] = "IPaddr2" self["DoStandby"] = 1 self["DoFencing"] = 1 self["XmitLoss"] = "0.0" self["RecvLoss"] = "0.0" self["ClobberCIB"] = 0 self["CIBfilename"] = None self["CIBResource"] = 0 self["DoBSC"] = 0 self["use_logd"] = 0 self["oprofile"] = [] self["warn-inactive"] = 0 self["ListTests"] = 0 self["benchmark"] = 0 self["LogWatcher"] = "any" self["SyslogFacility"] = "daemon" self["LogFileName"] = "/var/log/messages" self["Schema"] = "pacemaker-2.0" self["Stack"] = "corosync" self["stonith-type"] = "external/ssh" self["stonith-params"] = "hostlist=all,livedangerously=yes" self["loop-minutes"] = 60 self["valgrind-prefix"] = None self["valgrind-procs"] = "attrd cib crmd lrmd pengine stonith-ng" self["valgrind-opts"] = """--leak-check=full --show-reachable=yes --trace-children=no --num-callers=25 --gen-suppressions=all --suppressions="""+CTSvars.CTS_home+"""/cts.supp""" self["experimental-tests"] = 0 self["container-tests"] = 0 self["valgrind-tests"] = 0 self["unsafe-tests"] = 1 self["loop-tests"] = 1 self["scenario"] = "random" self["stats"] = 0 self["docker"] = 0 self.RandomGen = random.Random() self.logger = LogFactory() self.SeedRandom() self.rsh = RemoteFactory().getInstance() self.target = "localhost" self.parse_args(args) self.discover() self.validate() def SeedRandom(self, seed=None): if not seed: seed = int(time.time()) self["RandSeed"] = seed self.RandomGen.seed(str(seed)) def dump(self): keys = [] for key in list(self.data.keys()): keys.append(key) keys.sort() for key in keys: self.logger.debug("Environment["+key+"]:\t"+str(self[key])) def keys(self): return self.data.keys() def has_key(self, key): if key == "nodes": return True return key in self.data def __getitem__(self, key): if str(key) == "0": raise ValueError("Bad call to 'foo in X', should reference 'foo in X.keys()' instead") if key == "nodes": return self.Nodes elif key == "Name": return self.get_stack_short() elif key in self.data: return self.data[key] else: return None def __setitem__(self, key, value): if key == "Stack": self.set_stack(value) elif key == "node-limit": self.data[key] = value self.filter_nodes() elif key == "nodes": self.Nodes = [] for node in value: # I don't think I need the IP address, etc. but this validates # the node name against /etc/hosts and/or DNS, so it's a # GoodThing(tm). try: n = node.strip() if self.data["docker"] == 0: socket.gethostbyname_ex(n) self.Nodes.append(n) except: self.logger.log(node+" not found in DNS... aborting") raise self.filter_nodes() else: self.data[key] = value def RandomNode(self): '''Choose a random node from the cluster''' return self.RandomGen.choice(self["nodes"]) def set_stack(self, name): # Normalize stack names if name == "heartbeat" or name == "lha": self.data["Stack"] = "heartbeat" elif name == "openais" or name == "ais" or name == "whitetank": self.data["Stack"] = "corosync (plugin v0)" elif name == "corosync" or name == "cs" or name == "mcp": self.data["Stack"] = "corosync 2.x" elif name == "cman": self.data["Stack"] = "corosync (cman)" elif name == "v1": self.data["Stack"] = "corosync (plugin v1)" elif name == "v0": self.data["Stack"] = "corosync (plugin v0)" else: raise ValueError("Unknown stack: "+name) sys.exit(1) def get_stack_short(self): # Create the Cluster Manager object if not "Stack" in self.data: return "unknown" elif self.data["Stack"] == "heartbeat": return "crm-lha" elif self.data["Stack"] == "corosync 2.x": if self["docker"]: return "crm-mcp-docker" else: return "crm-mcp" elif self.data["Stack"] == "corosync (cman)": return "crm-cman" elif self.data["Stack"] == "corosync (plugin v1)": return "crm-plugin-v1" elif self.data["Stack"] == "corosync (plugin v0)": return "crm-plugin-v0" else: LogFactory().log("Unknown stack: "+self["stack"]) raise ValueError("Unknown stack: "+self["stack"]) def detect_syslog(self): # Detect syslog variant if not "syslogd" in self.data: if self["have_systemd"]: # Systemd self["syslogd"] = self.rsh(self.target, "systemctl list-units | grep syslog.*\.service.*active.*running | sed 's:.service.*::'", stdout=1).strip() else: # SYS-V self["syslogd"] = self.rsh(self.target, "chkconfig --list | grep syslog.*on | awk '{print $1}' | head -n 1", stdout=1).strip() if not "syslogd" in self.data or not self["syslogd"]: # default self["syslogd"] = "rsyslog" def detect_at_boot(self): # Detect if the cluster starts at boot if not "at-boot" in self.data: atboot = 0 if self["have_systemd"]: # Systemd atboot = atboot or not self.rsh(self.target, "systemctl is-enabled heartbeat.service") atboot = atboot or not self.rsh(self.target, "systemctl is-enabled corosync.service") atboot = atboot or not self.rsh(self.target, "systemctl is-enabled pacemaker.service") else: # SYS-V atboot = atboot or not self.rsh(self.target, "chkconfig --list | grep -e corosync.*on -e heartbeat.*on -e pacemaker.*on") self["at-boot"] = atboot def detect_ip_offset(self): # Try to determin an offset for IPaddr resources if self["CIBResource"] and not "IPBase" in self.data: network=self.rsh(self.target, "ip addr | grep inet | grep -v -e link -e inet6 -e '/32' -e ' lo' | awk '{print $2}'", stdout=1).strip() self["IPBase"] = self.rsh(self.target, "nmap -sn -n %s | grep 'scan report' | awk '{print $NF}' | sed 's:(::' | sed 's:)::' | sort -V | tail -n 1" % network, stdout=1).strip() if not self["IPBase"]: self["IPBase"] = " fe80::1234:56:7890:1000" self.logger.log("Could not determine an offset for IPaddr resources. Perhaps nmap is not installed on the nodes.") self.logger.log("Defaulting to '%s', use --test-ip-base to override" % self["IPBase"]) elif int(self["IPBase"].split('.')[3]) >= 240: self.logger.log("Could not determine an offset for IPaddr resources. Upper bound is too high: %s %s" % (self["IPBase"], self["IPBase"].split('.')[3])) self["IPBase"] = " fe80::1234:56:7890:1000" self.logger.log("Defaulting to '%s', use --test-ip-base to override" % self["IPBase"]) def filter_nodes(self): if self["node-limit"] > 0: if len(self["nodes"]) > self["node-limit"]: self.logger.log("Limiting the number of nodes configured=%d (max=%d)" %(len(self["nodes"]), self["node-limit"])) while len(self["nodes"]) > self["node-limit"]: self["nodes"].pop(len(self["nodes"])-1) def validate(self): if len(self["nodes"]) < 1: print("No nodes specified!") sys.exit(1) def discover(self): self.target = random.Random().choice(self["nodes"]) master = socket.gethostname() # Use the IP where possible to avoid name lookup failures for ip in socket.gethostbyname_ex(master)[2]: if ip != "127.0.0.1": master = ip break; self["cts-master"] = master if not "have_systemd" in self.data: self["have_systemd"] = not self.rsh(self.target, "systemctl list-units") self.detect_syslog() self.detect_at_boot() self.detect_ip_offset() self.validate() def parse_args(self, args): skipthis=None if not args: args=sys.argv[1:] for i in range(0, len(args)): if skipthis: skipthis=None continue elif args[i] == "-l" or args[i] == "--limit-nodes": skipthis=1 self["node-limit"] = int(args[i+1]) elif args[i] == "-r" or args[i] == "--populate-resources": self["CIBResource"] = 1 self["ClobberCIB"] = 1 elif args[i] == "--outputfile": skipthis=1 self["OutputFile"] = args[i+1] LogFactory().add_file(self["OutputFile"]) elif args[i] == "-L" or args[i] == "--logfile": skipthis=1 self["LogWatcher"] = "remote" self["LogAuditDisabled"] = 1 self["LogFileName"] = args[i+1] elif args[i] == "--ip" or args[i] == "--test-ip-base": skipthis=1 self["IPBase"] = args[i+1] self["CIBResource"] = 1 self["ClobberCIB"] = 1 elif args[i] == "--oprofile": skipthis=1 self["oprofile"] = args[i+1].split(' ') elif args[i] == "--trunc": self["TruncateLog"]=1 elif args[i] == "--list-tests" or args[i] == "--list" : self["ListTests"]=1 elif args[i] == "--benchmark": self["benchmark"]=1 elif args[i] == "--bsc": self["DoBSC"] = 1 self["scenario"] = "basic-sanity" elif args[i] == "--qarsh": RemoteFactory().enable_qarsh() elif args[i] == "--docker": self["docker"] = 1 RemoteFactory().enable_docker() elif args[i] == "--stonith" or args[i] == "--fencing": skipthis=1 if args[i+1] == "1" or args[i+1] == "yes": self["DoFencing"]=1 elif args[i+1] == "0" or args[i+1] == "no": self["DoFencing"]=0 elif args[i+1] == "phd": self["DoStonith"]=1 self["stonith-type"] = "fence_phd_kvm" self["stonith-params"] = "pcmk_arg_map=domain:uname,delay=0" elif args[i+1] == "rhcs" or args[i+1] == "xvm" or args[i+1] == "virt": self["DoStonith"]=1 self["stonith-type"] = "fence_xvm" self["stonith-params"] = "pcmk_arg_map=domain:uname,delay=0" elif args[i+1] == "docker": self["DoStonith"]=1 self["stonith-type"] = "fence_docker_cts" elif args[i+1] == "scsi": self["DoStonith"]=1 self["stonith-type"] = "fence_scsi" self["stonith-params"] = "delay=0" elif args[i+1] == "ssh" or args[i+1] == "lha": self["DoStonith"]=1 self["stonith-type"] = "external/ssh" self["stonith-params"] = "hostlist=all,livedangerously=yes" elif args[i+1] == "north": self["DoStonith"]=1 self["stonith-type"] = "fence_apc" self["stonith-params"] = "ipaddr=north-apc,login=apc,passwd=apc,pcmk_host_map=north-01:2;north-02:3;north-03:4;north-04:5;north-05:6;north-06:7;north-07:9;north-08:10;north-09:11;north-10:12;north-11:13;north-12:14;north-13:15;north-14:18;north-15:17;north-16:19;" elif args[i+1] == "south": self["DoStonith"]=1 self["stonith-type"] = "fence_apc" self["stonith-params"] = "ipaddr=south-apc,login=apc,passwd=apc,pcmk_host_map=south-01:2;south-02:3;south-03:4;south-04:5;south-05:6;south-06:7;south-07:9;south-08:10;south-09:11;south-10:12;south-11:13;south-12:14;south-13:15;south-14:18;south-15:17;south-16:19;" elif args[i+1] == "east": self["DoStonith"]=1 self["stonith-type"] = "fence_apc" self["stonith-params"] = "ipaddr=east-apc,login=apc,passwd=apc,pcmk_host_map=east-01:2;east-02:3;east-03:4;east-04:5;east-05:6;east-06:7;east-07:9;east-08:10;east-09:11;east-10:12;east-11:13;east-12:14;east-13:15;east-14:18;east-15:17;east-16:19;" elif args[i+1] == "west": self["DoStonith"]=1 self["stonith-type"] = "fence_apc" self["stonith-params"] = "ipaddr=west-apc,login=apc,passwd=apc,pcmk_host_map=west-01:2;west-02:3;west-03:4;west-04:5;west-05:6;west-06:7;west-07:9;west-08:10;west-09:11;west-10:12;west-11:13;west-12:14;west-13:15;west-14:18;west-15:17;west-16:19;" elif args[i+1] == "openstack": self["DoStonith"]=1 self["stonith-type"] = "fence_openstack" print("Obtaining OpenStack credentials from the current environment") self["stonith-params"] = "region=%s,tenant=%s,auth=%s,user=%s,password=%s" % ( os.environ['OS_REGION_NAME'], os.environ['OS_TENANT_NAME'], os.environ['OS_AUTH_URL'], os.environ['OS_USERNAME'], os.environ['OS_PASSWORD'] ) elif args[i+1] == "rhevm": self["DoStonith"]=1 self["stonith-type"] = "fence_rhevm" print("Obtaining RHEV-M credentials from the current environment") self["stonith-params"] = "login=%s,passwd=%s,ipaddr=%s,ipport=%s,ssl=1,shell_timeout=10" % ( os.environ['RHEVM_USERNAME'], os.environ['RHEVM_PASSWORD'], os.environ['RHEVM_SERVER'], os.environ['RHEVM_PORT'], ) else: self.usage(args[i+1]) elif args[i] == "--stonith-type": self["stonith-type"] = args[i+1] skipthis=1 elif args[i] == "--stonith-args": self["stonith-params"] = args[i+1] skipthis=1 elif args[i] == "--standby": skipthis=1 if args[i+1] == "1" or args[i+1] == "yes": self["DoStandby"] = 1 elif args[i+1] == "0" or args[i+1] == "no": self["DoStandby"] = 0 else: self.usage(args[i+1]) elif args[i] == "--clobber-cib" or args[i] == "-c": self["ClobberCIB"] = 1 elif args[i] == "--cib-filename": skipthis=1 self["CIBfilename"] = args[i+1] elif args[i] == "--xmit-loss": try: float(args[i+1]) except ValueError: print("--xmit-loss parameter should be float") self.usage(args[i+1]) skipthis=1 self["XmitLoss"] = args[i+1] elif args[i] == "--recv-loss": try: float(args[i+1]) except ValueError: print("--recv-loss parameter should be float") self.usage(args[i+1]) skipthis=1 self["RecvLoss"] = args[i+1] elif args[i] == "--choose": skipthis=1 self["tests"].append(args[i+1]) self["scenario"] = "sequence" elif args[i] == "--nodes": skipthis=1 self["nodes"] = args[i+1].split(' ') elif args[i] == "-g" or args[i] == "--group" or args[i] == "--dsh-group": skipthis=1 self["OutputFile"] = "%s/cluster-%s.log" % (os.environ['HOME'], args[i+1]) LogFactory().add_file(self["OutputFile"], "CTS") dsh_file = "%s/.dsh/group/%s" % (os.environ['HOME'], args[i+1]) # Hacks to make my life easier if args[i+1] == "r6": self["Stack"] = "cman" self["DoStonith"]=1 self["stonith-type"] = "fence_xvm" self["stonith-params"] = "delay=0" self["IPBase"] = " fe80::1234:56:7890:4000" elif args[i+1] == "virt1": self["Stack"] = "corosync" self["DoStonith"]=1 self["stonith-type"] = "fence_xvm" self["stonith-params"] = "delay=0" self["IPBase"] = " fe80::1234:56:7890:1000" elif args[i+1] == "east16" or args[i+1] == "nsew": self["Stack"] = "corosync" self["DoStonith"]=1 self["stonith-type"] = "fence_apc" self["stonith-params"] = "ipaddr=east-apc,login=apc,passwd=apc,pcmk_host_map=east-01:2;east-02:3;east-03:4;east-04:5;east-05:6;east-06:7;east-07:9;east-08:10;east-09:11;east-10:12;east-11:13;east-12:14;east-13:15;east-14:18;east-15:17;east-16:19;" self["IPBase"] = " fe80::1234:56:7890:2000" if args[i+1] == "east16": # Requires newer python than available via nsew self["IPagent"] = "Dummy" elif args[i+1] == "corosync8": self["Stack"] = "corosync" self["DoStonith"]=1 self["stonith-type"] = "fence_rhevm" print("Obtaining RHEV-M credentials from the current environment") self["stonith-params"] = "login=%s,passwd=%s,ipaddr=%s,ipport=%s,ssl=1,shell_timeout=10" % ( os.environ['RHEVM_USERNAME'], os.environ['RHEVM_PASSWORD'], os.environ['RHEVM_SERVER'], os.environ['RHEVM_PORT'], ) self["IPBase"] = " fe80::1234:56:7890:3000" if os.path.isfile(dsh_file): self["nodes"] = [] f = open(dsh_file, 'r') for line in f: l = line.strip().rstrip() if not l.startswith('#'): self["nodes"].append(l) f.close() else: print("Unknown DSH group: %s" % args[i+1]) elif args[i] == "--syslog-facility" or args[i] == "--facility": skipthis=1 self["SyslogFacility"] = args[i+1] elif args[i] == "--seed": skipthis=1 self.SeedRandom(args[i+1]) elif args[i] == "--warn-inactive": self["warn-inactive"] = 1 elif args[i] == "--schema": skipthis=1 self["Schema"] = args[i+1] elif args[i] == "--ais": self["Stack"] = "openais" elif args[i] == "--at-boot" or args[i] == "--cluster-starts-at-boot": skipthis=1 if args[i+1] == "1" or args[i+1] == "yes": self["at-boot"] = 1 elif args[i+1] == "0" or args[i+1] == "no": self["at-boot"] = 0 else: self.usage(args[i+1]) elif args[i] == "--heartbeat" or args[i] == "--lha": self["Stack"] = "heartbeat" elif args[i] == "--hae": self["Stack"] = "openais" self["Schema"] = "hae" elif args[i] == "--stack": if args[i+1] == "fedora" or args[i+1] == "fedora-17" or args[i+1] == "fedora-18": self["Stack"] = "corosync" elif args[i+1] == "rhel-6": self["Stack"] = "cman" elif args[i+1] == "rhel-7": self["Stack"] = "corosync" else: self["Stack"] = args[i+1] skipthis=1 elif args[i] == "--once": self["scenario"] = "all-once" elif args[i] == "--boot": self["scenario"] = "boot" elif args[i] == "--valgrind-tests": self["valgrind-tests"] = 1 elif args[i] == "--valgrind-procs": self["valgrind-procs"] = args[i+1] skipthis = 1 elif args[i] == "--no-loop-tests": self["loop-tests"] = 0 elif args[i] == "--loop-minutes": skipthis=1 try: self["loop-minutes"]=int(args[i+1]) except ValueError: self.usage(args[i]) elif args[i] == "--no-unsafe-tests": self["unsafe-tests"] = 0 elif args[i] == "--experimental-tests": self["experimental-tests"] = 1 elif args[i] == "--container-tests": self["container-tests"] = 1 elif args[i] == "--set": skipthis=1 (name, value) = args[i+1].split('=') self[name] = value print("Setting %s = %s" % (name, value)) elif args[i] == "--help": self.usage(args[i], 0) elif args[i] == "--": break else: try: NumIter=int(args[i]) self["iterations"] = NumIter except ValueError: self.usage(args[i]) def usage(self, arg, status=1): if status: print("Illegal argument %s" % arg) print("usage: " + sys.argv[0] +" [options] number-of-iterations") print("\nCommon options: ") print("\t [--nodes 'node list'] list of cluster nodes separated by whitespace") print("\t [--group | -g 'name'] use the nodes listed in the named DSH group (~/.dsh/groups/$name)") print("\t [--limit-nodes max] only use the first 'max' cluster nodes supplied with --nodes") print("\t [--stack (v0|v1|cman|corosync|heartbeat|openais)] which cluster stack is installed") print("\t [--list-tests] list the valid tests") print("\t [--benchmark] add the timing information") print("\t ") print("Options that CTS will usually auto-detect correctly: ") print("\t [--logfile path] where should the test software look for logs from cluster nodes") print("\t [--syslog-facility name] which syslog facility should the test software log to") print("\t [--at-boot (1|0)] does the cluster software start at boot time") print("\t [--test-ip-base ip] offset for generated IP address resources") print("\t ") print("Options for release testing: ") print("\t [--populate-resources | -r] generate a sample configuration") print("\t [--choose name] run only the named test") print("\t [--stonith (1 | 0 | yes | no | rhcs | ssh)]") print("\t [--once] run all valid tests once") print("\t ") print("Additional (less common) options: ") print("\t [--clobber-cib | -c ] erase any existing configuration") print("\t [--outputfile path] optional location for the test software to write logs to") print("\t [--trunc] truncate logfile before starting") print("\t [--xmit-loss lost-rate(0.0-1.0)]") print("\t [--recv-loss lost-rate(0.0-1.0)]") print("\t [--standby (1 | 0 | yes | no)]") print("\t [--fencing (1 | 0 | yes | no | rhcs | lha | openstack )]") print("\t [--stonith-type type]") print("\t [--stonith-args name=value]") print("\t [--bsc]") print("\t [--no-loop-tests] dont run looping/time-based tests") print("\t [--no-unsafe-tests] dont run tests that are unsafe for use with ocfs2/drbd") print("\t [--valgrind-tests] include tests using valgrind") print("\t [--experimental-tests] include experimental tests") print("\t [--container-tests] include pacemaker_remote tests that run in lxc container resources") print("\t [--oprofile 'node list'] list of cluster nodes to run oprofile on]") print("\t [--qarsh] use the QARSH backdoor to access nodes instead of SSH") print("\t [--docker] Indicates nodes are docker nodes.") print("\t [--seed random_seed]") print("\t [--set option=value]") print("\t ") print("\t Example: ") print("\t python sys.argv[0] -g virt1 --stack cs -r --stonith ssh --schema pacemaker-1.0 500") sys.exit(status) class EnvFactory: instance = None def __init__(self): pass def getInstance(self, args=None): if not EnvFactory.instance: EnvFactory.instance = Environment(args) return EnvFactory.instance
gpl-2.0
waywardcoder/small_programs
fast_fibo/scala_version/fibs.scala
536
package com.waywardcode.math import java.math.BigInteger object FastFib { private val TWO = BigInteger.valueOf(2L) private def recFib(n: Int) : Tuple2[BigInteger,BigInteger] = { if(n == 0) { return (BigInteger.ZERO, BigInteger.ONE) } val (a,b) = recFib(n/2) val c = ((b multiply TWO) subtract a) multiply a val d = (a multiply a) add (b multiply b) (n & 1) match { case 0 => (c,d) case _ => (d, (c add d)) } } def apply(n: Int): BigInteger = recFib(n)._1 }
gpl-2.0
vcgato29/cygwin
winsup/cygwin/fhandler_socket.cc
68400
/* fhandler_socket.cc. See fhandler.h for a description of the fhandler classes. Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Red Hat, Inc. This file is part of Cygwin. This software is a copyrighted work licensed under the terms of the Cygwin license. Please consult the file "CYGWIN_LICENSE" for details. */ /* #define DEBUG_NEST_ON 1 */ #define __INSIDE_CYGWIN_NET__ #define USE_SYS_TYPES_FD_SET #define _BSDTYPES_DEFINED #include "winsup.h" #undef _BSDTYPES_DEFINED #ifdef __x86_64__ /* 2014-04-24: Current Mingw headers define sockaddr_in6 using u_long (8 byte) because a redefinition for LP64 systems is missing. This leads to a wrong definition and size of sockaddr_in6 when building with winsock headers. This definition is also required to use the right u_long type in subsequent function calls. */ #undef u_long #define u_long __ms_u_long #endif #include <ws2tcpip.h> #include <mswsock.h> #include <iphlpapi.h> #include "cygerrno.h" #include "security.h" #include "path.h" #include "fhandler.h" #include "dtable.h" #include "cygheap.h" #include <asm/byteorder.h> #include "cygwin/version.h" #include "perprocess.h" #include "shared_info.h" #include "sigproc.h" #include "wininfo.h" #include <unistd.h> #include <sys/param.h> #include <sys/acl.h> #include "cygtls.h" #include <sys/un.h> #include "ntdll.h" #include "miscfuncs.h" #define ASYNC_MASK (FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT) #define EVENT_MASK (FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT|FD_CLOSE) extern bool fdsock (cygheap_fdmanip& fd, const device *, SOCKET soc); extern "C" { int sscanf (const char *, const char *, ...); } /* End of "C" section */ static inline mode_t adjust_socket_file_mode (mode_t mode) { /* Kludge: Don't allow to remove read bit on socket files for user/group/other, if the accompanying write bit is set. It would be nice to have exact permissions on a socket file, but it's necessary that somebody able to access the socket can always read the contents of the socket file to avoid spurious "permission denied" messages. */ return mode | ((mode & (S_IWUSR | S_IWGRP | S_IWOTH)) << 1); } /* cygwin internal: map sockaddr into internet domain address */ int get_inet_addr (const struct sockaddr *in, int inlen, struct sockaddr_storage *out, int *outlen, int *type = NULL, int *secret = NULL) { int secret_buf [4]; int* secret_ptr = (secret ? : secret_buf); switch (in->sa_family) { case AF_LOCAL: /* Check for abstract socket. These are generated for AF_LOCAL datagram sockets in recv_internal, to allow a datagram server to use sendto after recvfrom. */ if (inlen >= (int) sizeof (in->sa_family) + 7 && in->sa_data[0] == '\0' && in->sa_data[1] == 'd' && in->sa_data[6] == '\0') { struct sockaddr_in addr; addr.sin_family = AF_INET; sscanf (in->sa_data + 2, "%04hx", &addr.sin_port); addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); *outlen = sizeof addr; memcpy (out, &addr, *outlen); return 0; } break; case AF_INET: memcpy (out, in, inlen); *outlen = inlen; /* If the peer address given in connect or sendto is the ANY address, Winsock fails with WSAEADDRNOTAVAIL, while Linux converts that into a connection/send attempt to LOOPBACK. We're doing the same here. */ if (((struct sockaddr_in *) out)->sin_addr.s_addr == htonl (INADDR_ANY)) ((struct sockaddr_in *) out)->sin_addr.s_addr = htonl (INADDR_LOOPBACK); return 0; case AF_INET6: memcpy (out, in, inlen); *outlen = inlen; /* See comment in AF_INET case. */ if (IN6_IS_ADDR_UNSPECIFIED (&((struct sockaddr_in6 *) out)->sin6_addr)) ((struct sockaddr_in6 *) out)->sin6_addr = in6addr_loopback; return 0; default: set_errno (EAFNOSUPPORT); return SOCKET_ERROR; } /* AF_LOCAL/AF_UNIX only */ path_conv pc (in->sa_data, PC_SYM_FOLLOW); if (pc.error) { set_errno (pc.error); return SOCKET_ERROR; } if (!pc.exists ()) { set_errno (ENOENT); return SOCKET_ERROR; } /* Do NOT test for the file being a socket file here. The socket file creation is not an atomic operation, so there is a chance that socket files which are just in the process of being created are recognized as non-socket files. To work around this problem we now create the file with all sharing disabled. If the below NtOpenFile fails with STATUS_SHARING_VIOLATION we know that the file already exists, but the creating process isn't finished yet. So we yield and try again, until we can either open the file successfully, or some error other than STATUS_SHARING_VIOLATION occurs. Since we now don't know if the file is actually a socket file, we perform this check here explicitely. */ NTSTATUS status; HANDLE fh; OBJECT_ATTRIBUTES attr; IO_STATUS_BLOCK io; pc.get_object_attr (attr, sec_none_nih); do { status = NtOpenFile (&fh, GENERIC_READ | SYNCHRONIZE, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT | FILE_NON_DIRECTORY_FILE); if (status == STATUS_SHARING_VIOLATION) { /* While we hope that the sharing violation is only temporary, we also could easily get stuck here, waiting for a file in use by some greedy Win32 application. Therefore we should never wait endlessly without checking for signals and thread cancel event. */ pthread_testcancel (); if (cygwait (NULL, cw_nowait, cw_sig_eintr) == WAIT_SIGNALED && !_my_tls.call_signal_handler ()) { set_errno (EINTR); return SOCKET_ERROR; } yield (); } else if (!NT_SUCCESS (status)) { __seterrno_from_nt_status (status); return SOCKET_ERROR; } } while (status == STATUS_SHARING_VIOLATION); /* Now test for the SYSTEM bit. */ FILE_BASIC_INFORMATION fbi; status = NtQueryInformationFile (fh, &io, &fbi, sizeof fbi, FileBasicInformation); if (!NT_SUCCESS (status)) { __seterrno_from_nt_status (status); return SOCKET_ERROR; } if (!(fbi.FileAttributes & FILE_ATTRIBUTE_SYSTEM)) { NtClose (fh); set_errno (EBADF); return SOCKET_ERROR; } /* Eventually check the content and fetch the required information. */ char buf[128]; memset (buf, 0, sizeof buf); status = NtReadFile (fh, NULL, NULL, NULL, &io, buf, 128, NULL, NULL); NtClose (fh); if (NT_SUCCESS (status)) { struct sockaddr_in sin; char ctype; sin.sin_family = AF_INET; if (strncmp (buf, SOCKET_COOKIE, strlen (SOCKET_COOKIE))) { set_errno (EBADF); return SOCKET_ERROR; } sscanf (buf + strlen (SOCKET_COOKIE), "%hu %c %08x-%08x-%08x-%08x", &sin.sin_port, &ctype, secret_ptr, secret_ptr + 1, secret_ptr + 2, secret_ptr + 3); sin.sin_port = htons (sin.sin_port); sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); memcpy (out, &sin, sizeof sin); *outlen = sizeof sin; if (type) *type = (ctype == 's' ? SOCK_STREAM : ctype == 'd' ? SOCK_DGRAM : 0); return 0; } __seterrno_from_nt_status (status); return SOCKET_ERROR; } /**********************************************************************/ /* fhandler_socket */ fhandler_socket::fhandler_socket () : fhandler_base (), wsock_events (NULL), wsock_mtx (NULL), wsock_evt (NULL), prot_info_ptr (NULL), sun_path (NULL), peer_sun_path (NULL), status () { need_fork_fixup (true); } fhandler_socket::~fhandler_socket () { if (prot_info_ptr) cfree (prot_info_ptr); if (sun_path) cfree (sun_path); if (peer_sun_path) cfree (peer_sun_path); } char * fhandler_socket::get_proc_fd_name (char *buf) { __small_sprintf (buf, "socket:[%lu]", get_socket ()); return buf; } int fhandler_socket::open (int flags, mode_t mode) { set_errno (ENXIO); return 0; } void fhandler_socket::af_local_set_sockpair_cred () { sec_pid = sec_peer_pid = getpid (); sec_uid = sec_peer_uid = geteuid32 (); sec_gid = sec_peer_gid = getegid32 (); } void fhandler_socket::af_local_setblocking (bool &async, bool &nonblocking) { async = async_io (); nonblocking = is_nonblocking (); if (async) { WSAAsyncSelect (get_socket (), winmsg, 0, 0); WSAEventSelect (get_socket (), wsock_evt, EVENT_MASK); } set_nonblocking (false); async_io (false); } void fhandler_socket::af_local_unsetblocking (bool async, bool nonblocking) { if (nonblocking) set_nonblocking (true); if (async) { WSAAsyncSelect (get_socket (), winmsg, WM_ASYNCIO, ASYNC_MASK); async_io (true); } } bool fhandler_socket::af_local_recv_secret () { int out[4] = { 0, 0, 0, 0 }; int rest = sizeof out; char *ptr = (char *) out; while (rest > 0) { int ret = recvfrom (ptr, rest, 0, NULL, NULL); if (ret <= 0) break; rest -= ret; ptr += ret; } if (rest == 0) { debug_printf ("Received af_local secret: %08x-%08x-%08x-%08x", out[0], out[1], out[2], out[3]); if (out[0] != connect_secret[0] || out[1] != connect_secret[1] || out[2] != connect_secret[2] || out[3] != connect_secret[3]) { debug_printf ("Receiving af_local secret mismatch"); return false; } } else debug_printf ("Receiving af_local secret failed"); return rest == 0; } bool fhandler_socket::af_local_send_secret () { int rest = sizeof connect_secret; char *ptr = (char *) connect_secret; while (rest > 0) { int ret = sendto (ptr, rest, 0, NULL, 0); if (ret <= 0) break; rest -= ret; ptr += ret; } debug_printf ("Sending af_local secret %s", rest == 0 ? "succeeded" : "failed"); return rest == 0; } bool fhandler_socket::af_local_recv_cred () { struct ucred out = { (pid_t) 0, (uid_t) -1, (gid_t) -1 }; int rest = sizeof out; char *ptr = (char *) &out; while (rest > 0) { int ret = recvfrom (ptr, rest, 0, NULL, NULL); if (ret <= 0) break; rest -= ret; ptr += ret; } if (rest == 0) { debug_printf ("Received eid credentials: pid: %d, uid: %d, gid: %d", out.pid, out.uid, out.gid); sec_peer_pid = out.pid; sec_peer_uid = out.uid; sec_peer_gid = out.gid; } else debug_printf ("Receiving eid credentials failed"); return rest == 0; } bool fhandler_socket::af_local_send_cred () { struct ucred in = { sec_pid, sec_uid, sec_gid }; int rest = sizeof in; char *ptr = (char *) &in; while (rest > 0) { int ret = sendto (ptr, rest, 0, NULL, 0); if (ret <= 0) break; rest -= ret; ptr += ret; } if (rest == 0) debug_printf ("Sending eid credentials succeeded"); else debug_printf ("Sending eid credentials failed"); return rest == 0; } int fhandler_socket::af_local_connect () { bool orig_async_io, orig_is_nonblocking; if (get_addr_family () != AF_LOCAL || get_socket_type () != SOCK_STREAM) return 0; debug_printf ("af_local_connect called, no_getpeereid=%d", no_getpeereid ()); if (no_getpeereid ()) return 0; af_local_setblocking (orig_async_io, orig_is_nonblocking); if (!af_local_send_secret () || !af_local_recv_secret () || !af_local_send_cred () || !af_local_recv_cred ()) { debug_printf ("accept from unauthorized server"); ::shutdown (get_socket (), SD_BOTH); WSASetLastError (WSAECONNREFUSED); return -1; } af_local_unsetblocking (orig_async_io, orig_is_nonblocking); return 0; } int fhandler_socket::af_local_accept () { bool orig_async_io, orig_is_nonblocking; debug_printf ("af_local_accept called, no_getpeereid=%d", no_getpeereid ()); if (no_getpeereid ()) return 0; af_local_setblocking (orig_async_io, orig_is_nonblocking); if (!af_local_recv_secret () || !af_local_send_secret () || !af_local_recv_cred () || !af_local_send_cred ()) { debug_printf ("connect from unauthorized client"); ::shutdown (get_socket (), SD_BOTH); ::closesocket (get_socket ()); WSASetLastError (WSAECONNABORTED); return -1; } af_local_unsetblocking (orig_async_io, orig_is_nonblocking); return 0; } int fhandler_socket::af_local_set_no_getpeereid () { if (get_addr_family () != AF_LOCAL || get_socket_type () != SOCK_STREAM) { set_errno (EINVAL); return -1; } if (connect_state () != unconnected) { set_errno (EALREADY); return -1; } debug_printf ("no_getpeereid set"); no_getpeereid (true); return 0; } void fhandler_socket::af_local_set_cred () { sec_pid = getpid (); sec_uid = geteuid32 (); sec_gid = getegid32 (); sec_peer_pid = (pid_t) 0; sec_peer_uid = (uid_t) -1; sec_peer_gid = (gid_t) -1; } void fhandler_socket::af_local_copy (fhandler_socket *sock) { sock->connect_secret[0] = connect_secret[0]; sock->connect_secret[1] = connect_secret[1]; sock->connect_secret[2] = connect_secret[2]; sock->connect_secret[3] = connect_secret[3]; sock->sec_pid = sec_pid; sock->sec_uid = sec_uid; sock->sec_gid = sec_gid; sock->sec_peer_pid = sec_peer_pid; sock->sec_peer_uid = sec_peer_uid; sock->sec_peer_gid = sec_peer_gid; sock->no_getpeereid (no_getpeereid ()); } void fhandler_socket::af_local_set_secret (char *buf) { if (!fhandler_dev_random::crypt_gen_random (connect_secret, sizeof (connect_secret))) bzero ((char*) connect_secret, sizeof (connect_secret)); __small_sprintf (buf, "%08x-%08x-%08x-%08x", connect_secret [0], connect_secret [1], connect_secret [2], connect_secret [3]); } /* Maximum number of concurrently opened sockets from all Cygwin processes per session. Note that shared sockets (through dup/fork/exec) are counted as one socket. */ #define NUM_SOCKS (32768 / sizeof (wsa_event)) #define LOCK_EVENTS WaitForSingleObject (wsock_mtx, INFINITE) #define UNLOCK_EVENTS ReleaseMutex (wsock_mtx) static wsa_event wsa_events[NUM_SOCKS] __attribute__((section (".cygwin_dll_common"), shared)); static LONG socket_serial_number __attribute__((section (".cygwin_dll_common"), shared)); static HANDLE wsa_slot_mtx; static PWCHAR sock_shared_name (PWCHAR buf, LONG num) { __small_swprintf (buf, L"socket.%d", num); return buf; } static wsa_event * search_wsa_event_slot (LONG new_serial_number) { WCHAR name[32], searchname[32]; UNICODE_STRING uname; OBJECT_ATTRIBUTES attr; NTSTATUS status; if (!wsa_slot_mtx) { RtlInitUnicodeString (&uname, sock_shared_name (name, 0)); InitializeObjectAttributes (&attr, &uname, OBJ_INHERIT | OBJ_OPENIF, get_session_parent_dir (), everyone_sd (CYG_MUTANT_ACCESS)); status = NtCreateMutant (&wsa_slot_mtx, CYG_MUTANT_ACCESS, &attr, FALSE); if (!NT_SUCCESS (status)) api_fatal ("Couldn't create/open shared socket mutex %S, %y", &uname, status); } switch (WaitForSingleObject (wsa_slot_mtx, INFINITE)) { case WAIT_OBJECT_0: case WAIT_ABANDONED: break; default: api_fatal ("WFSO failed for shared socket mutex, %E"); break; } unsigned int slot = new_serial_number % NUM_SOCKS; while (wsa_events[slot].serial_number) { HANDLE searchmtx; RtlInitUnicodeString (&uname, sock_shared_name (searchname, wsa_events[slot].serial_number)); InitializeObjectAttributes (&attr, &uname, 0, get_session_parent_dir (), NULL); status = NtOpenMutant (&searchmtx, READ_CONTROL, &attr); if (!NT_SUCCESS (status)) break; /* Mutex still exists, attached socket is active, try next slot. */ NtClose (searchmtx); slot = (slot + 1) % NUM_SOCKS; if (slot == (new_serial_number % NUM_SOCKS)) { /* Did the whole array once. Too bad. */ debug_printf ("No free socket slot"); ReleaseMutex (wsa_slot_mtx); return NULL; } } memset (&wsa_events[slot], 0, sizeof (wsa_event)); wsa_events[slot].serial_number = new_serial_number; ReleaseMutex (wsa_slot_mtx); return wsa_events + slot; } bool fhandler_socket::init_events () { LONG new_serial_number; WCHAR name[32]; UNICODE_STRING uname; OBJECT_ATTRIBUTES attr; NTSTATUS status; do { new_serial_number = InterlockedIncrement (&socket_serial_number); if (!new_serial_number) /* 0 is reserved for global mutex */ InterlockedIncrement (&socket_serial_number); RtlInitUnicodeString (&uname, sock_shared_name (name, new_serial_number)); InitializeObjectAttributes (&attr, &uname, OBJ_INHERIT | OBJ_OPENIF, get_session_parent_dir (), everyone_sd (CYG_MUTANT_ACCESS)); status = NtCreateMutant (&wsock_mtx, CYG_MUTANT_ACCESS, &attr, FALSE); if (!NT_SUCCESS (status)) { debug_printf ("NtCreateMutant(%S), %y", &uname, status); set_errno (ENOBUFS); return false; } if (status == STATUS_OBJECT_NAME_EXISTS) NtClose (wsock_mtx); } while (status == STATUS_OBJECT_NAME_EXISTS); if ((wsock_evt = CreateEvent (&sec_all, TRUE, FALSE, NULL)) == WSA_INVALID_EVENT) { debug_printf ("CreateEvent, %E"); set_errno (ENOBUFS); NtClose (wsock_mtx); return false; } if (WSAEventSelect (get_socket (), wsock_evt, EVENT_MASK) == SOCKET_ERROR) { debug_printf ("WSAEventSelect, %E"); set_winsock_errno (); NtClose (wsock_evt); NtClose (wsock_mtx); return false; } wsock_events = search_wsa_event_slot (new_serial_number); /* sock type not yet set here. */ if (pc.dev == FH_UDP || pc.dev == FH_DGRAM) wsock_events->events = FD_WRITE; return true; } int fhandler_socket::evaluate_events (const long event_mask, long &events, const bool erase) { int ret = 0; long events_now = 0; WSANETWORKEVENTS evts = { 0 }; if (!(WSAEnumNetworkEvents (get_socket (), wsock_evt, &evts))) { if (evts.lNetworkEvents) { LOCK_EVENTS; wsock_events->events |= evts.lNetworkEvents; events_now = (wsock_events->events & event_mask); if (evts.lNetworkEvents & FD_CONNECT) { wsock_events->connect_errorcode = evts.iErrorCode[FD_CONNECT_BIT]; /* Setting the connect_state and calling the AF_LOCAL handshake here allows to handle this stuff from a single point. This is independent of FD_CONNECT being requested. Consider a server calling connect(2) and then immediately poll(2) with only polling for POLLIN (example: postfix), or select(2) just asking for descriptors ready to read. Something weird occurs in Winsock: If you fork off and call recv/send on the duplicated, already connected socket, another FD_CONNECT event is generated in the child process. This would trigger a call to af_local_connect which obviously fail. Avoid this by calling set_connect_state only if connect_state is connect_pending. */ if (connect_state () == connect_pending) { if (wsock_events->connect_errorcode) connect_state (connect_failed); else if (af_local_connect ()) { wsock_events->connect_errorcode = WSAGetLastError (); connect_state (connect_failed); } else connect_state (connected); } } UNLOCK_EVENTS; if ((evts.lNetworkEvents & FD_OOB) && wsock_events->owner) kill (wsock_events->owner, SIGURG); } } LOCK_EVENTS; if ((events = events_now) != 0 || (events = (wsock_events->events & event_mask)) != 0) { if (events & FD_CONNECT) { int wsa_err = wsock_events->connect_errorcode; if (wsa_err) { /* CV 2014-04-23: This is really weird. If you call connect asynchronously on a socket and then select, an error like "Connection refused" is set in the event and in the SO_ERROR socket option. If you call connect, then dup, then select, the error is set in the event, but not in the SO_ERROR socket option, despite the dup'ed socket handle referring to the same socket. We're trying to workaround this problem here by taking the connect errorcode from the event and write it back into the SO_ERROR socket option. CV 2014-06-16: Call WSASetLastError *after* setsockopt since, apparently, setsockopt sets the last WSA error code to 0 on success. */ setsockopt (get_socket (), SOL_SOCKET, SO_ERROR, (const char *) &wsa_err, sizeof wsa_err); WSASetLastError (wsa_err); ret = SOCKET_ERROR; } else wsock_events->events |= FD_WRITE; wsock_events->events &= ~FD_CONNECT; wsock_events->connect_errorcode = 0; } /* This test makes the accept function behave as on Linux when accept is called on a socket for which shutdown for the read side has been called. The second half of this code is in the shutdown method. See there for more info. */ if ((event_mask & FD_ACCEPT) && (events & FD_CLOSE)) { WSASetLastError (WSAEINVAL); ret = SOCKET_ERROR; } if (erase) wsock_events->events &= ~(events & ~(FD_WRITE | FD_CLOSE)); } UNLOCK_EVENTS; return ret; } int fhandler_socket::wait_for_events (const long event_mask, const DWORD flags) { if (async_io ()) return 0; int ret; long events; while (!(ret = evaluate_events (event_mask, events, !(flags & MSG_PEEK))) && !events) { if (is_nonblocking () || (flags & MSG_DONTWAIT)) { WSASetLastError (WSAEWOULDBLOCK); return SOCKET_ERROR; } WSAEVENT ev[2] = { wsock_evt }; set_signal_arrived here (ev[1]); switch (WSAWaitForMultipleEvents (2, ev, FALSE, 50, FALSE)) { case WSA_WAIT_TIMEOUT: pthread_testcancel (); /*FALLTHRU*/ case WSA_WAIT_EVENT_0: break; case WSA_WAIT_EVENT_0 + 1: if (_my_tls.call_signal_handler ()) break; WSASetLastError (WSAEINTR); return SOCKET_ERROR; default: WSASetLastError (WSAEFAULT); return SOCKET_ERROR; } } return ret; } void fhandler_socket::release_events () { NtClose (wsock_evt); NtClose (wsock_mtx); } /* Called from net.cc:fdsock() if a freshly created socket is not inheritable. In that case we use fixup_before_fork_exec. See the comment in fdsock() for a description of the problem. */ void fhandler_socket::init_fixup_before () { prot_info_ptr = (LPWSAPROTOCOL_INFOW) cmalloc_abort (HEAP_BUF, sizeof (WSAPROTOCOL_INFOW)); cygheap->fdtab.inc_need_fixup_before (); } int fhandler_socket::fixup_before_fork_exec (DWORD win_pid) { SOCKET ret = WSADuplicateSocketW (get_socket (), win_pid, prot_info_ptr); if (ret) set_winsock_errno (); else debug_printf ("WSADuplicateSocket succeeded (%x)", prot_info_ptr->dwProviderReserved); return (int) ret; } void fhandler_socket::fixup_after_fork (HANDLE parent) { fork_fixup (parent, wsock_mtx, "wsock_mtx"); fork_fixup (parent, wsock_evt, "wsock_evt"); if (!need_fixup_before ()) { fhandler_base::fixup_after_fork (parent); return; } SOCKET new_sock = WSASocketW (FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, prot_info_ptr, 0, WSA_FLAG_OVERLAPPED); if (new_sock == INVALID_SOCKET) { set_winsock_errno (); set_io_handle ((HANDLE) INVALID_SOCKET); } else { /* Even though the original socket was not inheritable, the duplicated socket is potentially inheritable again. */ SetHandleInformation ((HANDLE) new_sock, HANDLE_FLAG_INHERIT, 0); set_io_handle ((HANDLE) new_sock); debug_printf ("WSASocket succeeded (%p)", new_sock); } } void fhandler_socket::fixup_after_exec () { if (need_fixup_before () && !close_on_exec ()) fixup_after_fork (NULL); } int fhandler_socket::dup (fhandler_base *child, int flags) { debug_printf ("here"); fhandler_socket *fhs = (fhandler_socket *) child; if (!DuplicateHandle (GetCurrentProcess (), wsock_mtx, GetCurrentProcess (), &fhs->wsock_mtx, 0, TRUE, DUPLICATE_SAME_ACCESS)) { __seterrno (); return -1; } if (!DuplicateHandle (GetCurrentProcess (), wsock_evt, GetCurrentProcess (), &fhs->wsock_evt, 0, TRUE, DUPLICATE_SAME_ACCESS)) { __seterrno (); NtClose (fhs->wsock_mtx); return -1; } if (get_addr_family () == AF_LOCAL) { fhs->set_sun_path (get_sun_path ()); fhs->set_peer_sun_path (get_peer_sun_path ()); } if (!need_fixup_before ()) { int ret = fhandler_base::dup (child, flags); if (ret) { NtClose (fhs->wsock_evt); NtClose (fhs->wsock_mtx); } return ret; } cygheap->user.deimpersonate (); fhs->init_fixup_before (); fhs->set_io_handle (get_io_handle ()); int ret = fhs->fixup_before_fork_exec (GetCurrentProcessId ()); cygheap->user.reimpersonate (); if (!ret) { fhs->fixup_after_fork (GetCurrentProcess ()); if (fhs->get_io_handle() != (HANDLE) INVALID_SOCKET) return 0; } cygheap->fdtab.dec_need_fixup_before (); NtClose (fhs->wsock_evt); NtClose (fhs->wsock_mtx); return -1; } int __reg2 fhandler_socket::fstat (struct stat *buf) { int res; if (get_device () == FH_UNIX) { res = fhandler_base::fstat_fs (buf); if (!res) { buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFSOCK; buf->st_size = 0; } } else { res = fhandler_base::fstat (buf); if (!res) { buf->st_dev = 0; buf->st_ino = (ino_t) ((uintptr_t) get_handle ()); buf->st_mode = S_IFSOCK | S_IRWXU | S_IRWXG | S_IRWXO; buf->st_size = 0; } } return res; } int __reg2 fhandler_socket::fstatvfs (struct statvfs *sfs) { if (get_device () == FH_UNIX) { fhandler_disk_file fh (pc); fh.get_device () = FH_FS; return fh.fstatvfs (sfs); } set_errno (EBADF); return -1; } int fhandler_socket::fchmod (mode_t mode) { if (get_device () == FH_UNIX) { fhandler_disk_file fh (pc); fh.get_device () = FH_FS; int ret = fh.fchmod (S_IFSOCK | adjust_socket_file_mode (mode)); return ret; } set_errno (EBADF); return -1; } int fhandler_socket::fchown (uid_t uid, gid_t gid) { if (get_device () == FH_UNIX) { fhandler_disk_file fh (pc); return fh.fchown (uid, gid); } set_errno (EBADF); return -1; } int fhandler_socket::facl (int cmd, int nentries, aclent_t *aclbufp) { if (get_device () == FH_UNIX) { fhandler_disk_file fh (pc); return fh.facl (cmd, nentries, aclbufp); } set_errno (EBADF); return -1; } int fhandler_socket::link (const char *newpath) { if (get_device () == FH_UNIX) { fhandler_disk_file fh (pc); return fh.link (newpath); } return fhandler_base::link (newpath); } int fhandler_socket::bind (const struct sockaddr *name, int namelen) { int res = -1; if (name->sa_family == AF_LOCAL) { #define un_addr ((struct sockaddr_un *) name) struct sockaddr_in sin; int len = namelen - offsetof (struct sockaddr_un, sun_path); /* Check that name is within bounds. Don't check if the string is NUL-terminated, because there are projects out there which set namelen to a value which doesn't cover the trailing NUL. */ if (len <= 1 || (len = strnlen (un_addr->sun_path, len)) > UNIX_PATH_MAX) { set_errno (len <= 1 ? (len == 1 ? ENOENT : EINVAL) : ENAMETOOLONG); goto out; } /* Copy over the sun_path string into a buffer big enough to add a trailing NUL. */ char sun_path[len + 1]; strncpy (sun_path, un_addr->sun_path, len); sun_path[len] = '\0'; /* This isn't entirely foolproof, but we check first if the file exists so we can return with EADDRINUSE before having bound the socket. This allows an application to call bind again on the same socket using another filename. If we bind first, the application will not be able to call bind successfully ever again. */ path_conv pc (sun_path, PC_SYM_FOLLOW); if (pc.error) { set_errno (pc.error); goto out; } if (pc.exists ()) { set_errno (EADDRINUSE); goto out; } sin.sin_family = AF_INET; sin.sin_port = 0; sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (::bind (get_socket (), (sockaddr *) &sin, len = sizeof sin)) { syscall_printf ("AF_LOCAL: bind failed"); set_winsock_errno (); goto out; } if (::getsockname (get_socket (), (sockaddr *) &sin, &len)) { syscall_printf ("AF_LOCAL: getsockname failed"); set_winsock_errno (); goto out; } sin.sin_port = ntohs (sin.sin_port); debug_printf ("AF_LOCAL: socket bound to port %u", sin.sin_port); mode_t mode = adjust_socket_file_mode ((S_IRWXU | S_IRWXG | S_IRWXO) & ~cygheap->umask); DWORD fattr = FILE_ATTRIBUTE_SYSTEM; if (!(mode & (S_IWUSR | S_IWGRP | S_IWOTH)) && !pc.has_acls ()) fattr |= FILE_ATTRIBUTE_READONLY; SECURITY_ATTRIBUTES sa = sec_none_nih; NTSTATUS status; HANDLE fh; OBJECT_ATTRIBUTES attr; IO_STATUS_BLOCK io; ULONG access = DELETE | FILE_GENERIC_WRITE; /* If the filesystem supports ACLs, we will overwrite the DACL after the call to NtCreateFile. This requires a handle with READ_CONTROL and WRITE_DAC access, otherwise get_file_sd and set_file_sd both have to open the file again. FIXME: On remote NTFS shares open sometimes fails because even the creator of the file doesn't have the right to change the DACL. I don't know what setting that is or how to recognize such a share, so for now we don't request WRITE_DAC on remote drives. */ if (pc.has_acls () && !pc.isremote ()) access |= READ_CONTROL | WRITE_DAC; status = NtCreateFile (&fh, access, pc.get_object_attr (attr, sa), &io, NULL, fattr, 0, FILE_CREATE, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT, NULL, 0); if (!NT_SUCCESS (status)) { if (io.Information == FILE_EXISTS) set_errno (EADDRINUSE); else __seterrno_from_nt_status (status); } else { if (pc.has_acls ()) set_file_attribute (fh, pc, ILLEGAL_UID, ILLEGAL_GID, S_JUSTCREATED | mode); char buf[sizeof (SOCKET_COOKIE) + 80]; __small_sprintf (buf, "%s%u %c ", SOCKET_COOKIE, sin.sin_port, get_socket_type () == SOCK_STREAM ? 's' : get_socket_type () == SOCK_DGRAM ? 'd' : '-'); af_local_set_secret (strchr (buf, '\0')); DWORD blen = strlen (buf) + 1; status = NtWriteFile (fh, NULL, NULL, NULL, &io, buf, blen, NULL, 0); if (!NT_SUCCESS (status)) { __seterrno_from_nt_status (status); FILE_DISPOSITION_INFORMATION fdi = { TRUE }; status = NtSetInformationFile (fh, &io, &fdi, sizeof fdi, FileDispositionInformation); if (!NT_SUCCESS (status)) debug_printf ("Setting delete dispostion failed, status = %y", status); } else { set_sun_path (sun_path); res = 0; } NtClose (fh); } #undef un_addr } else { if (!saw_reuseaddr ()) { /* If the application didn't explicitely request SO_REUSEADDR, enforce POSIX standard socket binding behaviour by setting the SO_EXCLUSIVEADDRUSE socket option. See cygwin_setsockopt() for a more detailed description. */ int on = 1; int ret = ::setsockopt (get_socket (), SOL_SOCKET, ~(SO_REUSEADDR), (const char *) &on, sizeof on); debug_printf ("%d = setsockopt(SO_EXCLUSIVEADDRUSE), %E", ret); } if (::bind (get_socket (), name, namelen)) set_winsock_errno (); else res = 0; } out: return res; } int fhandler_socket::connect (const struct sockaddr *name, int namelen) { struct sockaddr_storage sst; int type; if (get_inet_addr (name, namelen, &sst, &namelen, &type, connect_secret) == SOCKET_ERROR) return SOCKET_ERROR; if (get_addr_family () == AF_LOCAL) { if (get_socket_type () != type) { WSASetLastError (WSAEPROTOTYPE); set_winsock_errno (); return SOCKET_ERROR; } set_peer_sun_path (name->sa_data); /* Don't move af_local_set_cred into af_local_connect which may be called via select, possibly running under another identity. Call early here, because af_local_connect is called in wait_for_events. */ if (get_socket_type () == SOCK_STREAM) af_local_set_cred (); } /* Initialize connect state to "connect_pending". State is ultimately set to "connected" or "connect_failed" in wait_for_events when the FD_CONNECT event occurs. Note that the underlying OS sockets are always non-blocking and a successfully initiated non-blocking Winsock connect always returns WSAEWOULDBLOCK. Thus it's safe to rely on event handling. Check for either unconnected or connect_failed since in both cases it's allowed to retry connecting the socket. It's also ok (albeit ugly) to call connect to check if a previous non-blocking connect finished. Set connect_state before calling connect, otherwise a race condition with an already running select or poll might occur. */ if (connect_state () == unconnected || connect_state () == connect_failed) connect_state (connect_pending); int res = ::connect (get_socket (), (struct sockaddr *) &sst, namelen); if (!is_nonblocking () && res == SOCKET_ERROR && WSAGetLastError () == WSAEWOULDBLOCK) res = wait_for_events (FD_CONNECT | FD_CLOSE, 0); if (res) { DWORD err = WSAGetLastError (); /* Some applications use the ugly technique to check if a non-blocking connect succeeded by calling connect again, until it returns EISCONN. This circumvents the event handling and connect_state is never set. Thus we check for this situation here. */ if (err == WSAEISCONN) connect_state (connected); /* Winsock returns WSAEWOULDBLOCK if the non-blocking socket cannot be conected immediately. Convert to POSIX/Linux compliant EINPROGRESS. */ else if (is_nonblocking () && err == WSAEWOULDBLOCK) WSASetLastError (WSAEINPROGRESS); /* Winsock returns WSAEINVAL if the socket is already a listener. Convert to POSIX/Linux compliant EISCONN. */ else if (err == WSAEINVAL && connect_state () == listener) WSASetLastError (WSAEISCONN); /* Any other error except WSAEALREADY during connect_pending means the connect failed. */ else if (connect_state () == connect_pending && err != WSAEALREADY) connect_state (connect_failed); set_winsock_errno (); } return res; } int fhandler_socket::listen (int backlog) { int res = ::listen (get_socket (), backlog); if (res && WSAGetLastError () == WSAEINVAL) { /* It's perfectly valid to call listen on an unbound INET socket. In this case the socket is automatically bound to an unused port number, listening on all interfaces. On WinSock, listen fails with WSAEINVAL when it's called on an unbound socket. So we have to bind manually here to have POSIX semantics. */ if (get_addr_family () == AF_INET) { struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = 0; sin.sin_addr.s_addr = INADDR_ANY; if (!::bind (get_socket (), (struct sockaddr *) &sin, sizeof sin)) res = ::listen (get_socket (), backlog); } else if (get_addr_family () == AF_INET6) { struct sockaddr_in6 sin6; memset (&sin6, 0, sizeof sin6); sin6.sin6_family = AF_INET6; if (!::bind (get_socket (), (struct sockaddr *) &sin6, sizeof sin6)) res = ::listen (get_socket (), backlog); } } if (!res) { if (get_addr_family () == AF_LOCAL && get_socket_type () == SOCK_STREAM) af_local_set_cred (); connect_state (listener); /* gets set to connected on accepted socket. */ } else set_winsock_errno (); return res; } int fhandler_socket::accept4 (struct sockaddr *peer, int *len, int flags) { /* Allows NULL peer and len parameters. */ struct sockaddr_storage lpeer; int llen = sizeof (struct sockaddr_storage); int res = (int) INVALID_SOCKET; /* Windows event handling does not check for the validity of the desired flags so we have to do it here. */ if (connect_state () != listener) { WSASetLastError (WSAEINVAL); set_winsock_errno (); goto out; } while (!(res = wait_for_events (FD_ACCEPT | FD_CLOSE, 0)) && (res = ::accept (get_socket (), (struct sockaddr *) &lpeer, &llen)) == SOCKET_ERROR && WSAGetLastError () == WSAEWOULDBLOCK) ; if (res == (int) INVALID_SOCKET) set_winsock_errno (); else { cygheap_fdnew res_fd; if (res_fd >= 0 && fdsock (res_fd, &dev (), res)) { fhandler_socket *sock = (fhandler_socket *) res_fd; sock->set_addr_family (get_addr_family ()); sock->set_socket_type (get_socket_type ()); sock->async_io (false); /* fdsock switches async mode off. */ if (get_addr_family () == AF_LOCAL) { sock->set_sun_path (get_sun_path ()); sock->set_peer_sun_path (get_peer_sun_path ()); if (get_socket_type () == SOCK_STREAM) { /* Don't forget to copy credentials from accepting socket to accepted socket and start transaction on accepted socket! */ af_local_copy (sock); res = sock->af_local_accept (); if (res == -1) { res_fd.release (); set_winsock_errno (); goto out; } } } sock->set_nonblocking (flags & SOCK_NONBLOCK); if (flags & SOCK_CLOEXEC) sock->set_close_on_exec (true); /* No locking necessary at this point. */ sock->wsock_events->events = wsock_events->events | FD_WRITE; sock->wsock_events->owner = wsock_events->owner; sock->connect_state (connected); res = res_fd; if (peer) { if (get_addr_family () == AF_LOCAL) { /* FIXME: Right now we have no way to determine the bound socket name of the peer's socket. For now we just fake an unbound socket on the other side. */ static struct sockaddr_un un = { AF_LOCAL, "" }; memcpy (peer, &un, MIN (*len, (int) sizeof (un.sun_family))); *len = (int) sizeof (un.sun_family); } else { memcpy (peer, &lpeer, MIN (*len, llen)); *len = llen; } } } else { closesocket (res); res = -1; } } out: debug_printf ("res %d", res); return res; } int fhandler_socket::getsockname (struct sockaddr *name, int *namelen) { int res = -1; if (get_addr_family () == AF_LOCAL) { struct sockaddr_un sun; sun.sun_family = AF_LOCAL; sun.sun_path[0] = '\0'; if (get_sun_path ()) strncat (sun.sun_path, get_sun_path (), UNIX_PATH_MAX - 1); memcpy (name, &sun, MIN (*namelen, (int) SUN_LEN (&sun) + 1)); *namelen = (int) SUN_LEN (&sun) + (get_sun_path () ? 1 : 0); res = 0; } else { /* Always use a local big enough buffer and truncate later as necessary per POSIX. WinSock unfortunaltey only returns WSAEFAULT if the buffer is too small. */ struct sockaddr_storage sock; int len = sizeof sock; res = ::getsockname (get_socket (), (struct sockaddr *) &sock, &len); if (!res) { memcpy (name, &sock, MIN (*namelen, len)); *namelen = len; } else { if (WSAGetLastError () == WSAEINVAL) { /* WinSock returns WSAEINVAL if the socket is locally unbound. Per SUSv3 this is not an error condition. We're faking a valid return value here by creating the same content in the sockaddr structure as on Linux. */ memset (&sock, 0, sizeof sock); sock.ss_family = get_addr_family (); switch (get_addr_family ()) { case AF_INET: res = 0; len = (int) sizeof (struct sockaddr_in); break; case AF_INET6: res = 0; len = (int) sizeof (struct sockaddr_in6); break; default: WSASetLastError (WSAEOPNOTSUPP); break; } if (!res) { memcpy (name, &sock, MIN (*namelen, len)); *namelen = len; } } if (res) set_winsock_errno (); } } return res; } int fhandler_socket::getpeername (struct sockaddr *name, int *namelen) { /* Always use a local big enough buffer and truncate later as necessary per POSIX. WinSock unfortunately only returns WSAEFAULT if the buffer is too small. */ struct sockaddr_storage sock; int len = sizeof sock; int res = ::getpeername (get_socket (), (struct sockaddr *) &sock, &len); if (res) set_winsock_errno (); else if (get_addr_family () == AF_LOCAL) { struct sockaddr_un sun; memset (&sun, 0, sizeof sun); sun.sun_family = AF_LOCAL; sun.sun_path[0] = '\0'; if (get_peer_sun_path ()) strncat (sun.sun_path, get_peer_sun_path (), UNIX_PATH_MAX - 1); memcpy (name, &sun, MIN (*namelen, (int) SUN_LEN (&sun) + 1)); *namelen = (int) SUN_LEN (&sun) + (get_peer_sun_path () ? 1 : 0); } else { memcpy (name, &sock, MIN (*namelen, len)); *namelen = len; } return res; } /* There's no DLL which exports the symbol WSARecvMsg. One has to call WSAIoctl as below to fetch the function pointer. Why on earth did the MS developers decide not to export a normal symbol for these extension functions? */ inline int get_ext_funcptr (SOCKET sock, void *funcptr) { DWORD bret; const GUID guid = WSAID_WSARECVMSG; return WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER, (void *) &guid, sizeof (GUID), funcptr, sizeof (void *), &bret, NULL, NULL); } inline ssize_t fhandler_socket::recv_internal (LPWSAMSG wsamsg, bool use_recvmsg) { ssize_t res = 0; DWORD ret = 0, wret; int evt_mask = FD_READ | ((wsamsg->dwFlags & MSG_OOB) ? FD_OOB : 0); LPWSABUF &wsabuf = wsamsg->lpBuffers; ULONG &wsacnt = wsamsg->dwBufferCount; static NO_COPY LPFN_WSARECVMSG WSARecvMsg; int orig_namelen = wsamsg->namelen; /* CV 2014-10-26: Do not check for the connect_state at this point. In certain scenarios there's no way to check the connect state reliably. Example (hexchat): Parent process creates socket, forks, child process calls connect, parent process calls read. Even if the event handling allows to check for FD_CONNECT in the parent, there is always yet another scenario we can easily break. */ DWORD wait_flags = wsamsg->dwFlags; bool waitall = !!(wait_flags & MSG_WAITALL); wsamsg->dwFlags &= (MSG_OOB | MSG_PEEK | MSG_DONTROUTE); if (use_recvmsg) { if (!WSARecvMsg && get_ext_funcptr (get_socket (), &WSARecvMsg) == SOCKET_ERROR) { if (wsamsg->Control.len > 0) { set_winsock_errno (); return SOCKET_ERROR; } use_recvmsg = false; } else /* Only MSG_PEEK is supported by WSARecvMsg. */ wsamsg->dwFlags &= MSG_PEEK; } if (waitall) { if (get_socket_type () != SOCK_STREAM) { WSASetLastError (WSAEOPNOTSUPP); set_winsock_errno (); return SOCKET_ERROR; } if (is_nonblocking () || (wsamsg->dwFlags & (MSG_OOB | MSG_PEEK))) waitall = false; } /* Note: Don't call WSARecvFrom(MSG_PEEK) without actually having data waiting in the buffers, otherwise the event handling gets messed up for some reason. */ while (!(res = wait_for_events (evt_mask | FD_CLOSE, wait_flags)) || saw_shutdown_read ()) { if (use_recvmsg) res = WSARecvMsg (get_socket (), wsamsg, &wret, NULL, NULL); /* This is working around a really weird problem in WinSock. Assume you create a socket, fork the process (thus duplicating the socket), connect the socket in the child, then call recv on the original socket handle in the parent process. In this scenario, calls to WinSock's recvfrom and WSARecvFrom in the parent will fail with WSAEINVAL, regardless whether both address parameters, name and namelen, are NULL or point to valid storage. However, calls to recv and WSARecv succeed as expected. Per MSDN, WSAEINVAL in the context of recv means "The socket has not been bound". It is as if the recvfrom functions test if the socket is bound locally, but in the parent process, WinSock doesn't know about that and fails, while the same test is omitted in the recv functions. This also covers another weird case: WinSock returns WSAEFAULT if namelen is a valid pointer while name is NULL. Both parameters are ignored for TCP sockets, so this only occurs when using UDP socket. */ else if (!wsamsg->name || get_socket_type () == SOCK_STREAM) res = WSARecv (get_socket (), wsabuf, wsacnt, &wret, &wsamsg->dwFlags, NULL, NULL); else res = WSARecvFrom (get_socket (), wsabuf, wsacnt, &wret, &wsamsg->dwFlags, wsamsg->name, &wsamsg->namelen, NULL, NULL); if (!res) { ret += wret; if (!waitall) break; while (wret && wsacnt) { if (wsabuf->len > wret) { wsabuf->len -= wret; wsabuf->buf += wret; wret = 0; } else { wret -= wsabuf->len; ++wsabuf; --wsacnt; } } if (!wret) break; } else if (WSAGetLastError () != WSAEWOULDBLOCK) break; } if (res) { /* According to SUSv3, errno isn't set in that case and no error condition is returned. */ if (WSAGetLastError () == WSAEMSGSIZE) ret += wret; else if (!ret) { /* ESHUTDOWN isn't defined for recv in SUSv3. Simply EOF is returned in this case. */ if (WSAGetLastError () == WSAESHUTDOWN) ret = 0; else { set_winsock_errno (); return SOCKET_ERROR; } } } if (get_addr_family () == AF_LOCAL && wsamsg->name != NULL && orig_namelen >= (int) sizeof (sa_family_t)) { /* WSARecvFrom copied the sockaddr_in block to wsamsg->name. We have to overwrite it with a sockaddr_un block. For datagram sockets we generate a sockaddr_un with a filename analogue to abstract socket names under Linux. See `man 7 unix' under Linux for a description. */ sockaddr_un *un = (sockaddr_un *) wsamsg->name; un->sun_family = AF_LOCAL; int len = orig_namelen - offsetof (struct sockaddr_un, sun_path); if (len > 0) { if (get_socket_type () == SOCK_DGRAM) { if (len >= 7) { __small_sprintf (un->sun_path + 1, "d%04x", ((struct sockaddr_in *) wsamsg->name)->sin_port); wsamsg->namelen = offsetof (struct sockaddr_un, sun_path) + 7; } else wsamsg->namelen = offsetof (struct sockaddr_un, sun_path) + 1; un->sun_path[0] = '\0'; } else if (!get_peer_sun_path ()) wsamsg->namelen = sizeof (sa_family_t); else { memset (un->sun_path, 0, len); strncpy (un->sun_path, get_peer_sun_path (), len); if (un->sun_path[len - 1] == '\0') len = strlen (un->sun_path) + 1; if (len > UNIX_PATH_MAX) len = UNIX_PATH_MAX; wsamsg->namelen = offsetof (struct sockaddr_un, sun_path) + len; } } } return ret; } void __reg3 fhandler_socket::read (void *in_ptr, size_t& len) { char *ptr = (char *) in_ptr; #ifdef __x86_64__ /* size_t is 64 bit, but the len member in WSABUF is 32 bit. Split buffer if necessary. */ DWORD bufcnt = len / UINT32_MAX + ((!len || (len % UINT32_MAX)) ? 1 : 0); WSABUF wsabuf[bufcnt]; WSAMSG wsamsg = { NULL, 0, wsabuf, bufcnt, { 0, NULL }, 0 }; /* Don't use len as loop condition, it could be 0. */ for (WSABUF *wsaptr = wsabuf; bufcnt--; ++wsaptr) { wsaptr->len = MIN (len, UINT32_MAX); wsaptr->buf = ptr; len -= wsaptr->len; ptr += wsaptr->len; } #else WSABUF wsabuf = { len, ptr }; WSAMSG wsamsg = { NULL, 0, &wsabuf, 1, { 0, NULL }, 0 }; #endif len = recv_internal (&wsamsg, false); } ssize_t fhandler_socket::readv (const struct iovec *const iov, const int iovcnt, ssize_t tot) { WSABUF wsabuf[iovcnt]; WSABUF *wsaptr = wsabuf + iovcnt; const struct iovec *iovptr = iov + iovcnt; while (--wsaptr >= wsabuf) { wsaptr->len = (--iovptr)->iov_len; wsaptr->buf = (char *) iovptr->iov_base; } WSAMSG wsamsg = { NULL, 0, wsabuf, (DWORD) iovcnt, { 0, NULL}, 0 }; return recv_internal (&wsamsg, false); } ssize_t fhandler_socket::recvfrom (void *in_ptr, size_t len, int flags, struct sockaddr *from, int *fromlen) { char *ptr = (char *) in_ptr; #ifdef __x86_64__ /* size_t is 64 bit, but the len member in WSABUF is 32 bit. Split buffer if necessary. */ DWORD bufcnt = len / UINT32_MAX + ((!len || (len % UINT32_MAX)) ? 1 : 0); WSABUF wsabuf[bufcnt]; WSAMSG wsamsg = { from, from && fromlen ? *fromlen : 0, wsabuf, bufcnt, { 0, NULL }, (DWORD) flags }; /* Don't use len as loop condition, it could be 0. */ for (WSABUF *wsaptr = wsabuf; bufcnt--; ++wsaptr) { wsaptr->len = MIN (len, UINT32_MAX); wsaptr->buf = ptr; len -= wsaptr->len; ptr += wsaptr->len; } #else WSABUF wsabuf = { len, ptr }; WSAMSG wsamsg = { from, from && fromlen ? *fromlen : 0, &wsabuf, 1, { 0, NULL}, (DWORD) flags }; #endif ssize_t ret = recv_internal (&wsamsg, false); if (fromlen) *fromlen = wsamsg.namelen; return ret; } ssize_t fhandler_socket::recvmsg (struct msghdr *msg, int flags) { /* TODO: Descriptor passing on AF_LOCAL sockets. */ /* Disappointing but true: Even if WSARecvMsg is supported, it's only supported for datagram and raw sockets. */ bool use_recvmsg = true; if (get_socket_type () == SOCK_STREAM || get_addr_family () == AF_LOCAL) { use_recvmsg = false; msg->msg_controllen = 0; } WSABUF wsabuf[msg->msg_iovlen]; WSABUF *wsaptr = wsabuf + msg->msg_iovlen; const struct iovec *iovptr = msg->msg_iov + msg->msg_iovlen; while (--wsaptr >= wsabuf) { wsaptr->len = (--iovptr)->iov_len; wsaptr->buf = (char *) iovptr->iov_base; } WSAMSG wsamsg = { (struct sockaddr *) msg->msg_name, msg->msg_namelen, wsabuf, (DWORD) msg->msg_iovlen, { (DWORD) msg->msg_controllen, (char *) msg->msg_control }, (DWORD) flags }; ssize_t ret = recv_internal (&wsamsg, use_recvmsg); if (ret >= 0) { msg->msg_namelen = wsamsg.namelen; msg->msg_controllen = wsamsg.Control.len; if (!CYGWIN_VERSION_CHECK_FOR_USING_ANCIENT_MSGHDR) msg->msg_flags = wsamsg.dwFlags; } return ret; } inline ssize_t fhandler_socket::send_internal (struct _WSAMSG *wsamsg, int flags) { ssize_t res = 0; DWORD ret = 0, err = 0, sum = 0; WSABUF out_buf[wsamsg->dwBufferCount]; bool use_sendmsg = false; DWORD wait_flags = flags & MSG_DONTWAIT; bool nosignal = !!(flags & MSG_NOSIGNAL); flags &= (MSG_OOB | MSG_DONTROUTE); if (wsamsg->Control.len > 0) use_sendmsg = true; /* Workaround for MSDN KB 823764: Split a message into chunks <= SO_SNDBUF. in_idx is the index of the current lpBuffers from the input wsamsg buffer. in_off is used to keep track of the next byte to write from a wsamsg buffer which only gets partially written. */ for (DWORD in_idx = 0, in_off = 0; in_idx < wsamsg->dwBufferCount; in_off >= wsamsg->lpBuffers[in_idx].len && (++in_idx, in_off = 0)) { /* Split a message into the least number of pieces to minimize the number of WsaSendTo calls. Don't split datagram messages (bad idea). out_idx is the index of the next buffer in the out_buf WSABUF, also the number of buffers given to WSASendTo. out_len is the number of bytes in the buffers given to WSASendTo. Don't split datagram messages (very bad idea). */ DWORD out_idx = 0; DWORD out_len = 0; if (get_socket_type () == SOCK_STREAM) { do { out_buf[out_idx].buf = wsamsg->lpBuffers[in_idx].buf + in_off; out_buf[out_idx].len = wsamsg->lpBuffers[in_idx].len - in_off; out_len += out_buf[out_idx].len; out_idx++; } while (out_len < (unsigned) wmem () && (in_off = 0, ++in_idx < wsamsg->dwBufferCount)); /* Tweak len of the last out_buf buffer so the entire number of bytes is (less than or) equal to wmem (). Fix out_len as well since it's used in a subsequent test expression. */ if (out_len > (unsigned) wmem ()) { out_buf[out_idx - 1].len -= out_len - (unsigned) wmem (); out_len = (unsigned) wmem (); } /* Add the bytes written from the current last buffer to in_off, so in_off points to the next byte to be written from that buffer, or beyond which lets the outper loop skip to the next buffer. */ in_off += out_buf[out_idx - 1].len; } do { if (use_sendmsg) res = WSASendMsg (get_socket (), wsamsg, flags, &ret, NULL, NULL); else if (get_socket_type () == SOCK_STREAM) res = WSASendTo (get_socket (), out_buf, out_idx, &ret, flags, wsamsg->name, wsamsg->namelen, NULL, NULL); else res = WSASendTo (get_socket (), wsamsg->lpBuffers, wsamsg->dwBufferCount, &ret, flags, wsamsg->name, wsamsg->namelen, NULL, NULL); if (res && (err = WSAGetLastError ()) == WSAEWOULDBLOCK) { LOCK_EVENTS; wsock_events->events &= ~FD_WRITE; UNLOCK_EVENTS; } } while (res && err == WSAEWOULDBLOCK && !(res = wait_for_events (FD_WRITE | FD_CLOSE, wait_flags))); if (!res) { sum += ret; /* For streams, return to application if the number of bytes written is less than the number of bytes we intended to write in a single call to WSASendTo. Otherwise we would have to add code to backtrack in the input buffers, which is questionable. There was probably a good reason we couldn't write more. */ if (get_socket_type () != SOCK_STREAM || ret < out_len) break; } else if (is_nonblocking () || err != WSAEWOULDBLOCK) break; } if (sum) res = sum; else if (res == SOCKET_ERROR) { set_winsock_errno (); /* Special handling for EPIPE and SIGPIPE. EPIPE is generated if the local end has been shut down on a connection oriented socket. In this case the process will also receive a SIGPIPE unless MSG_NOSIGNAL is set. */ if ((get_errno () == ECONNABORTED || get_errno () == ESHUTDOWN) && get_socket_type () == SOCK_STREAM) { set_errno (EPIPE); if (!nosignal) raise (SIGPIPE); } } return res; } ssize_t fhandler_socket::write (const void *in_ptr, size_t len) { char *ptr = (char *) in_ptr; #ifdef __x86_64__ /* size_t is 64 bit, but the len member in WSABUF is 32 bit. Split buffer if necessary. */ DWORD bufcnt = len / UINT32_MAX + ((!len || (len % UINT32_MAX)) ? 1 : 0); WSABUF wsabuf[bufcnt]; WSAMSG wsamsg = { NULL, 0, wsabuf, bufcnt, { 0, NULL }, 0 }; /* Don't use len as loop condition, it could be 0. */ for (WSABUF *wsaptr = wsabuf; bufcnt--; ++wsaptr) { wsaptr->len = MIN (len, UINT32_MAX); wsaptr->buf = ptr; len -= wsaptr->len; ptr += wsaptr->len; } #else WSABUF wsabuf = { len, ptr }; WSAMSG wsamsg = { NULL, 0, &wsabuf, 1, { 0, NULL }, 0 }; #endif return send_internal (&wsamsg, 0); } ssize_t fhandler_socket::writev (const struct iovec *const iov, const int iovcnt, ssize_t tot) { WSABUF wsabuf[iovcnt]; WSABUF *wsaptr = wsabuf; const struct iovec *iovptr = iov; for (int i = 0; i < iovcnt; ++i) { wsaptr->len = iovptr->iov_len; (wsaptr++)->buf = (char *) (iovptr++)->iov_base; } WSAMSG wsamsg = { NULL, 0, wsabuf, (DWORD) iovcnt, { 0, NULL}, 0 }; return send_internal (&wsamsg, 0); } ssize_t fhandler_socket::sendto (const void *in_ptr, size_t len, int flags, const struct sockaddr *to, int tolen) { char *ptr = (char *) in_ptr; struct sockaddr_storage sst; if (to && get_inet_addr (to, tolen, &sst, &tolen) == SOCKET_ERROR) return SOCKET_ERROR; #ifdef __x86_64__ /* size_t is 64 bit, but the len member in WSABUF is 32 bit. Split buffer if necessary. */ DWORD bufcnt = len / UINT32_MAX + ((!len || (len % UINT32_MAX)) ? 1 : 0); WSABUF wsabuf[bufcnt]; WSAMSG wsamsg = { to ? (struct sockaddr *) &sst : NULL, tolen, wsabuf, bufcnt, { 0, NULL }, 0 }; /* Don't use len as loop condition, it could be 0. */ for (WSABUF *wsaptr = wsabuf; bufcnt--; ++wsaptr) { wsaptr->len = MIN (len, UINT32_MAX); wsaptr->buf = ptr; len -= wsaptr->len; ptr += wsaptr->len; } #else WSABUF wsabuf = { len, ptr }; WSAMSG wsamsg = { to ? (struct sockaddr *) &sst : NULL, tolen, &wsabuf, 1, { 0, NULL}, 0 }; #endif return send_internal (&wsamsg, flags); } ssize_t fhandler_socket::sendmsg (const struct msghdr *msg, int flags) { /* TODO: Descriptor passing on AF_LOCAL sockets. */ struct sockaddr_storage sst; int len = 0; if (msg->msg_name && get_inet_addr ((struct sockaddr *) msg->msg_name, msg->msg_namelen, &sst, &len) == SOCKET_ERROR) return SOCKET_ERROR; WSABUF wsabuf[msg->msg_iovlen]; WSABUF *wsaptr = wsabuf; const struct iovec *iovptr = msg->msg_iov; for (int i = 0; i < msg->msg_iovlen; ++i) { wsaptr->len = iovptr->iov_len; (wsaptr++)->buf = (char *) (iovptr++)->iov_base; } /* Disappointing but true: Even if WSASendMsg is supported, it's only supported for datagram and raw sockets. */ DWORD controllen = (DWORD) (!wincap.has_sendmsg () || get_socket_type () == SOCK_STREAM || get_addr_family () == AF_LOCAL ? 0 : msg->msg_controllen); WSAMSG wsamsg = { msg->msg_name ? (struct sockaddr *) &sst : NULL, len, wsabuf, (DWORD) msg->msg_iovlen, { controllen, (char *) msg->msg_control }, 0 }; return send_internal (&wsamsg, flags); } int fhandler_socket::shutdown (int how) { int res = ::shutdown (get_socket (), how); /* Linux allows to call shutdown for any socket, even if it's not connected. This also disables to call accept on this socket, if shutdown has been called with the SHUT_RD or SHUT_RDWR parameter. In contrast, WinSock only allows to call shutdown on a connected socket. The accept function is in no way affected. So, what we do here is to fake success, and to change the event settings so that an FD_CLOSE event is triggered for the calling Cygwin function. The evaluate_events method handles the call from accept specially to generate a Linux-compatible behaviour. */ if (res && WSAGetLastError () != WSAENOTCONN) set_winsock_errno (); else { res = 0; switch (how) { case SHUT_RD: saw_shutdown_read (true); wsock_events->events |= FD_CLOSE; SetEvent (wsock_evt); break; case SHUT_WR: saw_shutdown_write (true); break; case SHUT_RDWR: saw_shutdown_read (true); saw_shutdown_write (true); wsock_events->events |= FD_CLOSE; SetEvent (wsock_evt); break; } } return res; } int fhandler_socket::close () { int res = 0; release_events (); while ((res = closesocket (get_socket ())) != 0) { if (WSAGetLastError () != WSAEWOULDBLOCK) { set_winsock_errno (); res = -1; break; } if (cygwait (10) == WAIT_SIGNALED) { set_errno (EINTR); res = -1; break; } WSASetLastError (0); } debug_printf ("%d = fhandler_socket::close()", res); return res; } /* Definitions of old ifreq stuff used prior to Cygwin 1.7.0. */ #define OLD_SIOCGIFFLAGS _IOW('s', 101, struct __old_ifreq) #define OLD_SIOCGIFADDR _IOW('s', 102, struct __old_ifreq) #define OLD_SIOCGIFBRDADDR _IOW('s', 103, struct __old_ifreq) #define OLD_SIOCGIFNETMASK _IOW('s', 104, struct __old_ifreq) #define OLD_SIOCGIFHWADDR _IOW('s', 105, struct __old_ifreq) #define OLD_SIOCGIFMETRIC _IOW('s', 106, struct __old_ifreq) #define OLD_SIOCGIFMTU _IOW('s', 107, struct __old_ifreq) #define OLD_SIOCGIFINDEX _IOW('s', 108, struct __old_ifreq) #define CONV_OLD_TO_NEW_SIO(old) (((old)&0xff00ffff)|(((long)sizeof(struct ifreq)&IOCPARM_MASK)<<16)) struct __old_ifreq { #define __OLD_IFNAMSIZ 16 union { char ifrn_name[__OLD_IFNAMSIZ]; /* if name, e.g. "en0" */ } ifr_ifrn; union { struct sockaddr ifru_addr; struct sockaddr ifru_broadaddr; struct sockaddr ifru_netmask; struct sockaddr ifru_hwaddr; short ifru_flags; int ifru_metric; int ifru_mtu; int ifru_ifindex; } ifr_ifru; }; int fhandler_socket::ioctl (unsigned int cmd, void *p) { extern int get_ifconf (struct ifconf *ifc, int what); /* net.cc */ int res; struct ifconf ifc, *ifcp; struct ifreq *ifrp; switch (cmd) { case SIOCGIFCONF: ifcp = (struct ifconf *) p; if (!ifcp) { set_errno (EINVAL); return -1; } if (CYGWIN_VERSION_CHECK_FOR_OLD_IFREQ) { ifc.ifc_len = ifcp->ifc_len / sizeof (struct __old_ifreq) * sizeof (struct ifreq); ifc.ifc_buf = (caddr_t) alloca (ifc.ifc_len); } else { ifc.ifc_len = ifcp->ifc_len; ifc.ifc_buf = ifcp->ifc_buf; } res = get_ifconf (&ifc, cmd); if (res) debug_printf ("error in get_ifconf"); if (CYGWIN_VERSION_CHECK_FOR_OLD_IFREQ) { struct __old_ifreq *ifr = (struct __old_ifreq *) ifcp->ifc_buf; for (ifrp = ifc.ifc_req; (caddr_t) ifrp < ifc.ifc_buf + ifc.ifc_len; ++ifrp, ++ifr) { memcpy (&ifr->ifr_ifrn, &ifrp->ifr_ifrn, sizeof ifr->ifr_ifrn); ifr->ifr_name[__OLD_IFNAMSIZ - 1] = '\0'; memcpy (&ifr->ifr_ifru, &ifrp->ifr_ifru, sizeof ifr->ifr_ifru); } ifcp->ifc_len = ifc.ifc_len / sizeof (struct ifreq) * sizeof (struct __old_ifreq); } else ifcp->ifc_len = ifc.ifc_len; break; case OLD_SIOCGIFFLAGS: case OLD_SIOCGIFADDR: case OLD_SIOCGIFBRDADDR: case OLD_SIOCGIFNETMASK: case OLD_SIOCGIFHWADDR: case OLD_SIOCGIFMETRIC: case OLD_SIOCGIFMTU: case OLD_SIOCGIFINDEX: cmd = CONV_OLD_TO_NEW_SIO (cmd); /*FALLTHRU*/ case SIOCGIFFLAGS: case SIOCGIFBRDADDR: case SIOCGIFNETMASK: case SIOCGIFADDR: case SIOCGIFHWADDR: case SIOCGIFMETRIC: case SIOCGIFMTU: case SIOCGIFINDEX: case SIOCGIFFRNDLYNAM: case SIOCGIFDSTADDR: { if (!p) { debug_printf ("ifr == NULL"); set_errno (EINVAL); return -1; } if (cmd > SIOCGIFINDEX && CYGWIN_VERSION_CHECK_FOR_OLD_IFREQ) { debug_printf ("cmd not supported on this platform"); set_errno (EINVAL); return -1; } ifc.ifc_len = 64 * sizeof (struct ifreq); ifc.ifc_buf = (caddr_t) alloca (ifc.ifc_len); if (cmd == SIOCGIFFRNDLYNAM) { struct ifreq_frndlyname *iff = (struct ifreq_frndlyname *) alloca (64 * sizeof (struct ifreq_frndlyname)); for (int i = 0; i < 64; ++i) ifc.ifc_req[i].ifr_frndlyname = &iff[i]; } res = get_ifconf (&ifc, cmd); if (res) { debug_printf ("error in get_ifconf"); break; } if (CYGWIN_VERSION_CHECK_FOR_OLD_IFREQ) { struct __old_ifreq *ifr = (struct __old_ifreq *) p; debug_printf (" name: %s", ifr->ifr_name); for (ifrp = ifc.ifc_req; (caddr_t) ifrp < ifc.ifc_buf + ifc.ifc_len; ++ifrp) { debug_printf ("testname: %s", ifrp->ifr_name); if (! strcmp (ifrp->ifr_name, ifr->ifr_name)) { memcpy (&ifr->ifr_ifru, &ifrp->ifr_ifru, sizeof ifr->ifr_ifru); break; } } } else { struct ifreq *ifr = (struct ifreq *) p; debug_printf (" name: %s", ifr->ifr_name); for (ifrp = ifc.ifc_req; (caddr_t) ifrp < ifc.ifc_buf + ifc.ifc_len; ++ifrp) { debug_printf ("testname: %s", ifrp->ifr_name); if (! strcmp (ifrp->ifr_name, ifr->ifr_name)) { if (cmd == SIOCGIFFRNDLYNAM) /* The application has to care for the space. */ memcpy (ifr->ifr_frndlyname, ifrp->ifr_frndlyname, sizeof (struct ifreq_frndlyname)); else memcpy (&ifr->ifr_ifru, &ifrp->ifr_ifru, sizeof ifr->ifr_ifru); break; } } } if ((caddr_t) ifrp >= ifc.ifc_buf + ifc.ifc_len) { set_errno (EINVAL); return -1; } break; } /* From this point on we handle only ioctl commands which are understood by Winsock. However, we have a problem, which is, the different size of u_long in Windows and 64 bit Cygwin. This affects the definitions of FIOASYNC, etc, because they are defined in terms of sizeof(u_long). So we have to use case labels which are independent of the sizeof u_long. Since we're redefining u_long at the start of this file to matching Winsock's idea of u_long, we can use the real definitions in calls to Windows. In theory we also have to make sure to convert the different ideas of u_long between the application and Winsock, but fortunately, the parameters defined as u_long pointers are on Linux and BSD systems defined as int pointer, so the applications will use a type of the expected size. Hopefully. */ case FIOASYNC: #ifdef __x86_64__ case _IOW('f', 125, unsigned long): #endif res = WSAAsyncSelect (get_socket (), winmsg, WM_ASYNCIO, *(int *) p ? ASYNC_MASK : 0); syscall_printf ("Async I/O on socket %s", *(int *) p ? "started" : "cancelled"); async_io (*(int *) p != 0); /* If async_io is switched off, revert the event handling. */ if (*(int *) p == 0) WSAEventSelect (get_socket (), wsock_evt, EVENT_MASK); break; case FIONREAD: #ifdef __x86_64__ case _IOR('f', 127, unsigned long): #endif res = ioctlsocket (get_socket (), FIONREAD, (u_long *) p); if (res == SOCKET_ERROR) set_winsock_errno (); break; default: /* Sockets are always non-blocking internally. So we just note the state here. */ #ifdef __x86_64__ /* Convert the different idea of u_long in the definition of cmd. */ if (((cmd >> 16) & IOCPARM_MASK) == sizeof (unsigned long)) cmd = (cmd & ~(IOCPARM_MASK << 16)) | (sizeof (u_long) << 16); #endif if (cmd == FIONBIO) { syscall_printf ("socket is now %sblocking", *(int *) p ? "non" : ""); set_nonblocking (*(int *) p); res = 0; } else res = ioctlsocket (get_socket (), cmd, (u_long *) p); break; } syscall_printf ("%d = ioctl_socket(%x, %p)", res, cmd, p); return res; } int fhandler_socket::fcntl (int cmd, intptr_t arg) { int res = 0; int request, current; switch (cmd) { case F_SETOWN: { pid_t pid = (pid_t) arg; LOCK_EVENTS; wsock_events->owner = pid; UNLOCK_EVENTS; debug_printf ("owner set to %d", pid); } break; case F_GETOWN: res = wsock_events->owner; break; case F_SETFL: { /* Carefully test for the O_NONBLOCK or deprecated OLD_O_NDELAY flag. Set only the flag that has been passed in. If both are set, just record O_NONBLOCK. */ int new_flags = arg & O_NONBLOCK_MASK; if ((new_flags & OLD_O_NDELAY) && (new_flags & O_NONBLOCK)) new_flags = O_NONBLOCK; current = get_flags () & O_NONBLOCK_MASK; request = new_flags ? 1 : 0; if (!!current != !!new_flags && (res = ioctl (FIONBIO, &request))) break; set_flags ((get_flags () & ~O_NONBLOCK_MASK) | new_flags); break; } default: res = fhandler_base::fcntl (cmd, arg); break; } return res; } void fhandler_socket::set_close_on_exec (bool val) { set_no_inheritance (wsock_mtx, val); set_no_inheritance (wsock_evt, val); if (need_fixup_before ()) { close_on_exec (val); debug_printf ("set close_on_exec for %s to %d", get_name (), val); } else fhandler_base::set_close_on_exec (val); } void fhandler_socket::set_sun_path (const char *path) { sun_path = path ? cstrdup (path) : NULL; } void fhandler_socket::set_peer_sun_path (const char *path) { peer_sun_path = path ? cstrdup (path) : NULL; } int fhandler_socket::getpeereid (pid_t *pid, uid_t *euid, gid_t *egid) { if (get_addr_family () != AF_LOCAL || get_socket_type () != SOCK_STREAM) { set_errno (EINVAL); return -1; } if (no_getpeereid ()) { set_errno (ENOTSUP); return -1; } if (connect_state () != connected) { set_errno (ENOTCONN); return -1; } __try { if (pid) *pid = sec_peer_pid; if (euid) *euid = sec_peer_uid; if (egid) *egid = sec_peer_gid; return 0; } __except (EFAULT) {} __endtry return -1; }
gpl-2.0
chisimba/chisimba
app/core_modules/utilities/resources/oauth/OAuth.php
22342
<?php // vim: foldmethod=marker /* Generic exception class */ class OAuthException extends Exception {/*{{{*/ // pass }/*}}}*/ class OAuthConsumer {/*{{{*/ public $key; public $secret; function __construct($key, $secret, $callback_url=NULL) {/*{{{*/ $this->key = $key; $this->secret = $secret; $this->callback_url = $callback_url; }/*}}}*/ }/*}}}*/ class OAuthToken {/*{{{*/ // access tokens and request tokens public $key; public $secret; /** * key = the token * secret = the token secret */ function __construct($key, $secret) {/*{{{*/ $this->key = $key; $this->secret = $secret; }/*}}}*/ /** * generates the basic string serialization of a token that a server * would respond to request_token and access_token calls with */ function to_string() {/*{{{*/ return "oauth_token=" . OAuthUtil::urlencodeRFC3986($this->key) . "&oauth_token_secret=" . OAuthUtil::urlencodeRFC3986($this->secret); }/*}}}*/ function __toString() {/*{{{*/ return $this->to_string(); }/*}}}*/ }/*}}}*/ class OAuthSignatureMethod {/*{{{*/ public function check_signature(&$request, $consumer, $token, $signature) { $built = $this->build_signature($request, $consumer, $token); return $built == $signature; } }/*}}}*/ class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/ function get_name() {/*{{{*/ return "HMAC-SHA1"; }/*}}}*/ public function build_signature($request, $consumer, $token) {/*{{{*/ $base_string = $request->get_signature_base_string(); $request->base_string = $base_string; $key_parts = array( $consumer->secret, ($token) ? $token->secret : "" ); $key_parts = array_map(array('OAuthUtil','urlencodeRFC3986'), $key_parts); $key = implode('&', $key_parts); return base64_encode( hash_hmac('sha1', $base_string, $key, true)); }/*}}}*/ }/*}}}*/ class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {/*{{{*/ public function get_name() {/*{{{*/ return "PLAINTEXT"; }/*}}}*/ public function build_signature($request, $consumer, $token) {/*{{{*/ $sig = array( OAuthUtil::urlencodeRFC3986($consumer->secret) ); if ($token) { array_push($sig, OAuthUtil::urlencodeRFC3986($token->secret)); } else { array_push($sig, ''); } $raw = implode("&", $sig); // for debug purposes $request->base_string = $raw; return OAuthUtil::urlencodeRFC3986($raw); }/*}}}*/ }/*}}}*/ class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {/*{{{*/ public function get_name() {/*{{{*/ return "RSA-SHA1"; }/*}}}*/ protected function fetch_public_cert(&$request) {/*{{{*/ // not implemented yet, ideas are: // (1) do a lookup in a table of trusted certs keyed off of consumer // (2) fetch via http using a url provided by the requester // (3) some sort of specific discovery code based on request // // either way should return a string representation of the certificate throw Exception("fetch_public_cert not implemented"); }/*}}}*/ protected function fetch_private_cert(&$request) {/*{{{*/ // not implemented yet, ideas are: // (1) do a lookup in a table of trusted certs keyed off of consumer // // either way should return a string representation of the certificate throw Exception("fetch_private_cert not implemented"); }/*}}}*/ public function build_signature(&$request, $consumer, $token) {/*{{{*/ $base_string = $request->get_signature_base_string(); $request->base_string = $base_string; // Fetch the private key cert based on the request $cert = $this->fetch_private_cert($request); // Pull the private key ID from the certificate $privatekeyid = openssl_get_privatekey($cert); // Sign using the key $ok = openssl_sign($base_string, $signature, $privatekeyid); // Release the key resource openssl_free_key($privatekeyid); return base64_encode($signature); } /*}}}*/ public function check_signature(&$request, $consumer, $token, $signature) {/*{{{*/ $decoded_sig = base64_decode($signature); $base_string = $request->get_signature_base_string(); // Fetch the public key cert based on the request $cert = $this->fetch_public_cert($request); // Pull the public key ID from the certificate $publickeyid = openssl_get_publickey($cert); // Check the computed signature against the one passed in the query $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); // Release the key resource openssl_free_key($publickeyid); return $ok == 1; } /*}}}*/ }/*}}}*/ class OAuthRequest {/*{{{*/ private $parameters; private $http_method; private $http_url; // for debug purposes public $base_string; public static $version = '1.0'; function __construct($http_method, $http_url, $parameters=NULL) {/*{{{*/ @$parameters or $parameters = array(); $this->parameters = $parameters; $this->http_method = $http_method; $this->http_url = $http_url; }/*}}}*/ /** * attempt to build up a request from what was passed to the server */ public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {/*{{{*/ $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https'; @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; @$http_method or $http_method = $_SERVER['REQUEST_METHOD']; $request_headers = OAuthRequest::get_headers(); // let the library user override things however they'd like, if they know // which parameters to use then go for it, for example XMLRPC might want to // do this if ($parameters) { $req = new OAuthRequest($http_method, $http_url, $parameters); } // next check for the auth header, we need to do some extra stuff // if that is the case, namely suck in the parameters from GET or POST // so that we can include them in the signature else if (@substr($request_headers['Authorization'], 0, 5) == "OAuth") { $header_parameters = OAuthRequest::split_header($request_headers['Authorization']); if ($http_method == "GET") { $req_parameters = $_GET; } else if ($http_method == "POST") { $req_parameters = $_POST; } $parameters = array_merge($header_parameters, $req_parameters); $req = new OAuthRequest($http_method, $http_url, $parameters); } else if ($http_method == "GET") { $req = new OAuthRequest($http_method, $http_url, $_GET); } else if ($http_method == "POST") { $req = new OAuthRequest($http_method, $http_url, $_POST); } return $req; }/*}}}*/ /** * pretty much a helper function to set up the request */ public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {/*{{{*/ @$parameters or $parameters = array(); $defaults = array("oauth_version" => OAuthRequest::$version, "oauth_nonce" => OAuthRequest::generate_nonce(), "oauth_timestamp" => OAuthRequest::generate_timestamp(), "oauth_consumer_key" => $consumer->key); $parameters = array_merge($defaults, $parameters); if ($token) { $parameters['oauth_token'] = $token->key; } return new OAuthRequest($http_method, $http_url, $parameters); }/*}}}*/ public function set_parameter($name, $value) {/*{{{*/ $this->parameters[$name] = $value; }/*}}}*/ public function get_parameter($name) {/*{{{*/ return $this->parameters[$name]; }/*}}}*/ public function get_parameters() {/*{{{*/ return $this->parameters; }/*}}}*/ /** * Returns the normalized parameters of the request * * This will be all (except oauth_signature) parameters, * sorted first by key, and if duplicate keys, then by * value. * * The returned string will be all the key=value pairs * concated by &. * * @return string */ public function get_signable_parameters() {/*{{{*/ // Grab all parameters $params = $this->parameters; // Remove oauth_signature if present if (isset($params['oauth_signature'])) { unset($params['oauth_signature']); } // Urlencode both keys and values $keys = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_keys($params)); $values = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_values($params)); $params = array_combine($keys, $values); // Sort by keys (natsort) uksort($params, 'strnatcmp'); // Generate key=value pairs $pairs = array(); foreach ($params as $key=>$value ) { if (is_array($value)) { // If the value is an array, it's because there are multiple // with the same key, sort them, then add all the pairs natsort($value); foreach ($value as $v2) { $pairs[] = $key . '=' . $v2; } } else { $pairs[] = $key . '=' . $value; } } // Return the pairs, concated with & return implode('&', $pairs); }/*}}}*/ /** * Returns the base string of this request * * The base string defined as the method, the url * and the parameters (normalized), each urlencoded * and the concated with &. */ public function get_signature_base_string() {/*{{{*/ $parts = array( $this->get_normalized_http_method(), $this->get_normalized_http_url(), $this->get_signable_parameters() ); $parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $parts); return implode('&', $parts); }/*}}}*/ /** * just uppercases the http method */ public function get_normalized_http_method() {/*{{{*/ return strtoupper($this->http_method); }/*}}}*/ /** * parses the url and rebuilds it to be * scheme://host/path */ public function get_normalized_http_url() {/*{{{*/ $parts = parse_url($this->http_url); $port = @$parts['port']; $scheme = $parts['scheme']; $host = $parts['host']; $path = @$parts['path']; $port or $port = ($scheme == 'https') ? '443' : '80'; if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) { $host = "$host:$port"; } return "$scheme://$host$path"; }/*}}}*/ /** * builds a url usable for a GET request */ public function to_url() {/*{{{*/ $out = $this->get_normalized_http_url() . "?"; $out .= $this->to_postdata(); return $out; }/*}}}*/ /** * builds the data one would send in a POST request */ public function to_postdata() {/*{{{*/ $total = array(); foreach ($this->parameters as $k => $v) { $total[] = OAuthUtil::urlencodeRFC3986($k) . "=" . OAuthUtil::urlencodeRFC3986($v); } $out = implode("&", $total); return $out; }/*}}}*/ /** * builds the Authorization: header */ public function to_header($realm="") {/*{{{*/ $out ='"Authorization: OAuth realm="' . $realm . '",'; $total = array(); foreach ($this->parameters as $k => $v) { if (substr($k, 0, 5) != "oauth") continue; $out .= ',' . OAuthUtil::urlencodeRFC3986($k) . '="' . OAuthUtil::urlencodeRFC3986($v) . '"'; } return $out; }/*}}}*/ public function __toString() {/*{{{*/ return $this->to_url(); }/*}}}*/ public function sign_request($signature_method, $consumer, $token) {/*{{{*/ $this->set_parameter("oauth_signature_method", $signature_method->get_name()); $signature = $this->build_signature($signature_method, $consumer, $token); $this->set_parameter("oauth_signature", $signature); }/*}}}*/ public function build_signature($signature_method, $consumer, $token) {/*{{{*/ $signature = $signature_method->build_signature($this, $consumer, $token); return $signature; }/*}}}*/ /** * util function: current timestamp */ private static function generate_timestamp() {/*{{{*/ return time(); }/*}}}*/ /** * util function: current nonce */ private static function generate_nonce() {/*{{{*/ $mt = microtime(); $rand = mt_rand(); return md5($mt . $rand); // md5s look nicer than numbers }/*}}}*/ /** * util function for turning the Authorization: header into * parameters, has to do some unescaping */ private static function split_header($header) {/*{{{*/ // remove 'OAuth ' at the start of a header $header = substr($header, 6); // error cases: commas in parameter values? $parts = explode(",", $header); $out = array(); foreach ($parts as $param) { $param = ltrim($param); // skip the "realm" param, nobody ever uses it anyway if (substr($param, 0, 5) != "oauth") continue; $param_parts = explode("=", $param); // rawurldecode() used because urldecode() will turn a "+" in the // value into a space $out[$param_parts[0]] = rawurldecode(substr($param_parts[1], 1, -1)); } return $out; }/*}}}*/ /** * helper to try to sort out headers for people who aren't running apache */ private static function get_headers() {/*{{{*/ if (function_exists('apache_request_headers')) { // we need this to get the actual Authorization: header // because apache tends to tell us it doesn't exist return apache_request_headers(); } // otherwise we don't have apache and are just going to have to hope // that $_SERVER actually contains what we need $out = array(); foreach ($_SERVER as $key => $value) { if (substr($key, 0, 5) == "HTTP_") { // this is chaos, basically it is just there to capitalize the first // letter of every word that is not an initial HTTP and strip HTTP // code from przemek $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5))))); $out[$key] = $value; } } return $out; }/*}}}*/ }/*}}}*/ class OAuthServer {/*{{{*/ protected $timestamp_threshold = 300; // in seconds, five minutes protected $version = 1.0; // hi blaine protected $signature_methods = array(); protected $data_store; function __construct($data_store) {/*{{{*/ $this->data_store = $data_store; }/*}}}*/ public function add_signature_method($signature_method) {/*{{{*/ $this->signature_methods[$signature_method->get_name()] = $signature_method; }/*}}}*/ // high level functions /** * process a request_token request * returns the request token on success */ public function fetch_request_token(&$request) {/*{{{*/ $this->get_version($request); $consumer = $this->get_consumer($request); // no token required for the initial token request $token = NULL; $this->check_signature($request, $consumer, $token); $new_token = $this->data_store->new_request_token($consumer); return $new_token; }/*}}}*/ /** * process an access_token request * returns the access token on success */ public function fetch_access_token(&$request) {/*{{{*/ $this->get_version($request); $consumer = $this->get_consumer($request); // requires authorized request token $token = $this->get_token($request, $consumer, "request"); $this->check_signature($request, $consumer, $token); $new_token = $this->data_store->new_access_token($token, $consumer); return $new_token; }/*}}}*/ /** * verify an api call, checks all the parameters */ public function verify_request(&$request) {/*{{{*/ $this->get_version($request); $consumer = $this->get_consumer($request); $token = $this->get_token($request, $consumer, "access"); $this->check_signature($request, $consumer, $token); return array($consumer, $token); }/*}}}*/ // Internals from here /** * version 1 */ private function get_version(&$request) {/*{{{*/ $version = $request->get_parameter("oauth_version"); if (!$version) { $version = 1.0; } if ($version && $version != $this->version) { throw new OAuthException("OAuth version '$version' not supported"); } return $version; }/*}}}*/ /** * figure out the signature with some defaults */ private function get_signature_method(&$request) {/*{{{*/ $signature_method = @$request->get_parameter("oauth_signature_method"); if (!$signature_method) { $signature_method = "PLAINTEXT"; } if (!in_array($signature_method, array_keys($this->signature_methods))) { throw new OAuthException( "Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods)) ); } return $this->signature_methods[$signature_method]; }/*}}}*/ /** * try to find the consumer for the provided request's consumer key */ private function get_consumer(&$request) {/*{{{*/ $consumer_key = @$request->get_parameter("oauth_consumer_key"); if (!$consumer_key) { throw new OAuthException("Invalid consumer key"); } $consumer = $this->data_store->lookup_consumer($consumer_key); if (!$consumer) { throw new OAuthException("Invalid consumer"); } return $consumer; }/*}}}*/ /** * try to find the token for the provided request's token key */ private function get_token(&$request, $consumer, $token_type="access") {/*{{{*/ $token_field = @$request->get_parameter('oauth_token'); $token = $this->data_store->lookup_token( $consumer, $token_type, $token_field ); if (!$token) { throw new OAuthException("Invalid $token_type token: $token_field"); } return $token; }/*}}}*/ /** * all-in-one function to check the signature on a request * should guess the signature method appropriately */ private function check_signature(&$request, $consumer, $token) {/*{{{*/ // this should probably be in a different method $timestamp = @$request->get_parameter('oauth_timestamp'); $nonce = @$request->get_parameter('oauth_nonce'); $this->check_timestamp($timestamp); $this->check_nonce($consumer, $token, $nonce, $timestamp); $signature_method = $this->get_signature_method($request); $signature = $request->get_parameter('oauth_signature'); $valid_sig = $signature_method->check_signature( $request, $consumer, $token, $signature ); if (!$valid_sig) { throw new OAuthException("Invalid signature"); } }/*}}}*/ /** * check that the timestamp is new enough */ private function check_timestamp($timestamp) {/*{{{*/ // verify that timestamp is recentish $now = time(); if ($now - $timestamp > $this->timestamp_threshold) { throw new OAuthException("Expired timestamp, yours $timestamp, ours $now"); } }/*}}}*/ /** * check that the nonce is not repeated */ private function check_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/ // verify that the nonce is uniqueish $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp); if ($found) { throw new OAuthException("Nonce already used: $nonce"); } }/*}}}*/ }/*}}}*/ class OAuthDataStore {/*{{{*/ function lookup_consumer($consumer_key) {/*{{{*/ // implement me }/*}}}*/ function lookup_token($consumer, $token_type, $token) {/*{{{*/ // implement me }/*}}}*/ function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/ // implement me }/*}}}*/ function fetch_request_token($consumer) {/*{{{*/ // return a new token attached to this consumer }/*}}}*/ function fetch_access_token($token, $consumer) {/*{{{*/ // return a new access token attached to this consumer // for the user associated with this token if the request token // is authorized // should also invalidate the request token }/*}}}*/ }/*}}}*/ /* A very naive dbm-based oauth storage */ class SimpleOAuthDataStore extends OAuthDataStore {/*{{{*/ private $dbh; function __construct($path = "oauth.gdbm") {/*{{{*/ $this->dbh = dba_popen($path, 'c', 'gdbm'); }/*}}}*/ function __destruct() {/*{{{*/ dba_close($this->dbh); }/*}}}*/ function lookup_consumer($consumer_key) {/*{{{*/ $rv = dba_fetch("consumer_$consumer_key", $this->dbh); if ($rv === FALSE) { return NULL; } $obj = unserialize($rv); if (!($obj instanceof OAuthConsumer)) { return NULL; } return $obj; }/*}}}*/ function lookup_token($consumer, $token_type, $token) {/*{{{*/ $rv = dba_fetch("${token_type}_${token}", $this->dbh); if ($rv === FALSE) { return NULL; } $obj = unserialize($rv); if (!($obj instanceof OAuthToken)) { return NULL; } return $obj; }/*}}}*/ function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/ if (dba_exists("nonce_$nonce", $this->dbh)) { return TRUE; } else { dba_insert("nonce_$nonce", "1", $this->dbh); return FALSE; } }/*}}}*/ function new_token($consumer, $type="request") {/*{{{*/ $key = md5(time()); $secret = time() + time(); $token = new OAuthToken($key, md5(md5($secret))); if (!dba_insert("${type}_$key", serialize($token), $this->dbh)) { throw new OAuthException("doooom!"); } return $token; }/*}}}*/ function new_request_token($consumer) {/*{{{*/ return $this->new_token($consumer, "request"); }/*}}}*/ function new_access_token($token, $consumer) {/*{{{*/ $token = $this->new_token($consumer, 'access'); dba_delete("request_" . $token->key, $this->dbh); return $token; }/*}}}*/ }/*}}}*/ class OAuthUtil {/*{{{*/ public static function urlencodeRFC3986($string) {/*{{{*/ return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($string))); }/*}}}*/ // This decode function isn't taking into consideration the above // modifications to the encoding process. However, this method doesn't // seem to be used anywhere so leaving it as is. public static function urldecodeRFC3986($string) {/*{{{*/ return rawurldecode($string); }/*}}}*/ }/*}}}*/ ?>
gpl-2.0
ymc-elst/playground-ez48
kernel/content/copy.php
9220
<?php /** * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 2012.8 * @package kernel */ $Module = $Params['Module']; $ObjectID = $Params['ObjectID']; $http = eZHTTPTool::instance(); if ( $http->hasPostVariable( 'BrowseCancelButton' ) ) { if ( $http->hasPostVariable( 'BrowseCancelURI' ) ) { return $Module->redirectTo( $http->postVariable( 'BrowseCancelURI' ) ); } } if ( $ObjectID === null ) { // ObjectID is returned after browsing $ObjectID = $http->postVariable( 'ObjectID' ); } $object = eZContentObject::fetch( $ObjectID ); if ( $object === null ) return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' ); if ( !$object->attribute( 'can_read' ) ) return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); if ( $Module->isCurrentAction( 'Cancel' ) ) { $mainParentNodeID = $object->attribute( 'main_parent_node_id' ); return $Module->redirectToView( 'view', array( 'full', $mainParentNodeID ) ); } $contentINI = eZINI::instance( 'content.ini' ); /*! Copy the specified object to a given node */ function copyObject( $Module, $object, $allVersions, $newParentNodeID ) { if ( !$newParentNodeID ) return $Module->redirectToView( 'view', array( 'full', 2 ) ); // check if we can create node under the specified parent node if( ( $newParentNode = eZContentObjectTreeNode::fetch( $newParentNodeID ) ) === null ) return $Module->redirectToView( 'view', array( 'full', 2 ) ); $classID = $object->attribute('contentclass_id'); if ( !$newParentNode->checkAccess( 'create', $classID ) ) { $objectID = $object->attribute( 'id' ); eZDebug::writeError( "Cannot copy object $objectID to node $newParentNodeID, " . "the current user does not have create permission for class ID $classID", 'content/copy' ); return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); } $db = eZDB::instance(); $db->begin(); $newObject = $object->copy( $allVersions ); // We should reset section that will be updated in updateSectionID(). // If sectionID is 0 then the object has been newly created $newObject->setAttribute( 'section_id', 0 ); $newObject->store(); $curVersion = $newObject->attribute( 'current_version' ); $curVersionObject = $newObject->attribute( 'current' ); $newObjAssignments = $curVersionObject->attribute( 'node_assignments' ); unset( $curVersionObject ); // remove old node assignments foreach( $newObjAssignments as $assignment ) { $assignment->purge(); } // and create a new one $nodeAssignment = eZNodeAssignment::create( array( 'contentobject_id' => $newObject->attribute( 'id' ), 'contentobject_version' => $curVersion, 'parent_node' => $newParentNodeID, 'is_main' => 1 ) ); $nodeAssignment->store(); // publish the newly created object eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $newObject->attribute( 'id' ), 'version' => $curVersion ) ); // Update "is_invisible" attribute for the newly created node. $newNode = $newObject->attribute( 'main_node' ); eZContentObjectTreeNode::updateNodeVisibility( $newNode, $newParentNode ); $db->commit(); return $Module->redirectToView( 'view', array( 'full', $newParentNodeID ) ); } /*! Browse for node to place the object copy into */ function browse( $Module, $object ) { if ( $Module->hasActionParameter( 'LanguageCode' ) ) $languageCode = $Module->actionParameter( 'LanguageCode' ); else { $languageCode = false; } $objectID = $object->attribute( 'id' ); $node = $object->attribute( 'main_node' ); $class = $object->contentClass(); $ignoreNodesSelect = array(); $ignoreNodesClick = array(); foreach ( $object->assignedNodes( false ) as $element ) { $ignoreNodesSelect[] = $element['node_id']; $ignoreNodesClick[] = $element['node_id']; } $ignoreNodesSelect = array_unique( $ignoreNodesSelect ); $ignoreNodesClick = array_unique( $ignoreNodesClick ); $viewMode = 'full'; if ( $Module->hasActionParameter( 'ViewMode' ) ) $viewMode = $Module->actionParameter( 'ViewMode' ); $sourceParentNodeID = $node->attribute( 'parent_node_id' ); eZContentBrowse::browse( array( 'action_name' => 'CopyNode', 'description_template' => 'design:content/browse_copy_node.tpl', 'keys' => array( 'class' => $class->attribute( 'id' ), 'class_id' => $class->attribute( 'identifier' ), 'classgroup' => $class->attribute( 'ingroup_id_list' ), 'section' => $object->attribute( 'section_id' ) ), 'ignore_nodes_select' => $ignoreNodesSelect, 'ignore_nodes_click' => $ignoreNodesClick, 'persistent_data' => array( 'ObjectID' => $objectID ), 'permission' => array( 'access' => 'create', 'contentclass_id' => $class->attribute( 'id' ) ), 'content' => array( 'object_id' => $objectID, 'object_version' => $object->attribute( 'current_version' ), 'object_language' => $languageCode ), 'start_node' => $sourceParentNodeID, 'cancel_page' => $Module->redirectionURIForModule( $Module, 'view', array( $viewMode, $sourceParentNodeID, $languageCode ) ), 'from_page' => "/content/copy" ), $Module ); } /*! Redirect to the page that lets a user to choose which versions to copy: either all version or the current one. */ function chooseObjectVersionsToCopy( $Module, &$Result, $object ) { $selectedNodeIDArray = eZContentBrowse::result( $Module->currentAction() ); $tpl = eZTemplate::factory(); $tpl->setVariable( 'object', $object ); $tpl->setVariable( 'selected_node_id', $selectedNodeIDArray[0] ); $Result['content'] = $tpl->fetch( 'design:content/copy.tpl' ); $Result['path'] = array( array( 'url' => false, 'text' => ezpI18n::tr( 'kernel/content', 'Content' ) ), array( 'url' => false, 'text' => ezpI18n::tr( 'kernel/content', 'Copy' ) ) ); } /* Object copying logic in pseudo-code: $targetNodeID = browse(); $versionsToCopy = fetchObjectVersionsToCopyFromContentINI(); if ( $versionsToCopy != 'user-defined' ) $versionsToCopy = askUserAboutVersionsToCopy(); copyObject( $object, $versionsToCopy, $targeNodeID ); Action parameters: 1. initially: null 2. when user has selected the target node: 'CopyNode' 3. when/if user has selected versions to copy: 'Copy' or 'Cancel' */ $versionHandling = $contentINI->variable( 'CopySettings', 'VersionHandling' ); $chooseVersions = ( $versionHandling == 'user-defined' ); if( $chooseVersions ) $allVersions = ( $Module->actionParameter( 'VersionChoice' ) == 1 ) ? true : false; else $allVersions = ( $versionHandling == 'last-published' ) ? false : true; if ( $Module->isCurrentAction( 'Copy' ) ) { // actually do copying after a user has selected object versions to copy $newParentNodeID = $http->postVariable( 'SelectedNodeID' ); return copyObject( $Module, $object, $allVersions, $newParentNodeID ); } else if ( $Module->isCurrentAction( 'CopyNode' ) ) { // we get here after a user selects target node to place the source object under if( $chooseVersions ) { // redirect to the page with choice of versions to copy $Result = array(); chooseObjectVersionsToCopy( $Module, $Result, $object ); } else { // actually do copying of the pre-configured object version(s) $selectedNodeIDArray = eZContentBrowse::result( $Module->currentAction() ); $newParentNodeID = $selectedNodeIDArray[0]; return copyObject( $Module, $object, $allVersions, $newParentNodeID ); } } else // default, initial action { /* Browse for target node. We get here when a user clicks "copy" button when viewing some node. */ browse( $Module, $object ); } ?>
gpl-2.0
gemol/Ecommerce
MrCMS/DbConfiguration/SqliteProvider.cs
925
using System.ComponentModel; using FluentNHibernate.Cfg.Db; using MrCMS.Settings; namespace MrCMS.DbConfiguration { [Description("Use built-in data storage (Sqlite) (limited compatibility).")] [NoConnectionStringBuilder] public class SqliteProvider : IDatabaseProvider { private readonly DatabaseSettings _databaseSettings; public SqliteProvider(DatabaseSettings databaseSettings) { _databaseSettings = databaseSettings; } public IPersistenceConfigurer GetPersistenceConfigurer() { return SQLiteConfiguration.Standard.ConnectionString(builder => builder.Is(_databaseSettings.ConnectionString)); } public void AddProviderSpecificConfiguration(NHibernate.Cfg.Configuration config) { } public string Type { get { return GetType().FullName; } } } }
gpl-2.0
brookinsconsulting/ezpedia
ezpublish_legacy/tests/toolkit/ezpdatabasehelper.php
2762
<?php /** * File containing the ezpDatabaseHelper class * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.07.0 * @package tests */ class ezpDatabaseHelper { /** * Constructs new ezpDatabaseHelper and sets default db instance. */ function __construct() { $this->DefaultDB = eZDB::instance(); self::setInstance( $this ); } /** * Returns true if we have instance of the ezpDatabaseHelper object, else false. * * @return bool */ static function hasInstance() { return isset( $GLOBALS['ezpDatabaseHelper'] ) && $GLOBALS['ezpDatabaseHelper'] instanceof ezpDatabaseHelper; } /** * Sets the global ezpDatabaseHelper instance to \a $instance. * * @param ezpDatabaseHelper $instance */ static function setInstance( ezpDatabaseHelper $instance ) { $GLOBALS['ezpDatabaseHelper'] = $instance; } /** * Returns an instance of the ezpDatabaseHelper object. * * @return ezpDatabaseHelper Instance of ezpDatabaseHelper */ static function instance() { if ( isset( $GLOBALS['ezpDatabaseHelper'] ) ) { $impl =& $GLOBALS['ezpDatabaseHelper']; return $impl; } else { $impl = new ezpDatabaseHelper(); self::setInstance( $impl ); return $impl; } } /** * Returns a database handler which uses database $database * * @param ezpDsn $database * @return eZDB Instance of eZDB */ static function useDatabase( ezpDsn $dsn, $makeDefaultInstance = true ) { $dbParams = $dsn->parts; $dbParams['use_defaults'] = false; $db = eZDB::instance( $dsn->phptype, $dbParams, true ); if ( $makeDefaultInstance ) eZDB::setInstance( $db ); return $db; } /** * Returns a ezdb instance which should be logged in as root * * @param ezpDsn $database * @return eZDB Instance of eZDB */ static function dbAsRootInstance( ezpDsn $dsn ) { $dbParams = $dsn->parts; $dbParams['use_defaults'] = false; $db = eZDB::instance( $dsn->phptype, $dbParams, true ); return $db; } /** * Resets the database handler back to default * * @return eZDB Instance of eZDB */ public function resetDatabaseHandler() { if ( !$this->DefaultDB->isConnected() ) return false; eZDB::setInstance( $this->DefaultDB ); return $this->DefaultDB; } } ?>
gpl-2.0
levofski/timeforlesson
wp-content/themes/fruitful/inc/func/plugins-included.php
3818
<?php get_template_part('inc/func/plugin-activation'); add_action( 'tgmpa_register', 'fruitful_register_required_plugins' ); /** * Register the required plugins for Fruitful theme. */ function fruitful_register_required_plugins() { $plugins = array( array( 'name' => 'Maintenance', 'slug' => 'maintenance', 'required' => false, ), array( 'name' => 'Contact Form 7', 'slug' => 'contact-form-7', 'required' => false, ), array( 'name' => 'WordPress SEO by Yoast', 'slug' => 'wordpress-seo', 'required' => false, ), array( 'name' => 'WooCommerce - excelling eCommerce', 'slug' => 'woocommerce', 'required' => false, ), ); $config = array( 'domain' => 'fruitful', 'default_path' => '', 'parent_menu_slug' => 'themes.php', 'parent_url_slug' => 'themes.php', 'menu' => 'install-required-plugins', 'has_notices' => true, 'is_automatic' => true, 'message' => '<br />1. Select all plugins checkbox to the left of "Plugin" <br />2. Click "Bulk Actions" and then Install <br />3. Click "Apply" button', 'strings' => array( 'page_title' => __( 'Fruitful Plugin Integration', 'fruitful' ), 'menu_title' => __( 'Plugin Integration', 'fruitful' ), 'installing' => __( 'Installing Plugin: %s', 'fruitful' ), // %1$s = plugin name 'oops' => __( 'Something went wrong with the plugin API.', 'fruitful' ), 'notice_can_install_required' => __( 'Fruitful theme requires the following plugin: %1$s.', 'fruitful' ), // %1$s = plugin name(s) 'notice_can_install_recommended' => __( 'Fruitful theme recommends the following plugin: %1$s.', 'fruitful' ), // %1$s = plugin name(s) 'notice_cannot_install' => __( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'fruitful' ), // %1$s = plugin name(s) 'notice_can_activate_required' => __( 'The following required plugin is currently inactive: %1$s.', 'fruitful' ), // %1$s = plugin name(s) 'notice_can_activate_recommended' => __( 'The following recommended plugin is currently inactive: %1$s.', 'fruitful' ), // %1$s = plugin name(s) 'notice_cannot_activate' => __( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.','fruitful' ), // %1$s = plugin name(s) 'notice_ask_to_update' => __( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with Fruitful theme: %1$s.', 'fruitful' ), // %1$s = plugin name(s) 'notice_cannot_update' => __( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'fruitful' ), // %1$s = plugin name(s) 'install_link' => __( 'Begin installing plugin', 'fruitful' ), 'activate_link' => __( 'Activate installed plugin', 'fruitful' ), 'return' => __( 'Return to Required Plugins Installer', 'fruitful' ), 'plugin_activated' => __( 'Plugin activated successfully.', 'fruitful' ), 'complete' => __( 'All plugins installed and activated successfully. %s', 'fruitful' ), // %1$s = dashboard link 'nag_type' => 'updated' ) ); tgmpa( $plugins, $config ); } ?>
gpl-2.0
mzmine/mzmine2
src/main/java/net/sf/mzmine/util/interpolatinglookuppaintscale/InterpolatingLookupPaintScaleSetupDialogTableModel.java
1778
/* * Copyright 2006-2018 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with MZmine 2; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.sf.mzmine.util.interpolatinglookuppaintscale; import java.awt.Color; import java.util.TreeMap; import javax.swing.table.AbstractTableModel; public class InterpolatingLookupPaintScaleSetupDialogTableModel extends AbstractTableModel { /** * */ private static final long serialVersionUID = 1L; private static String[] columnNames = {"Value", "Color"}; private TreeMap<Double, Color> lookupTable; public InterpolatingLookupPaintScaleSetupDialogTableModel(TreeMap<Double, Color> lookupTable) { this.lookupTable = lookupTable; } public int getColumnCount() { return 2; } public int getRowCount() { return lookupTable.size(); } public String getColumnName(int column) { return columnNames[column]; } public Object getValueAt(int row, int column) { if (column == 0) return lookupTable.keySet().toArray(new Double[0])[row]; return null; } }
gpl-2.0
grooverdan/mariadb-server
extra/yassl/include/log.hpp
1270
/* Copyright (C) 2000-2007 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA. */ /* yaSSL log interface * */ #ifndef yaSSL_LOG_HPP #define yaSSL_LOG_HPP #include "socket_wrapper.hpp" #ifdef YASSL_LOG #include <stdio.h> #endif namespace yaSSL { typedef unsigned int uint; // Debug logger class Log { #ifdef YASSL_LOG FILE* log_; #endif public: explicit Log(const char* str = "yaSSL.log"); ~Log(); void Trace(const char*); void ShowTCP(socket_t, bool ended = false); void ShowData(uint, bool sent = false); }; } // naemspace #endif // yaSSL_LOG_HPP
gpl-2.0
mityada/mangos-classic
src/game/AI/ScriptDevAI/scripts/eastern_kingdoms/molten_core/boss_garr.cpp
5593
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Garr SD%Complete: 95 SDComment: 'Summon Player' missing SDCategory: Molten Core EndScriptData */ #include "AI/ScriptDevAI/PreCompiledHeader.h" #include "molten_core.h" enum { EMOTE_MASSIVE_ERUPTION = -1409025, // Garr spells SPELL_ANTIMAGICPULSE = 19492, SPELL_MAGMASHACKLES = 19496, SPELL_ENRAGE = 19516, SPELL_SUMMON_PLAYER = 20477, SPELL_ERUPTION_TRIGGER = 20482, SPELL_SEPARATION_ANXIETY = 23487, // Aura cast on himself by Garr, if adds move out of range, they will cast spell 23492 on themselves // Firesworn spells SPELL_ERUPTION = 19497, SPELL_ENRAGE_TRIGGER = 19515, SPELL_MASSIVE_ERUPTION = 20483, }; struct boss_garrAI : public ScriptedAI { boss_garrAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance* m_pInstance; uint32 m_uiAntiMagicPulseTimer; uint32 m_uiMagmaShacklesTimer; uint32 m_uiMassiveEruptionTimer; void Reset() override { m_uiAntiMagicPulseTimer = urand(10 * IN_MILLISECONDS, 15 * IN_MILLISECONDS); m_uiMagmaShacklesTimer = urand(5 * IN_MILLISECONDS, 10 * IN_MILLISECONDS); m_uiMassiveEruptionTimer = 6 * MINUTE * IN_MILLISECONDS; } void Aggro(Unit* /*pWho*/) override { if (m_pInstance) m_pInstance->SetData(TYPE_GARR, IN_PROGRESS); // Garr has a 100 yard aura to keep track of the distance of each of his adds, they will enrage if moved out of it DoCastSpellIfCan(m_creature, SPELL_SEPARATION_ANXIETY, CAST_TRIGGERED | CAST_AURA_NOT_PRESENT); } void JustDied(Unit* /*pKiller*/) override { if (m_pInstance) m_pInstance->SetData(TYPE_GARR, DONE); } void JustReachedHome() override { if (m_pInstance) m_pInstance->SetData(TYPE_GARR, FAIL); } void SpellHit(Unit* /*pCaster*/, const SpellEntry* pSpell) override { if (pSpell->Id == SPELL_ENRAGE_TRIGGER) DoCastSpellIfCan(m_creature, SPELL_ENRAGE, CAST_TRIGGERED); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; // AntiMagicPulse_Timer if (m_uiAntiMagicPulseTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_ANTIMAGICPULSE) == CAST_OK) m_uiAntiMagicPulseTimer = urand(15 * IN_MILLISECONDS, 20 * IN_MILLISECONDS); } else m_uiAntiMagicPulseTimer -= uiDiff; // MagmaShackles_Timer if (m_uiMagmaShacklesTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_MAGMASHACKLES) == CAST_OK) m_uiMagmaShacklesTimer = urand(10 * IN_MILLISECONDS, 15 * IN_MILLISECONDS); } else m_uiMagmaShacklesTimer -= uiDiff; // MassiveEruption_Timer if (m_uiMassiveEruptionTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_ERUPTION_TRIGGER) == CAST_OK) { DoScriptText(EMOTE_MASSIVE_ERUPTION, m_creature); m_uiMassiveEruptionTimer = 20 * IN_MILLISECONDS; } } else m_uiMassiveEruptionTimer -= uiDiff; DoMeleeAttackIfReady(); } }; struct mob_fireswornAI : public ScriptedAI { mob_fireswornAI(Creature* pCreature) : ScriptedAI(pCreature) {} void Reset() override {} void JustDied(Unit* pKiller) override { if (m_creature != pKiller) DoCastSpellIfCan(m_creature, SPELL_ERUPTION); DoCastSpellIfCan(m_creature, SPELL_ENRAGE_TRIGGER, CAST_TRIGGERED); } void SpellHit(Unit* /*pCaster*/, const SpellEntry* pSpell) override { if (pSpell->Id == SPELL_ERUPTION_TRIGGER) DoCastSpellIfCan(m_creature, SPELL_MASSIVE_ERUPTION); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_garr(Creature* pCreature) { return new boss_garrAI(pCreature); } CreatureAI* GetAI_mob_firesworn(Creature* pCreature) { return new mob_fireswornAI(pCreature); } void AddSC_boss_garr() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_garr"; pNewScript->GetAI = &GetAI_boss_garr; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "mob_firesworn"; pNewScript->GetAI = &GetAI_mob_firesworn; pNewScript->RegisterSelf(); }
gpl-2.0
KimHe/skeleton
tools/arageli/src/arageli/gauss.hpp
30160
/***************************************************************************** gauss.hpp This file is part of Arageli library. Copyright (C) 1999--2006 Nikolai Yu. Zolotykh Copyright (C) 2005--2007 Sergey S. Lyalin The Arageli Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. The Arageli Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. We are also open for dual licensing for the whole library or for its particular part. If you are interested to get the library in this way, i.e. not under the GNU General Public License, please contact Arageli Support Service support.arageli@gmail.com. *****************************************************************************/ #ifndef _ARAGELI_GAUSS_HPP_ #define _ARAGELI_GAUSS_HPP_ /** \file gauss.hpp \brief Gauss algorithm and related. Gauss interation (row, col), The Gauss algorithm, Gauss-Bareiss algorithm and derived. */ #include "config.hpp" #include <cmath> #include <iostream> #include <iomanip> #include <functional> #include "type_opers.hpp" #include "type_traits.hpp" #include "factory.hpp" #include "exception.hpp" #include "powerest.hpp" #include "vector.hpp" #include "matrix.hpp" #include "std_import.hpp" namespace Arageli { /// Gauss elimination of column col with row manipulation. /** Eliminates nonzeros in column col exclude the element (row, col) by row manipulation. Pivot element (row, col) becomes 1. */ template <typename M> void gauss_field_row_iter ( M& a, typename M::size_type row, typename M::size_type col ); /// Gauss elimination of row with column manipulation. /** Eliminates nonzeros in row exclude the element (row, col) by column manipulation. Pivot element (row, col) becomes 1. */ template <typename M> void gauss_field_col_iter ( M& a, typename M::size_type row, typename M::size_type col ); /// Gauss-Bareiss elimination of column col with row manipulation. /** Eliminates nonzeros in column col exclude the element (row, col) by row manipulation. */ template <typename M, typename T> void gauss_bareiss_row_iter ( M& a, typename M::size_type row, typename M::size_type col, T& det, T& det_denom ); /// Gauss-Bareiss elimination of row with column manipulation. /** Eliminates nonzeros in row exclude the element (row, col) by column manipulation. */ template <typename M, typename T> void gauss_bareiss_col_iter ( M& a, typename M::size_type row, typename M::size_type col, T& det, T& det_denom ); /// Gauss-Bareiss elimination of column col with row manipulation. /** Eliminates nonzeros in column col exclude the element (row, col) by row manipulation. */ template <typename M> void gauss_bareiss_row_iter ( M& a, typename M::size_type row, typename M::size_type col ) { typename M::element_type det, det_denom; gauss_bareiss_row_iter(a, row, col, det, det_denom); } /// Gauss-Bareiss elimination of row with column manipulation. /** Eliminates nonzeros in row exclude the element (row, col) by column manipulation. */ template <typename M> void gauss_bareiss_col_iter ( M& a, typename M::size_type row, typename M::size_type col ) { typename M::element_type det, det_denom; gauss_bareiss_col_iter(a, row, col, det, det_denom); } namespace ctrl { /// Idler controller for Arageli::rref_gauss_field function. /** The names of parameters of the members are the same as for the ones of controlled function itself. */ struct rref_gauss_field_idler { class abort : public ctrl::abort {}; /// Called in the very beginning. template <typename A> void preamble (const A&) const {} /// Called in the very end. /** The arguments have the resulted values. */ template <typename B, typename Q, typename Det, typename Basis> void conclusion (const B&, const Q&, const Det&, const Basis&) const {} /// Called before an iteration. /** This function is called before choosing a pivot item in the current column. We consider only one column on each iteration. */ template <typename B, typename Q, typename Det, typename Basis> void before_iter (const B&, const Q&, const Det&, const Basis&) const {} /// Called just after an iteration. /** This function is called after each iteration has been completed. Actually there is no difference in the arguments between after_iter call and before_iter call inside the algorithm because between the iterations the algorithm does really nothing. */ template <typename B, typename Q, typename Det, typename Basis> void after_iter (const B&, const Q&, const Det&, const Basis&) const {} /// Called just before finding the biggest element in the column j. template <typename J> void find_biggest_in_col (const J& j) const {} /// Called after finding the biggest element if there are no non-zero items. /** This function is called after the algorithm make sure that in column j there are no non-zero etries, i.e. this column is negligible. */ template <typename J> void negligible_col (const J& j) const {} /// Called after finding the biggest element if one has been found. /** The chosen item is (i, j), it becomes a pivot item. */ template <typename I, typename J> void pivot_item (const I& i, const J& j) const {} /// Called after swapping rows due to the pivot item isn't on the diagonal. /** This function is called just after swapping the rows i1 and i2 to obtain the pivot item on the diagonal. Before the call the current det value is changed appropriately. */ template <typename I1, typename I2, typename B, typename Q, typename Det> void swap_rows ( const I1& i1, const I2& i2, const B&, const Q&, const Det& ) const {} /// Called just before elimination of column j. /** Between this call and a call of after_elimination function, the algorithm changes appropriately det and eliminates the columnt j. */ template <typename J> void eliminate_col (const J& j) const {} /// Called just after elimination of the column. template <typename B, typename Q, typename Det> void after_elimination (const B&, const Q&, const Det&) const {} }; /// Idler controller for Arageli::rref_gauss_bareiss function. /** The names of parameters of the members are the same as for the ones of controlled function itself. Det_denom is a type for representing a denominator of the current fractional value of the determinant. This class is inherited from rref_gauss_field_idler because some functions are the same for both these controllers. But not all of them. There is one additional argument for some of them --- det_denom. Ideologically, these functions have the same goal as their parents and have the same names. */ struct rref_gauss_bareiss_idler : public rref_gauss_field_idler { class abort : public ctrl::abort {}; /// See rref_gauss_field_idler::before_iter. template < typename B, typename Q, typename Det, typename Basis, typename Det_denom > void before_iter ( const B&, const Q&, const Det&, const Basis&, const Det_denom& ) const {} /// See rref_gauss_field_idler::after_iter. template < typename B, typename Q, typename Det, typename Basis, typename Det_denom > void after_iter ( const B&, const Q&, const Det&, const Basis&, const Det_denom& ) const {} /// See rref_gauss_field_idler::swap_rows. template < typename I1, typename I2, typename B, typename Q, typename Det, typename Det_denom > void swap_rows ( const I1&, const I2&, const B&, const Q&, const Det&, const Det_denom& ) const {} /// See rref_gauss_field_idler::after_elimination. template <typename B, typename Q, typename Det, typename Det_denom> void after_elimination ( const B&, const Q&, const Det&, const Det_denom& ) const {} }; /// Idler controller for Arageli::rref_field function. /** As the rref_field function just calls another controlled function, this controller has only the method to obtain appropriate controller for that. */ struct rref_field_idler { class abort : public ctrl::abort {}; /// Retruns a controller object for the rref_gauss_field function. rref_gauss_field_idler ctrl_rref_gauss_field () const { return rref_gauss_field_idler(); } }; /// Idler controller for Arageli::rref_int function. /** As the rref_int function just calls another controlled function, this controller has only the method to obtain appropriate controller for that. */ struct rref_int_idler { class abort : public ctrl::abort {}; /// Retruns a controller object for the rref_gauss_bareiss function. rref_gauss_bareiss_idler ctrl_rref_gauss_bareiss () const { return rref_gauss_bareiss_idler(); } }; /// Idler controller for Arageli::rref function. /** As the rref function just calls other controlled functions, this controller have only the methods to obtain appropriate controllers for that. */ struct rref_idler { class abort : public ctrl::abort {}; /// Retruns a controller object for the rref_field function. rref_field_idler ctrl_rref_field () const { return rref_field_idler(); } /// Retruns a controller object for the rref_int function. rref_int_idler ctrl_rref_int () const { return rref_int_idler(); } }; } // namespace ctrl /// Produces the reduced row echelon form `b' of the matrix `a' over a field. /** Elementary row operations are performed on `a', a matrix over a field, to reduce it to the reduced row echelon (Gauss-Jordan) form. Returns b, q, basis, det: - q is such that b = q * a; - r = basis.size() is the rank of A; - B.sumbatrix(0..(r-1), basis) is the r-by-r identity matrix; (?) - det is the value of the max size left upper corner minor of A; in general, it isn't a determinant of the matrix. @param ctrler the controller; must has an interface of ctrl::rref_gauss_field_idler class. */ template < typename A, typename B, typename Q, typename Basis, typename T, typename T_factory, typename Ctrler > void rref_gauss_field ( const A& a, B& b, Q& q, Basis& basis, T& det, const T_factory& tfctr, Ctrler ctrler ); /// Produces the reduced row echelon form B of a matrix A. template < typename A, typename B, typename Q, typename Basis, typename T, typename Ctrler // control visitor > inline void rref_gauss_field ( const A& a, B& b, Q& q, Basis& basis, T& det, Ctrler ctrler ) { rref_gauss_field(a, b, q, basis, det, factory<T>(), ctrler); } /// Produces the reduced row echelon form B of a matrix A. template <typename A, typename B, typename Q, typename Basis, typename T> inline void rref_gauss_field (const A& a, B& b, Q& q, Basis& basis, T& det) { rref_gauss_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_field_idler() ); } /// Produces the reduced row echelon form B of a matrix A. template <typename A, typename B, typename Q, typename Basis> inline void rref_gauss_field (const A& a, B& b, Q& q, Basis& basis) { typedef typename B::element_type T; T det; rref_gauss_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_field_idler() ); } /// Produces the reduced row echelon form B of a matrix A. template <typename A, typename B, typename Q> inline void rref_gauss_field (const A& a, B& b, Q& q) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; rref_gauss_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_field_idler() ); } /// Produces the reduced row echelon form B of a matrix A. template <typename A, typename B> inline void rref_gauss_field (const A& a, B& b) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; B q; rref_gauss_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_field_idler() ); } /// Produces the reduced row echelon form B of a matrix A. template <typename A> inline A rref_gauss_field (const A& a) { typedef typename A::element_type T; T det; vector<typename A::size_type, false> basis; A b, q; rref_gauss_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_field_idler() ); return b; } // ---------------------------------------- /// Produces the reduced row echelon form `b' of the matrix `a' over a field. /** It's the same that rref_gauss_field funtion. @param ctrler the controller; must has an interface of ctrl::rref_field_idler class. */ template < typename A, typename B, typename Q, typename Basis, typename T, typename T_factory, typename Ctrler // control visitor > inline void rref_field ( const A& a, B& b, Q& q, Basis& basis, T& det, const T_factory& tfctr, Ctrler ctrler ) { rref_gauss_field ( a, b, q, basis, det, tfctr, ctrler.ctrl_rref_gauss_field() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over a field. template < typename A, typename B, typename Q, typename Basis, typename T, typename Ctrler // control visitor > inline void rref_field ( const A& a, B& b, Q& q, Basis& basis, T& det, Ctrler ctrler ) { rref_field ( a, b, q, basis, det, factory<T>(), ctrler ); } /// Produces the reduced row echelon form `b' of the matrix `a' over a field. template <typename A, typename B, typename Q, typename Basis, typename T> inline void rref_field (const A& a, B& b, Q& q, Basis& basis, T& det) { rref_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_field_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over a field. template <typename A, typename B, typename Q, typename Basis> inline void rref_field (const A& a, B& b, Q& q, Basis& basis) { typedef typename B::element_type T; T det; rref_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_field_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over a field. template <typename A, typename B, typename Q> inline void rref_field (const A& a, B& b, Q& q) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; rref_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_field_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over a field. template <typename A, typename B> inline void rref_field (const A& a, B& b) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; B q; rref_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_field_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over a field. template <typename A> inline A rref_field (const A& a) { typedef typename A::element_type T; T det; vector<typename A::size_type> basis; A b, q; rref_field ( a, b, q, basis, det, factory<T>(), ctrl::rref_field_idler() ); return b; } // ---------------------------------------- /// Copies columns from a1 to a2 in order indexes in idx then tails the rest. template <typename A1, typename A2, typename I> void mat_col_copy_order (const A1& a1, A2& a2, const I& idx); /// Copies elements from a1 to a2 in order indexes in idx then tails the rest. template <typename A1, typename A2, typename I> void vec_copy_order (const A1& a1, A2& a2, const I& idx); /// Inverses permutation vector. template <typename A, typename B> void vec_inverse_permutation (const A& a, B& b); /// Produces the reduced row echelon from B of the matrix A with a specific column order. /** Makes RREF(A) with permutated columns according to basis_in. basis_in contains indexes of columns, basis_out indicates additional permutaitaon of columns. */ // TODO Make this function with an algorithm controller. template < typename A, typename B, typename Q, typename Basis_in, typename Basis_out, typename Det > void rref_order ( const A& a, B& b, Q& q, const Basis_in& basis_in, Basis_out& basis_out, Det& det ); /// Matrix inversion. /** Returns inversion of matrix A Requirement: A must be square. */ template <typename T, bool REFCNT> matrix<T, REFCNT> inverse (const matrix<T, REFCNT>& A); /// Returns determinant of A. /** Returns determinant of A. Precondition: A must be square */ template <typename T, bool REFCNT> T det (const matrix<T, REFCNT>& A); /// Returns a rank of a matrix. template <typename T, bool REFCNT> typename matrix<T, REFCNT>::size_type rank (const matrix<T, REFCNT>& A); /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. /** Produces the reduced row echelon form B of the integer matrix a by Gauss-Bareiss algorithm. Returns b, q, basis, det: - q is such that b = q * a; - r = basis.size() is the rank of A; - B.sumbatrix(mesh_grid(1,r), basis) is the r-by-r non-singular diagonal matrix; (?) - det is a determinant of a. (?) @param ctrler the controller; must has an interface of ctrl::rref_gauss_bareiss_idler class. */ template < typename A, typename B, typename Q, typename Basis, typename T, typename T_factory, typename Ctrler > void rref_gauss_bareiss ( const A& a, B& b, Q& q, Basis& basis, T& det, const T_factory& tfctr, Ctrler ctrler ); /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template < typename A, typename B, typename Q, typename Basis, typename T, typename Ctrler > inline void rref_gauss_bareiss ( const A& a, B& b, Q& q, Basis& basis, T& det, Ctrler ctrler ) { rref_gauss_bareiss(a, b, q, basis, det, factory<T>(), ctrler); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A, typename B, typename Q, typename Basis, typename T> inline void rref_gauss_bareiss (const A& a, B& b, Q& q, Basis& basis, T& det) { rref_gauss_bareiss ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_bareiss_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A, typename B, typename Q, typename Basis> inline void rref_gauss_bareiss (const A& a, B& b, Q& q, Basis& basis) { typedef typename B::element_type T; T det; rref_gauss_bareiss ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_bareiss_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A, typename B, typename Q> inline void rref_gauss_bareiss (const A& a, B& b, Q& q) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; rref_gauss_bareiss ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_bareiss_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A, typename B> inline void rref_gauss_bareiss (const A& a, B& b) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; B q; rref_gauss_bareiss ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_bareiss_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A> inline A rref_gauss_bareiss (const A& a) { typedef typename A::element_type T; T det; vector<typename A::size_type, false> basis; A b, q; rref_gauss_bareiss ( a, b, q, basis, det, factory<T>(), ctrl::rref_gauss_bareiss_idler() ); return b; } // ---------------------------------------- /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. /** It's the same that rref_gauss_bareiss function. @param ctrler the controller; must has an interface of ctrl::rref_int_idler class. */ template < typename A, typename B, typename Q, typename Basis, typename T, typename T_factory, typename Ctrler // control visitor > inline void rref_int ( const A& a, B& b, Q& q, Basis& basis, T& det, const T_factory& tfctr, Ctrler ctrler ) { rref_gauss_bareiss ( a, b, q, basis, det, tfctr, ctrler.ctrl_rref_gauss_bareiss() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template < typename A, typename B, typename Q, typename Basis, typename T, typename Ctrler // control visitor > inline void rref_int ( const A& a, B& b, Q& q, Basis& basis, T& det, Ctrler ctrler ) { rref_int(a, b, q, basis, det, factory<T>(), ctrler); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A, typename B, typename Q, typename Basis, typename T> inline void rref_int (const A& a, B& b, Q& q, Basis& basis, T& det) { rref_int ( a, b, q, basis, det, factory<T>(), ctrl::rref_int_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A, typename B, typename Q, typename Basis> inline void rref_int (const A& a, B& b, Q& q, Basis& basis) { typedef typename B::element_type T; T det; rref_int ( a, b, q, basis, det, factory<T>(), ctrl::rref_int_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A, typename B, typename Q> inline void rref_int (const A& a, B& b, Q& q) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; rref_int ( a, b, q, basis, det, factory<T>(), ctrl::rref_int_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A, typename B> inline void rref_int (const A& a, B& b) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; B q; rref_int ( a, b, q, basis, det, factory<T>(), ctrl::rref_int_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a' over an integer domain. template <typename A> inline A rref_int (const A& a) { typedef typename A::element_type T; T det; vector<typename A::size_type, false> basis; A b, q; rref_int ( a, b, q, basis, det, factory<T>(), ctrl::rref_int_idler() ); return b; } // ---------------------------------------- namespace _Internal { template < typename A, typename B, typename Q, typename Basis, typename T, typename T_factory, typename Ctrler // control visitor > inline void rref_helper_1 ( const A& a, B& b, Q& q, Basis& basis, T& det, const T_factory& tfctr, Ctrler ctrler, const true_type& ) { rref_field ( a, b, q, basis, det, tfctr, ctrler.ctrl_rref_field() ); } template < typename A, typename B, typename Q, typename Basis, typename T, typename T_factory, typename Ctrler > inline void rref_helper_1 ( const A& a, B& b, Q& q, Basis& basis, T& det, const T_factory& tfctr, Ctrler ctrler, const false_type& ) { rref_int ( a, b, q, basis, det, tfctr, ctrler.ctrl_rref_int() ); } } /// Produces the reduced row echelon form `b' of the matrix `a'. /** Exact meaning of RREF depends on type of result (integer domain or field); see rref_field and rref_int respectively. @param ctrler the controller; must has an interface of ctrl::rref_idler class. */ template < typename A, typename B, typename Q, typename Basis, typename T, typename T_factory, typename Ctrler // control visitor > inline void rref ( const A& a, B& b, Q& q, Basis& basis, T& det, const T_factory& tfctr, Ctrler ctrler ) { _Internal::rref_helper_1 ( a, b, q, basis, det, tfctr, ctrler, bool_type<type_traits<typename B::element_type>::is_field>::value ); } /// Produces the reduced row echelon form `b' of the matrix `a'. template < typename A, typename B, typename Q, typename Basis, typename T, typename Ctrler // control visitor > inline void rref ( const A& a, B& b, Q& q, Basis& basis, T& det, Ctrler ctrler ) { rref(a, b, q, basis, det, factory<T>(), ctrler); } /// Produces the reduced row echelon form `b' of the matrix `a'. template <typename A, typename B, typename Q, typename Basis, typename T> inline void rref (const A& a, B& b, Q& q, Basis& basis, T& det) { rref ( a, b, q, basis, det, factory<T>(), ctrl::rref_idler() ); } /// Produces the reduced row echelon form `b' of the matrix `a'. template <typename A, typename B, typename Q, typename Basis> void rref (const A& a, B& b, Q& q, Basis& basis) { typedef typename B::element_type T; T det; rref(a, b, q, basis, det, factory<T>(), ctrl::rref_idler()); } /// Produces the reduced row echelon form `b' of the matrix `a'. template <typename A, typename B, typename Q> inline void rref (const A& a, B& b, Q& q) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; rref(a, b, q, basis, det, factory<T>(), ctrl::rref_idler()); } /// Produces the reduced row echelon form `b' of the matrix `a'. template <typename A, typename B> inline void rref (const A& a, B& b) { typedef typename B::element_type T; T det; vector<typename B::size_type, false> basis; B q; rref(a, b, q, basis, det, factory<T>(), ctrl::rref_idler()); } /// Produces the reduced row echelon form `b' of the matrix `a'. template <typename A> inline A rref (const A& a) { typedef typename A::element_type T; T det; vector<typename A::size_type, false> basis; A b, q; rref(a, b, q, basis, det, factory<T>(), ctrl::rref_idler()); return b; } /// Returns determinant of integer matrix A. template <typename T, bool REFCNT> T det_int (const matrix<T, REFCNT>& A); /// Returns a rank of integer matrix. template <typename T, bool REFCNT> typename matrix<T, REFCNT>::size_type rank_int (const matrix<T, REFCNT>& A); /* // The following solve_linsys function have migrated to solve_linsys.{hpp, cpp} files. /// Solves a linear system. template < typename T_A, bool REFCNT_A, typename T_B, bool REFCNT_B, typename T_res, bool REFCNT_res > inline void solve_linsys ( const matrix<T_A, REFCNT_A>& A, const vector<T_B, REFCNT_B>& B, vector<T_res, REFCNT_res>& res ) { // WARNING! Slow implementation. res = inverse(A)*B; } /// Solves a linear system. template < typename T_A, bool REFCNT_A, typename T_B, bool REFCNT_B > inline vector<T_B, REFCNT_B> solve_linsys ( const matrix<T_A, REFCNT_A>& A, const vector<T_B, REFCNT_B>& B ) { vector<T_B, REFCNT_B> res(B.size()); solve_linsys(A, B, res); return res; } */ } #ifdef ARAGELI_INCLUDE_CPP_WITH_EXPORT_TEMPLATE #define ARAGELI_INCLUDE_CPP_WITH_EXPORT_TEMPLATE_GAUSS #include "gauss.cpp" #undef ARAGELI_INCLUDE_CPP_WITH_EXPORT_TEMPLATE_GAUSS #endif #endif
gpl-2.0
hexbinary/landing
src/test/java/org/oscarehr/common/dao/LabPatientPhysicianInfoDaoTest.java
2341
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.common.dao; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import org.oscarehr.common.dao.utils.EntityDataGenerator; import org.oscarehr.common.dao.utils.SchemaUtils; import org.oscarehr.common.model.LabPatientPhysicianInfo; import org.oscarehr.util.SpringUtils; public class LabPatientPhysicianInfoDaoTest extends DaoTestFixtures { protected LabPatientPhysicianInfoDao dao = SpringUtils.getBean(LabPatientPhysicianInfoDao.class); public LabPatientPhysicianInfoDaoTest() { } @Before public void before() throws Exception { SchemaUtils.restoreTable("labPatientPhysicianInfo", "patientLabRouting", "labPatientPhysicianInfo", "providerLabRouting","labReportInformation"); } @Test public void testCreate() throws Exception { LabPatientPhysicianInfo entity = new LabPatientPhysicianInfo(); EntityDataGenerator.generateTestDataForModelClass(entity); dao.persist(entity); assertNotNull(entity.getId()); } @Test public void testFindRoutings() { assertNotNull(dao.findRoutings(100, "T")); } @Test public void testFindByPatientName() { assertNotNull(dao.findByPatientName("ST", "LAB", "100", "LNAME", "FNAME", "HIN")); } @Test public void testFindByDemographic() { assertNotNull(dao.findByDemographic(199, "D")); } }
gpl-2.0
Trim/qtmoko
src/libraries/qtopiaphonemodem/qmodemphonebook.cpp
28448
/******************************************************+********************** ** ** This file is part of the Qt Extended Opensource Package. ** ** Copyright (C) 2009 Trolltech ASA. ** ** Contact: Qt Extended Information (info@qtextended.org) ** ** This file may be used under the terms of the GNU General Public License ** version 2.0 as published by the Free Software Foundation and appearing ** in the file LICENSE.GPL included in the packaging of this file. ** ** Please review the following information to ensure GNU General Public ** Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html. ** ** ****************************************************************************/ #include <qmodemphonebook.h> #include <qmodemservice.h> #include <qatutils.h> #include <qatresultparser.h> #include <QTimer> #include <QTextCodec> /*! \class QModemPhoneBook \inpublicgroup QtCellModule \brief The QModemPhoneBook class implements SIM phone book operations for AT-based modems. This class uses the commands \c{AT+CPBS}, \c{AT+CPBR}, \c{AT+CPBW}, \c{AT+CSCS}, and \c{AT+CLCK} from 3GPP TS 27.007. QModemPhoneBook implements the QPhoneBook telephony interface. Client applications should use QPhoneBook instead of this class to access the modem's SIM phone books. \sa QPhoneBook \ingroup telephony::modem */ // Fetch 10 entries at a time every half a second when in slow update mode. #define SLOW_UPDATE_TIMEOUT 500 class QModemPhoneBookPrivate { public: QModemPhoneBookPrivate() { caches = 0; charsetRetry = 5; storageRetry = 5; } ~QModemPhoneBookPrivate(); QModemService *service; QModemPhoneBookCache *caches; QString prevStorageName; QString pendingCommand; QString pendingStore; QTimer *slowTimer; QTextCodec *stringCodec; int charsetRetry; int storageRetry; }; class QModemPhoneBookOperation { public: enum Operation { Add, Remove, Update }; QModemPhoneBookOperation( Operation oper, const QPhoneBookEntry& entry, QModemPhoneBookOperation *next ) { this->oper = oper; this->entry = entry; this->next = next; } ~QModemPhoneBookOperation(); public: Operation oper; QPhoneBookEntry entry; QModemPhoneBookOperation *next; }; QModemPhoneBookOperation::~QModemPhoneBookOperation() { if ( next ) delete next; } class QModemPhoneBookCache { public: QModemPhoneBookCache( const QString& store ); ~QModemPhoneBookCache(); public: QString store; QModemPhoneBookCache *next; QList<QPhoneBookEntry> entries; uint first, last, current; bool fullyLoaded; bool needEmit; bool needLimitEmit; bool fast; bool redoQuery; bool selectOk; QModemPhoneBookOperation *opers; QString passwd; QPhoneBookLimits limits; }; QModemPhoneBookCache::QModemPhoneBookCache( const QString& store ) { this->store = store; next = 0; first = 0; last = 0; current = 0; fullyLoaded = false; needEmit = false; needLimitEmit = false; fast = false; redoQuery = false; selectOk = true; opers = 0; passwd = QString(); } QModemPhoneBookCache::~QModemPhoneBookCache() { if ( next ) { delete next; } if ( opers ) { delete opers; } } QModemPhoneBookPrivate::~QModemPhoneBookPrivate() { if ( caches ) delete caches; } /*! Construct an AT-based SIM phone book handler for \a service. */ QModemPhoneBook::QModemPhoneBook( QModemService *service ) : QPhoneBook( service->service(), service, QCommInterface::Server ) { d = new QModemPhoneBookPrivate(); d->service = service; d->slowTimer = new QTimer( this ); d->slowTimer->setSingleShot( true ); QObject::connect( d->slowTimer, SIGNAL(timeout()), this, SLOT(slowTimeout()) ); } /*! Destroy this AT-based SIM phone book handler. */ QModemPhoneBook::~QModemPhoneBook() { delete d; } /*! Returns the codec being used by the phone book subsystem to decode strings from the modem. This may be useful in other interfaces that need to decode strings. The value is based on the response to the \c{AT+CSCS?} command. \sa updateCodec() */ QTextCodec *QModemPhoneBook::stringCodec() const { return d->stringCodec; } /*! \reimp */ void QModemPhoneBook::getEntries( const QString& store ) { QModemPhoneBookCache *cache; // Find the cache entry associated with this store. cache = findCache( store ); // If the cache is fully loaded, then emit the result now. // If there is a password, then force a re-get of the phone book // because the new password may not be the same as the original. if ( cache->fullyLoaded && cache->passwd.isEmpty() ) { emit entries( store, cache->entries ); return; } // We need to requery the extents if the phone book was previously loaded. if ( cache->fullyLoaded ) { cache->fullyLoaded = false; cache->entries.clear(); cache->limits = QPhoneBookLimits(); sendQuery( cache ); } // We'll need a signal to be emitted once it is fully loaded. cache->needEmit = true; } // Strip non-numeric digits and then convert commas into the // extension "digit" used by the modem. static QString fixPhoneBookNumber( const QString& number ) { QString temp = QAtUtils::stripNumber( number ); return temp.replace( QChar( ',' ), QChar( 'p' ) ); } /*! \reimp */ void QModemPhoneBook::add ( const QPhoneBookEntry& entry, const QString& store, bool flush ) { QModemPhoneBookCache *cache = findCache( store ); QPhoneBookEntry newEntry( entry ); newEntry.setNumber( fixPhoneBookNumber( entry.number() ) ); newEntry.setIndex( 0 ); cache->opers = new QModemPhoneBookOperation ( QModemPhoneBookOperation::Add, newEntry, cache->opers ); if ( cache->fullyLoaded && flush ) { flushOperations( cache ); } } /*! \reimp */ void QModemPhoneBook::remove( uint index, const QString& store, bool flush ) { QModemPhoneBookCache *cache = findCache( store ); QPhoneBookEntry entry; entry.setIndex( index ); cache->opers = new QModemPhoneBookOperation ( QModemPhoneBookOperation::Remove, entry, cache->opers ); if ( cache->fullyLoaded && flush ) { flushOperations( cache ); } } /*! \reimp */ void QModemPhoneBook::update ( const QPhoneBookEntry& entry, const QString& store, bool flush ) { QModemPhoneBookCache *cache = findCache( store ); QPhoneBookEntry newEntry( entry ); newEntry.setNumber( fixPhoneBookNumber( entry.number() ) ); cache->opers = new QModemPhoneBookOperation ( QModemPhoneBookOperation::Update, newEntry, cache->opers ); if ( cache->fullyLoaded && flush ) { flushOperations( cache ); } } /*! \reimp */ void QModemPhoneBook::flush( const QString& store ) { QModemPhoneBookCache *cache = findCache( store ); if ( cache->fullyLoaded ) { flushOperations( cache ); } } /*! \reimp */ void QModemPhoneBook::setPassword ( const QString& store, const QString& password ) { QModemPhoneBookCache *cache = findCache( store, true, password ); cache->passwd = password; // Force the storage to be reselected upon the next operation, // to force the password to be sent. forceStorageUpdate(); } /*! \reimp */ void QModemPhoneBook::clearPassword( const QString& store ) { QModemPhoneBookCache *cache = findCache( store ); cache->passwd = QString(); } /*! \reimp */ void QModemPhoneBook::requestLimits( const QString& store ) { QModemPhoneBookCache *cache; // Find the cache entry associated with this store. cache = findCache( store ); // If the cache is fully loaded, then emit the result now. // If there is a password, then force a re-get of the phone book // because the new password may not be the same as the original. if ( cache->fullyLoaded && cache->passwd.isEmpty() ) { emit limits( store, cache->limits ); return; } // We need to requery the extents if the phone book was previously loaded. if ( cache->fullyLoaded ) { cache->fullyLoaded = false; cache->entries.clear(); cache->limits = QPhoneBookLimits(); sendQuery( cache ); } // We'll need a signal to be emitted once it is fully loaded. cache->needLimitEmit = true; } /*! \reimp */ void QModemPhoneBook::requestFixedDialingState() { d->service->secondaryAtChat()->chat ( "AT+CLCK=\"FD\",2", this, SLOT(fdQueryDone(bool,QAtResult)) ); } /*! \reimp */ void QModemPhoneBook::setFixedDialingState( bool enabled, const QString& pin2 ) { QString cmd = "AT+CLCK=\"FD\","; if ( enabled ) cmd += "1,\""; else cmd += "0,\""; cmd += QAtUtils::quote( pin2 ); cmd += "\""; d->service->secondaryAtChat()->chat ( cmd, this, SLOT(fdModifyDone(bool,QAtResult)) ); } /*! Attempt to preload the contents of \a store, in anticipation that it will be needed sometime in the future. This is typically used for the "SM" store so that the contacts list appears to load quickly for the user. */ void QModemPhoneBook::preload( const QString& store ) { // Create the cache in "slow loading" mode. if ( ! hasModemPhoneBookCache() ) { findCache( store, false ); } } /*! Flush all cached phone book information from the system because the SIM has been removed from the modem or because the modem has indicated that the SIM phone book has changed. */ void QModemPhoneBook::flushCaches() { removeAllCaches(); d->pendingCommand = QString(); d->pendingStore = QString(); } /*! Indicate that the modem is now ready to accept phone book related commands. See hasModemPhoneBookCache() for more information. \sa hasModemPhoneBookCache() */ void QModemPhoneBook::phoneBooksReady() { // Caching modem has finished preloading the SIM phone book into // its own internal memory. Now we copy it into ours and then // force it to be emitted to the application layer to refresh // contact lists. requestStorages(); QModemPhoneBookCache *cache = findCache( "SM" ); cache->needEmit = true; // Do the same with the emergency numbers list. cache = findCache( "EN" ); cache->needEmit = true; } /*! Returns true if the modem has an internal phone book cache; false otherwise. If this function returns true, then the phone library will not attempt to access phone books until phoneBooksReady() is called. The default implementation returns false. \sa phoneBooksReady() */ bool QModemPhoneBook::hasModemPhoneBookCache() const { return false; } /*! Returns true if the \c index option to the \c{AT+CPBW} command should be empty to add an element rather than to update an existing element. Returns false (the default) if the \c index option should be zero for this case. */ bool QModemPhoneBook::hasEmptyPhoneBookIndex() const { return false; } void QModemPhoneBook::forceStorageUpdate() { // Force "updateStorageName()" to send the name update the next operation. d->prevStorageName = QString(); } class QStoreUserData : public QAtResult::UserData { public: QStoreUserData( const QString& store ) { this->store = store; } QString store; }; void QModemPhoneBook::updateStorageName ( const QString& storage, QObject *target, const char *slot ) { if ( d->prevStorageName != storage ) { d->prevStorageName = storage; QModemPhoneBookCache *cache = findCache( storage ); if ( !cache->passwd.isEmpty() ) { d->service->secondaryAtChat()->chat ( "AT+CPBS=\"" + storage + "\",\"" + QAtUtils::quote( cache->passwd ) + "\"", target, slot, new QStoreUserData( storage ) ); } else { d->service->secondaryAtChat()->chat ( "AT+CPBS=\"" + storage + "\"", target, slot, new QStoreUserData( storage ) ); } } } void QModemPhoneBook::sendQuery( QModemPhoneBookCache *cache ) { // Update the current storage name in the phone device. cache->selectOk = false; updateStorageName( cache->store, this, SLOT(selectDone(bool,QAtResult)) ); // Query the extents of the phone book, so we know what range to use. d->service->secondaryAtChat()->chat ( "AT+CPBR=?", this, SLOT(queryDone(bool,QAtResult)), new QStoreUserData( cache->store ) ); } void QModemPhoneBook::selectDone( bool ok, const QAtResult& result ) { QString store = ((QStoreUserData *)result.userData())->store; QModemPhoneBookCache *cache = findCache( store, false ); cache->selectOk = ok; } QModemPhoneBookCache *QModemPhoneBook::findCache ( const QString& store, bool fast, const QString& initialPassword ) { QModemPhoneBookCache *cache; // Search for an existing cache with this name. cache = d->caches; while ( cache != 0 ) { if ( cache->store == store ) { if ( fast ) { // We need the values soon, so speed up the fetch cycle. cache->fast = true; } if ( cache->redoQuery ) { // The last query attempt failed, so send another. cache->redoQuery = false; forceStorageUpdate(); sendQuery( cache ); } return cache; } cache = cache->next; } // Create a new cache. cache = new QModemPhoneBookCache( store ); cache->next = d->caches; cache->fast = fast; cache->passwd = initialPassword; d->caches = cache; // Send the query command. sendQuery( cache ); // Return the cache to the caller. return cache; } void QModemPhoneBook::flushOperations( QModemPhoneBookCache *cache ) { QModemPhoneBookOperation *oper; QModemPhoneBookOperation *prev; bool changes = false; int used = (int)(cache->limits.used()); // Process the operations, from the end of the queue back. while ( cache->opers != 0 ) { // Remove the last item on the queue. oper = cache->opers; prev = 0; while ( oper->next != 0 ) { prev = oper; oper = oper->next; } if ( prev ) { prev->next = oper->next; } else { cache->opers = oper->next; } // Process the operation. if ( oper->oper == QModemPhoneBookOperation::Add ) { flushAdd( oper->entry, cache ); ++used; } else if ( oper->oper == QModemPhoneBookOperation::Remove ) { flushRemove( oper->entry.index(), cache ); --used; } else if ( oper->oper == QModemPhoneBookOperation::Update ) { flushUpdate( oper->entry, cache ); } changes = true; // Delete the operation, which we no longer require. delete oper; } // Emit the entry list if changes were made. if ( changes ) { if ( used < 0 ) used = 0; // Just in case. cache->limits.setUsed( (uint)used ); emit entries( cache->store, cache->entries ); } } void QModemPhoneBook::flushAdd( const QPhoneBookEntry& entry, QModemPhoneBookCache *cache ) { uint index, adjindex; // Find an unused index in the cache. QList<QPhoneBookEntry>::ConstIterator iter; unsigned char *flags = new unsigned char [((cache->last - cache->first + 1) + 7) / 8]; ::memset( flags, 0, ((cache->last - cache->first + 1) + 7) / 8 ); for ( iter = cache->entries.begin(); iter != cache->entries.end(); ++iter ) { index = (*iter).index(); if ( index >= cache->first && index <= cache->last ) { adjindex = index - cache->first; flags[adjindex / 8] |= (1 << (adjindex % 8)); } } for ( index = cache->first; index <= cache->last; ++index ) { adjindex = index - cache->first; if ( (flags[adjindex / 8] & (1 << (adjindex % 8))) == 0 ) { break; } } delete flags; if ( index > cache->last ) { // The phone book is full, so we cannot add this entry. return; } // Update the phone device. QPhoneBookEntry newEntry( entry ); newEntry.setIndex( index ); flushUpdate( newEntry, cache ); } void QModemPhoneBook::flushRemove( uint index, QModemPhoneBookCache *cache ) { // Find the entry in the cache and remove it. QList<QPhoneBookEntry>::Iterator iter; for ( iter = cache->entries.begin(); iter != cache->entries.end(); ++iter ) { if ( (*iter).index() == index ) { cache->entries.erase( iter ); break; } } // Send the update command to the phone device. updateStorageName( cache->store ); d->service->secondaryAtChat()->chat ( "AT+CPBW=" + QString::number( index ) ); } void QModemPhoneBook::flushUpdate( const QPhoneBookEntry& entry, QModemPhoneBookCache *cache ) { // Find the entry in the cache and update it. uint index = entry.index(); QList<QPhoneBookEntry>::Iterator iter; bool found = false; for ( iter = cache->entries.begin(); iter != cache->entries.end(); ++iter ) { if ( (*iter).index() == index ) { (*iter) = entry; found = true; break; } } if ( !found ) { // This is an "add" operation, so add a new entry. QPhoneBookEntry newEntry( entry ); newEntry.setIndex( index ); cache->entries.append( newEntry ); if ( hasEmptyPhoneBookIndex() ) index = 0; } // Send the update command to the phone device. updateStorageName( cache->store ); QString indexString; if ( index == 0 && hasEmptyPhoneBookIndex() ) indexString = ""; else indexString = QString::number( index ); d->service->secondaryAtChat()->chat ( "AT+CPBW=" + indexString + "," + QAtUtils::encodeNumber( entry.number() ) + ",\"" + QAtUtils::quote( entry.text(), d->stringCodec ) + "\"" ); } void QModemPhoneBook::removeAllCaches() { if ( d->caches != 0 ) { QModemPhoneBookCache *cache = d->caches; while ( cache != 0 ) { cache->entries.clear(); emit entries( cache->store, cache->entries ); cache = cache->next; } delete d->caches; d->caches = 0; } } void QModemPhoneBook::cscsDone( bool ok, const QAtResult& result ) { if ( ok ) { QAtResultParser cmd( result ); cmd.next( "+CSCS:" ); QString name = cmd.readString(); if ( !name.isEmpty() ) { updateCodec( name ); } QTimer::singleShot( 8000, this, SLOT(requestStorages()) ); } else if ( d->charsetRetry-- > 0 ) { QTimer::singleShot( 3000, this, SLOT(requestCharset()) ); } else { QTimer::singleShot( 8000, this, SLOT(requestStorages()) ); } } void QModemPhoneBook::cscsSetDone( bool ok, const QAtResult& result ) { if ( ok ) { QTimer::singleShot( 8000, this, SLOT(requestStorages()) ); } else if ( d->charsetRetry-- > 0 ) { QTimer::singleShot( 3000, this, SLOT(setCharset()) ); } else { QTimer::singleShot( 8000, this, SLOT(requestStorages()) ); } } void QModemPhoneBook::cpbsDone( bool ok, const QAtResult& result ) { if ( ok ) { QAtResultParser cmd( result ); if ( cmd.next( "+CPBS:" ) ) { QList<QAtResultParser::Node> nodes = cmd.readList(); QStringList storages; for ( int i = 0; i < nodes.count(); i++ ) storages.append( nodes.at( i ).asString() ); setValue( QLatin1String("Storages"), storages ); } emit ready(); } else if ( d->storageRetry-- > 0 ) { QTimer::singleShot( 5000, this, SLOT(requestStorages()) ); } } /*! Inform the modem SIM phone book handler that the \c{AT+CSCS} character set has been changed to \a gsmCharset. \sa stringCodec() */ void QModemPhoneBook::updateCodec( const QString& gsmCharset ) { d->stringCodec = QAtUtils::codec( gsmCharset ); } static uint nextNumber( const QString& line, uint& posn ) { uint value = 0; while ( posn < (uint)(line.length()) && ( line[posn] < '0' || line[posn] > '9' ) ) { ++posn; } while ( posn < (uint)(line.length()) && line[posn] >= '0' && line[posn] <= '9' ) { value = value * 10 + (uint)(line[posn].unicode() - '0'); ++posn; } return value; } void QModemPhoneBook::readDone( bool ok, const QAtResult& result ) { QAtResultParser cmd( result ); // Get the storage area that this response applies to. QString store = ((QStoreUserData *)result.userData())->store; QModemPhoneBookCache *cache = findCache( store, false ); // Extract the entries from the response. QString line, number, text; uint posn, index, type; QPhoneBookEntry entry; while ( cmd.next( "+CPBR:" ) ) { // Parse the contents of the line. line = cmd.line(); posn = 0; index = nextNumber( line, posn ); number = QAtUtils::nextString( line, posn ); type = nextNumber( line, posn ); text = QAtUtils::nextString( line, posn ); if ( type == 145 && ( number.length() == 0 || number[0] != '+' ) ) { number = "+" + number; } // Add the entry to the list. entry.setIndex( index ); entry.setNumber( number ); entry.setText( QAtUtils::decode( text, d->stringCodec ) ); cache->entries.append( entry ); } // Determine if the list has finished loading. if ( ok && cache->current <= cache->last ) { // Fetch the next 10 elements in "slow" mode, or everything if "fast". uint first = cache->current; uint last = cache->last; if ( !(cache->fast) ) { if ( ( last - first + 1 ) > 10 ) { last = first + 9; } } cache->current = last + 1; // Update the current storage name in the phone device. updateStorageName( store ); // Query the extents of the phone book, so we know what range to use. QString command; command = "AT+CPBR=" + QString::number( first ) + "," + QString::number(last); d->pendingCommand = QString(); d->pendingStore = QString(); if ( cache->fast ) { d->service->secondaryAtChat()->chat ( command, this, SLOT(readDone(bool,QAtResult)), new QStoreUserData( store ) ); } else { // Don't send it immediately: wait a bit to give other // parts of the system access to the AT handlers too. setGsmCharset(); d->pendingCommand = command; d->pendingStore = store; d->slowTimer->start( SLOW_UPDATE_TIMEOUT ); } } else { // The fetch has completed. setGsmCharset(); readFinished( cache ); } } void QModemPhoneBook::readFinished( QModemPhoneBookCache *cache ) { cache->fullyLoaded = true; cache->limits.setUsed( (uint)( cache->entries.size() ) ); // Emit the list of entries if we have a pending "getEntries". if ( cache->needEmit ) { cache->needEmit = false; emit entries( cache->store, cache->entries ); } // Emit the limits if we have a pending "requestLimits()". if ( cache->needLimitEmit ) { cache->needLimitEmit = false; emit limits( cache->store, cache->limits ); } // Execute pending add/remove/update commands. flushOperations( cache ); } void QModemPhoneBook::queryDone( bool ok, const QAtResult& result ) { QAtResultParser cmd( result ); // Get the storage area that this response applies to. QString store = ((QStoreUserData *)result.userData())->store; QModemPhoneBookCache *cache = findCache( store, false ); // If the query failed on a modem that caches phone books internally, // we need to queue it again for later. if ( !ok && hasModemPhoneBookCache() ) { cache->redoQuery = true; return; } // If the select failed, then the phone book does not exist and // we may have accidentally picked up a different phone book. if ( !cache->selectOk ) { readFinished( cache ); return; } // Extract the extent information for the phone book. // We assume that it has the format "(N-M)". uint first = 0; uint last = 0; uint nlength = 0; uint tlength = 0; if ( cmd.next( "+CPBR:" ) ) { QString line = cmd.line(); int posn = 0; while ( posn < line.length() && line[posn] != '(' ) { ++posn; } if ( posn < line.length() ) { ++posn; while ( posn < line.length() && line[posn] >= '0' && line[posn] <= '9' ) { first = first * 10 + (uint)(line[posn].unicode() - '0'); ++posn; } } while ( posn < line.length() && line[posn] != ')' ) { ++posn; } uint end = (uint)(posn + 1); if ( posn < line.length () ) { uint mult = 1; while ( posn > 0 && line[posn - 1] >= '0' && line[posn - 1] <= '9' ) { --posn; last += mult * (uint)(line[posn].unicode() - '0'); mult *= 10; } } nlength = QAtUtils::parseNumber( line, end ); tlength = QAtUtils::parseNumber( line, end ); } // Record the storage limits in the cache. cache->first = first; cache->last = last; cache->limits.setFirstIndex( first ); cache->limits.setLastIndex( last ); cache->limits.setNumberLength( nlength ); cache->limits.setTextLength( tlength ); // Determine how many entries to fetch. In "slow loading" // mode, we don't load more than 10 entries at a time, so // that other things in the system have a chance to work. if ( !(cache->fast) ) { if ( ( last - first + 1 ) > 10 ) { last = first + 9; } } cache->current = last + 1; // Update the storage name in the device again, just in case a // request for another phone book arrived in the meantime. updateStorageName( store ); // Send the read command to get the entries. QString command; command = "AT+CPBR=" + QString::number( first ) + "," + QString::number(last); setUcs2Charset(); d->service->secondaryAtChat()->chat ( command, this, SLOT(readDone(bool,QAtResult)), new QStoreUserData( store ) ); } void QModemPhoneBook::slowTimeout() { if ( !d->pendingCommand.isEmpty() ) { setUcs2Charset(); d->service->secondaryAtChat()->chat ( d->pendingCommand, this, SLOT(readDone(bool,QAtResult)), new QStoreUserData( d->pendingStore ) ); d->pendingCommand = QString(); d->pendingStore = QString(); } } void QModemPhoneBook::fdQueryDone( bool, const QAtResult& result ) { bool enabled = false; QAtResultParser parser( result ); if ( parser.next( "+CLCK:" ) ) { enabled = ( parser.readNumeric() != 0 ); } emit fixedDialingState( enabled ); } void QModemPhoneBook::fdModifyDone( bool, const QAtResult& result ) { emit setFixedDialingStateResult( (QTelephony::Result)result.resultCode() ); } void QModemPhoneBook::requestCharset() { d->service->secondaryAtChat()->chat ( "AT+CSCS?", this, SLOT(cscsDone(bool,QAtResult)) ); } void QModemPhoneBook::setUcs2Charset() { d->stringCodec = QAtUtils::codec( "UCS2" ); d->service->secondaryAtChat()->chat( "AT+CSCS=\"UCS2\"" ); } void QModemPhoneBook::setGsmCharset() { d->stringCodec = QAtUtils::codec( "GSM" ); d->service->secondaryAtChat()->chat( "AT+CSCS=\"GSM\"" ); } void QModemPhoneBook::requestStorages() { d->service->secondaryAtChat()->chat ( "AT+CPBS=?", this, SLOT(cpbsDone(bool,QAtResult)) ); }
gpl-2.0
dbaker3/welshimer2013_r14
no-results.php
1096
<?php /** * The template part for displaying a message that posts cannot be found. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package welshimer2013 * @since welshimer2013 1.0 */ ?> <article id="post-0" class="post no-results not-found"> <header class="entry-header"> <h1 class="entry-title"><?php _e( 'Nothing Found', 'welshimer2013' ); ?></h1> </header><!-- .entry-header --> <div class="entry-content"> <?php if ( is_home() ) { ?> <p><?php printf( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'welshimer2013' ), admin_url( 'post-new.php' ) ); ?></p> <?php } elseif ( is_search() ) { ?> <p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'welshimer2013' ); ?></p> <?php get_search_form(); ?> <?php } else { ?> <p><?php _e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching can help.', 'welshimer2013' ); ?></p> <?php get_search_form(); ?> <?php } ?> </div><!-- .entry-content --> </article><!-- #post-0 -->
gpl-2.0
MinnPost/minnpost-wordpress
wp-content/plugins/the-events-calendar/src/deprecated/Tribe__Events__Meta_Factory.php
7531
<?php /** * Meta Factory * * Events have meta that may change in the way it is displayed across templates. * The meta factory provides a storage and templating engine similar to the WordPress * Widget Factory which allows for registration, sorting, assignment, templating and * deregistration of meta items within a Tribe Meta container (similar to "sidebar") * * @deprecated 4.3 */ _deprecated_file( __FILE__, '4.3' ); if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } if ( ! class_exists( 'Tribe__Events__Meta_Factory' ) ) { class Tribe__Events__Meta_Factory { public $meta = []; public $meta_group = []; const META_IDS = 'meta_ids'; /** * register meta or meta_groups * * @deprecated 4.3 * * @param string $meta * @param array $args * * @return bool */ public static function register( $meta_id, $args = [] ) { global $_tribe_meta_factory; $defaults = [ 'wrap' => [ 'before' => '<div class="%s">', 'after' => '</div>', 'label_before' => '<label>', 'label_after' => '</label>', 'meta_before' => '<div class="%s">', 'meta_separator' => '', 'meta_after' => '</div>', ], 'classes' => [ 'before' => [ 'tribe-meta' ], 'meta_before' => [ 'tribe-meta-value' ], ], 'register_type' => 'meta', 'register_overwrite' => false, 'register_callback' => null, 'filter_callback' => null, 'callback' => null, 'meta_value' => null, 'label' => ucwords( preg_replace( '/[_-]/', ' ', $meta_id ) ), // if label is not set then use humanized form of meta_group_id 'show_on_meta' => true, // bool for automatically displaying meta within "the meta area" of a specific display 'priority' => 100, ]; // before we merge args and defaults lets play nice with the template if ( ! empty( $args['wrap'] ) ) { $args['wrap'] = wp_parse_args( $args['wrap'], $defaults['wrap'] ); } $args = wp_parse_args( $args, $defaults ); // setup default meta ids placeholder for meta_group registration if ( $args['register_type'] == 'meta_group' && empty( $args[ self::META_IDS ] ) ) { $args[ self::META_IDS ] = []; } do_action( 'tribe_meta_factory_register', $meta_id, $args ); // check if we should overwrite the existing registration args if set if ( isset( $_tribe_meta_factory->{$args['register_type']}[ $meta_id ] ) && ! $args['register_overwrite'] ) { return false; // otherwise merge existing args with new args and reregister } else { if ( isset( $_tribe_meta_factory->{$args['register_type']}[ $meta_id ] ) ) { $args = wp_parse_args( $args, $_tribe_meta_factory->{$args['register_type']}[ $meta_id ] ); } } $_tribe_meta_factory->{$args['register_type']}[ $meta_id ] = $args; // associate a meta item to a meta group(s) isset if ( $args['register_type'] == 'meta' && ! empty( $args['group'] ) ) { foreach ( (array) $args['group'] as $group ) { // if group doesn't exist - then register it before proceeding if ( ! self::check_exists( $group, 'meta_group' ) ) { tribe_register_meta_group( $group ); // if the meta_id has already been added to the group move onto the next one } elseif ( in_array( $meta_id, $_tribe_meta_factory->meta_group[ $group ][ self::META_IDS ] ) ) { continue; } $_tribe_meta_factory->meta_group[ $group ][ self::META_IDS ][] = $meta_id; } } // let the request know if we are successful for registering return true; } /** * check to see if meta item has been defined * * @deprecated 4.3 * * @param string $meta_id * @param string $type * * @return boolean */ public static function check_exists( $meta_id, $type = 'meta' ) { global $_tribe_meta_factory; $status = isset( $_tribe_meta_factory->{$type}[ $meta_id ] ) ? true : false; return apply_filters( 'tribe_meta_factory_check_exists', $status ); } /** * get meta arguments * * @deprecated 4.3 * * @param string $meta_id * @param string $type * * @return array of arguments */ public static function get_args( $meta_id, $type = 'meta' ) { global $_tribe_meta_factory; $args = self::check_exists( $meta_id, $type ) ? $_tribe_meta_factory->{$type}[ $meta_id ] : []; return apply_filters( 'tribe_meta_factory_get_args', $args ); } /** * get the set order of meta items * useful when generically displaying meta for skeleton view or bulk assignments * * @param string $meta_id * * @return array of ordered meta ids */ public static function get_order( $meta_id = null ) { global $_tribe_meta_factory; $ordered_group = []; if ( self::check_exists( $meta_id, 'meta_group' ) ) { foreach ( $_tribe_meta_factory->meta_group[ $meta_id ][ self::META_IDS ] as $key ) { if ( $item = self::get_args( $key ) ) { $ordered_group[ $item['priority'] ][] = $key; } } } else { foreach ( $_tribe_meta_factory->meta_group as $key => $item ) { $ordered_group[ $item['priority'] ][] = $key; } } ksort( $ordered_group ); return $ordered_group; } /** * set the visibility of a meta item when using a bulk display tag * * @param string $meta_id * @param string $type * @param boolean $status */ public static function set_visibility( $meta_id, $type = 'meta', $status = true ) { global $_tribe_meta_factory; if ( self::check_exists( $meta_id, $type ) ) { $_tribe_meta_factory->{$type}[ $meta_id ]['show_on_meta'] = $status; } } /** * embed css classes for templating the meta item on display * * @param string $template * @param array $classes * * @return string $template */ public static function embed_classes( $template, $classes = [] ) { if ( ! empty( $classes ) && is_array( $classes ) ) { // loop through the available class to template associations foreach ( $classes as $key => $class_list ) { if ( ! empty( $class_list ) && ! empty( $template[ $key ] ) && ( strpos( $template[ $key ], '%s' ) !== false || strpos( $template[ $key ], '%d' ) !== false ) ) { // if we're passed an array lets implode it $class_list = is_array( $class_list ) ? implode( ' ', $class_list ) : $class_list; // process the template string with all classes $template[ $key ] = vsprintf( $template[ $key ], $class_list ); } } } return $template; } /** * return a completed meta template for display * @uses self::embed_classes for css classes * * @param string $label * @param string $meta * @param string $meta_id * @param string $type * * @return string $html finished meta item for display */ public static function template( $label, $meta, $meta_id, $type = 'meta' ) { global $_tribe_meta_factory; $template = self::embed_classes( $_tribe_meta_factory->{$type}[ $meta_id ]['wrap'], $_tribe_meta_factory->{$type}[ $meta_id ]['classes'] ); $html = sprintf( '%s%s%s%s', $template['before'], ! empty( $label ) ? $template['label_before'] . $label . $template['label_after'] : '', ! empty( $meta ) ? $template['meta_before'] . $meta . $template['meta_after'] : '', $template['after'] ); return apply_filters( 'tribe_meta_factory_template', $html, $label, $meta, $template ); } } }
gpl-2.0
SuriyaaKudoIsc/wikia-app-test
extensions/RTLDebug/rtl-debug.js
321
( function( $ ) { // Select all elements in the body (we don't need stuff in <head>) $( document.body ) .find( '*' ) .andSelf() // include body as well .each( function() { var $el = $( this ); $el.addClass( $el.css( 'direction' ) === 'rtl' ? 'mw-rtldebug-rtl' : 'mw-rtldebug-ltr' ); } ); } )( jQuery );
gpl-2.0
magic2du/contact_matrix
Contact_maps/DeepLearning/DeepLearningTool/DL_contact_matrix_load2-new10fold_11_04_2014_server.py
41826
# coding: utf-8 # In[3]: import sys, os sys.path.append('../../../libs/') import os.path import IO_class from IO_class import FileOperator from sklearn import cross_validation import sklearn import numpy as np import csv from dateutil import parser from datetime import timedelta from sklearn import svm import numpy as np import pandas as pd import pdb import pickle import numpy as np from sklearn.cross_validation import train_test_split from sklearn.cross_validation import KFold from sklearn import preprocessing import sklearn import scipy.stats as ss from sklearn.svm import LinearSVC import random from DL_libs import * from itertools import izip #new import math from sklearn.svm import SVC # In[4]: #filename = 'SUCCESS_log_CrossValidation_load_DL_remoteFisherM1_DL_RE_US_DL_RE_US_1_1_19MAY2014.txt' #filename = 'listOfDDIsHaveOver2InterfacesHave40-75_Examples_2010_real_selected.txt' #for testing # set settings for this script settings = {} settings['filename'] = 'ddi_examples_40_60_over2top_diff_name_2014.txt' settings['fisher_mode'] = 'FisherM1' settings['predicted_score'] = False settings['reduce_ratio'] = 1 settings['SVM'] = 1 settings['DL'] = 1 settings['SAE_SVM'] = 0 settings['SVM_RBF'] = 1 settings['SVM_POLY'] = 0 settings['DL_S'] = 0 settings['DL_U'] = 0 settings['finetune_lr'] = 1 settings['batch_size'] = 100 settings['pretraining_interations'] = 25000 settings['pretrain_lr'] = 0.001 settings['training_epochs'] = 4000 settings['hidden_layers_sizes'] = [100, 100] settings['corruption_levels'] = [0,0] filename = settings['filename'] file_obj = FileOperator(filename) ddis = file_obj.readStripLines() import logging import time current_date = time.strftime("%m_%d_%Y") logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logname = 'log_DL_contact_matrix_load' + current_date + '.log' handler = logging.FileHandler(logname) handler.setLevel(logging.DEBUG) # create a logging format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # add the handlers to the logger logger.addHandler(handler) logger.info('Input DDI file: ' + filename) #logger.debug('This message should go to the log file') for key, value in settings.items(): logger.info(key +': '+ str(value)) # In[5]: ddis # In[28]: class DDI_family_base(object): #def __init__(self, ddi, Vectors_Fishers_aaIndex_raw_folder = '/home/du/Documents/Vectors_Fishers_aaIndex_raw_2014/'): #def __init__(self, ddi, Vectors_Fishers_aaIndex_raw_folder = '/home/sun/Downloads/contactmatrix/contactmatrixanddeeplearningcode/data_test/'): def __init__(self, ddi, Vectors_Fishers_aaIndex_raw_folder = '/big/du/Protein_Protein_Interaction_Project/Contact_Matrix_Project/Vectors_Fishers_aaIndex_raw_2014_paper/'): """ get total number of sequences in a ddi familgy Attributes: ddi: string ddi name Vectors_Fishers_aaIndex_raw_folder: string, folder total_number_of_sequences: int raw_data: dict raw_data[2] LOO_data['FisherM1'][1] """ self.ddi = ddi self.Vectors_Fishers_aaIndex_raw_folder = Vectors_Fishers_aaIndex_raw_folder self.ddi_folder = self.Vectors_Fishers_aaIndex_raw_folder + ddi + '/' self.total_number_of_sequences = self.get_total_number_of_sequences() self.raw_data = {} self.positve_negative_number = {} self.equal_size_data = {} for seq_no in range(1, self.total_number_of_sequences+1): self.raw_data[seq_no] = self.get_raw_data_for_selected_seq(seq_no) try: #positive_file = self.ddi_folder + 'numPos_'+ str(seq_no) + '.txt' #file_obj = FileOperator(positive_file) #lines = file_obj.readStripLines() #import pdb; pdb.set_trace() count_pos = int(np.sum(self.raw_data[seq_no][:, -1])) count_neg = self.raw_data[seq_no].shape[0] - count_pos #self.positve_negative_number[seq_no] = {'numPos': int(float(lines[0]))} #assert int(float(lines[0])) == count_pos self.positve_negative_number[seq_no] = {'numPos': count_pos} #negative_file = self.ddi_folder + 'numNeg_'+ str(seq_no) + '.txt' #file_obj = FileOperator(negative_file) #lines = file_obj.readStripLines() #self.positve_negative_number[seq_no]['numNeg'] = int(float(lines[0])) self.positve_negative_number[seq_no]['numNeg'] = count_neg except Exception,e: print ddi, seq_no print str(e) logger.info(ddi + str(seq_no)) logger.info(str(e)) # get data for equal positive and negative n_pos = self.positve_negative_number[seq_no]['numPos'] n_neg = self.positve_negative_number[seq_no]['numNeg'] index_neg = range(n_pos, n_pos + n_neg) random.shuffle(index_neg) index_neg = index_neg[: n_pos] positive_examples = self.raw_data[seq_no][ : n_pos, :] negative_examples = self.raw_data[seq_no][index_neg, :] self.equal_size_data[seq_no] = np.vstack((positive_examples, negative_examples)) def get_LOO_training_and_reduced_traing(self, seq_no, fisher_mode = 'FisherM1ONLY' , reduce_ratio = 4): """ get the leave one out traing data, reduced traing Parameters: seq_no: fisher_mode: default 'FisherM1ONLY' Returns: (train_X_LOO, train_y_LOO),(train_X_reduced, train_y_reduced), (test_X, test_y) """ train_X_LOO = np.array([]) train_y_LOO = np.array([]) train_X_reduced = np.array([]) train_y_reduced = np.array([]) total_number_of_sequences = self.total_number_of_sequences equal_size_data_selected_sequence = self.equal_size_data[seq_no] #get test data for selected sequence test_X, test_y = self.select_X_y(equal_size_data_selected_sequence, fisher_mode = fisher_mode) total_sequences = range(1, total_number_of_sequences+1) loo_sequences = [i for i in total_sequences if i != seq_no] number_of_reduced = len(loo_sequences)/reduce_ratio if len(loo_sequences)/reduce_ratio !=0 else 1 random.shuffle(loo_sequences) reduced_sequences = loo_sequences[:number_of_reduced] #for loo data for current_no in loo_sequences: raw_current_data = self.equal_size_data[current_no] current_X, current_y = self.select_X_y(raw_current_data, fisher_mode = fisher_mode) if train_X_LOO.ndim ==1: train_X_LOO = current_X else: train_X_LOO = np.vstack((train_X_LOO, current_X)) train_y_LOO = np.concatenate((train_y_LOO, current_y)) #for reduced data for current_no in reduced_sequences: raw_current_data = self.equal_size_data[current_no] current_X, current_y = self.select_X_y(raw_current_data, fisher_mode = fisher_mode) if train_X_reduced.ndim ==1: train_X_reduced = current_X else: train_X_reduced = np.vstack((train_X_reduced, current_X)) train_y_reduced = np.concatenate((train_y_reduced, current_y)) return (train_X_LOO, train_y_LOO),(train_X_reduced, train_y_reduced), (test_X, test_y) #def get_ten_fold_crossvalid_one_subset(self, start_subset, end_subset, fisher_mode = 'FisherM1ONLY' , reduce_ratio = 4): def get_ten_fold_crossvalid_one_subset(self, train_index, test_index, fisher_mode = 'FisherM1ONLY' , reduce_ratio = 4): """ get traing data, reduced traing data for 10-fold crossvalidation Parameters: start_subset: index of start of the testing data end_subset: index of end of the testing data fisher_mode: default 'FisherM1ONLY' Returns: (train_X_10fold, train_y_10fold),(train_X_reduced, train_y_reduced), (test_X, test_y) """ train_X_10fold = np.array([]) train_y_10fold = np.array([]) train_X_reduced = np.array([]) train_y_reduced = np.array([]) test_X = np.array([]) test_y = np.array([]) total_number_of_sequences = self.total_number_of_sequences #get test data for selected sequence #for current_no in range(start_subset, end_subset): for num in test_index: current_no = num + 1 raw_current_data = self.equal_size_data[current_no] current_X, current_y = self.select_X_y(raw_current_data, fisher_mode = fisher_mode) if test_X.ndim ==1: test_X = current_X else: test_X = np.vstack((test_X, current_X)) test_y = np.concatenate((test_y, current_y)) #total_sequences = range(1, total_number_of_sequences+1) #ten_fold_sequences = [i for i in total_sequences if not(i in range(start_subset, end_subset))] #number_of_reduced = len(ten_fold_sequences)/reduce_ratio if len(ten_fold_sequences)/reduce_ratio !=0 else 1 #random.shuffle(ten_fold_sequences) #reduced_sequences = ten_fold_sequences[:number_of_reduced] number_of_reduced = len(train_index)/reduce_ratio if len(train_index)/reduce_ratio !=0 else 1 random.shuffle(train_index) reduced_sequences = train_index[:number_of_reduced] #for 10-fold cross-validation data #for current_no in ten_fold_sequences: for num in train_index: current_no = num + 1 raw_current_data = self.equal_size_data[current_no] current_X, current_y = self.select_X_y(raw_current_data, fisher_mode = fisher_mode) if train_X_10fold.ndim ==1: train_X_10fold = current_X else: train_X_10fold = np.vstack((train_X_10fold, current_X)) train_y_10fold = np.concatenate((train_y_10fold, current_y)) #for reduced data for num in reduced_sequences: current_no = num + 1 raw_current_data = self.equal_size_data[current_no] current_X, current_y = self.select_X_y(raw_current_data, fisher_mode = fisher_mode) if train_X_reduced.ndim ==1: train_X_reduced = current_X else: train_X_reduced = np.vstack((train_X_reduced, current_X)) train_y_reduced = np.concatenate((train_y_reduced, current_y)) return (train_X_10fold, train_y_10fold),(train_X_reduced, train_y_reduced), (test_X, test_y) def get_total_number_of_sequences(self): """ get total number of sequences in a ddi familgy Parameters: ddi: string Vectors_Fishers_aaIndex_raw_folder: string Returns: n: int """ folder_path = self.Vectors_Fishers_aaIndex_raw_folder + self.ddi + '/' filename = folder_path +'allPairs.txt' all_pairs = np.loadtxt(filename) return len(all_pairs) def get_raw_data_for_selected_seq(self, seq_no): """ get raw data for selected seq no in a family Parameters: ddi: seq_no: Returns: data: raw data in the sequence file """ folder_path = self.Vectors_Fishers_aaIndex_raw_folder + self.ddi + '/' filename = folder_path + 'F0_20_F1_20_Sliding_17_11_F0_20_F1_20_Sliding_17_11_ouput_'+ str(seq_no) + '.txt' data = np.loadtxt(filename) return data def select_X_y(self, data, fisher_mode = ''): """ select subset from the raw input data set Parameters: data: data from matlab txt file fisher_mode: subset base on this Fisher of AAONLY... Returns: selected X, y """ y = data[:,-1] # get lable if fisher_mode == 'FisherM1': # fisher m1 plus AA index a = data[:, 20:227] b = data[:, 247:454] X = np.hstack((a,b)) elif fisher_mode == 'FisherM1ONLY': a = data[:, 20:40] b = data[:, 247:267] X = np.hstack((a,b)) elif fisher_mode == 'AAONLY': a = data[:, 40:227] b = data[:, 267:454] X = np.hstack((a,b)) else: raise('there is an error in mode') return X, y # In[28]: # In[29]: import sklearn.preprocessing def performance_score(target_label, predicted_label, predicted_score = False, print_report = True): """ get performance matrix for prediction Attributes: target_label: int 0, 1 predicted_label: 0, 1 or ranking predicted_score: bool if False, predicted_label is from 0, 1. If Ture, predicted_label is ranked, need to get AUC score. print_report: if True, print the perfromannce on screen """ import sklearn from sklearn.metrics import roc_auc_score score = {} if predicted_score == False: score['accuracy'] = sklearn.metrics.accuracy_score(target_label, predicted_label) score['precision'] = sklearn.metrics.precision_score(target_label, predicted_label, pos_label=1) score['recall'] = sklearn.metrics.recall_score(target_label, predicted_label, pos_label=1) if predicted_score == True: auc_score = roc_auc_score(target_label, predicted_label) score['auc_score'] = auc_score target_label = [x >= 0.5 for x in target_label] score['accuracy'] = sklearn.metrics.accuracy_score(target_label, predicted_label) score['precision'] = sklearn.metrics.precision_score(target_label, predicted_label, pos_label=1) score['recall'] = sklearn.metrics.recall_score(target_label, predicted_label, pos_label=1) if print_report == True: for key, value in score.iteritems(): print key, '{percent:.1%}'.format(percent=value) return score def saveAsCsv(predicted_score, fname, score_dict, *arguments): #new newfile = False if os.path.isfile('report_' + fname + '.csv'): pass else: newfile = True csvfile = open('report_' + fname + '.csv', 'a+') writer = csv.writer(csvfile) if newfile == True: if predicted_score == False: writer.writerow(['DDI', 'no.', 'FisherMode', 'method', 'isTest']+ score_dict.keys()) #, 'AUC']) else: writer.writerow(['DDI', 'no.', 'FisherMode', 'method', 'isTest'] + score_dict.keys()) for arg in arguments: writer.writerows(arg) csvfile.close() def LOO_out_performance_for_all(ddis): for ddi in ddis: try: one_ddi_family = LOO_out_performance_for_one_ddi(ddi) one_ddi_family.get_LOO_perfermance(settings = settings) except Exception,e: print str(e) logger.info("There is a error in this ddi: %s" % ddi) logger.info(str(e)) class LOO_out_performance_for_one_ddi(object): """ get the performance of ddi families Attributes: ddi: string ddi name Vectors_Fishers_aaIndex_raw_folder: string, folder total_number_of_sequences: int raw_data: dict raw_data[2] """ def __init__(self, ddi): self.ddi_obj = DDI_family_base(ddi) self.ddi = ddi def get_LOO_perfermance(self, settings = None): fisher_mode = settings['fisher_mode'] analysis_scr = [] predicted_score = settings['predicted_score'] reduce_ratio = settings['reduce_ratio'] for seq_no in range(1, self.ddi_obj.total_number_of_sequences+1): print seq_no logger.info('sequence number: ' + str(seq_no)) if settings['SVM']: print "SVM" (train_X_LOO, train_y_LOO),(train_X_reduced, train_y_reduced), (test_X, test_y) = self.ddi_obj.get_LOO_training_and_reduced_traing(seq_no,fisher_mode = fisher_mode, reduce_ratio = reduce_ratio) standard_scaler = preprocessing.StandardScaler().fit(train_X_reduced) scaled_train_X = standard_scaler.transform(train_X_reduced) scaled_test_X = standard_scaler.transform(test_X) Linear_SVC = LinearSVC(C=1, penalty="l2") Linear_SVC.fit(scaled_train_X, train_y_reduced) predicted_test_y = Linear_SVC.predict(scaled_test_X) isTest = True; #new analysis_scr.append((self.ddi, seq_no, fisher_mode, 'SVM', isTest) + tuple(performance_score(test_y, predicted_test_y).values())) #new predicted_train_y = Linear_SVC.predict(scaled_train_X) isTest = False; #new analysis_scr.append((self.ddi, seq_no, fisher_mode, 'SVM', isTest) + tuple(performance_score(train_y_reduced, predicted_train_y).values())) # Deep learning part min_max_scaler = Preprocessing_Scaler_with_mean_point5() X_train_pre_validation_minmax = min_max_scaler.fit(train_X_reduced) X_train_pre_validation_minmax = min_max_scaler.transform(train_X_reduced) x_test_minmax = min_max_scaler.transform(test_X) pretraining_X_minmax = min_max_scaler.transform(train_X_LOO) x_train_minmax, x_validation_minmax, y_train_minmax, y_validation_minmax = train_test_split(X_train_pre_validation_minmax, train_y_reduced , test_size=0.4, random_state=42) finetune_lr = settings['finetune_lr'] batch_size = settings['batch_size'] pretraining_epochs = cal_epochs(settings['pretraining_interations'], x_train_minmax, batch_size = batch_size) #pretrain_lr=0.001 pretrain_lr = settings['pretrain_lr'] training_epochs = settings['training_epochs'] hidden_layers_sizes= settings['hidden_layers_sizes'] corruption_levels = settings['corruption_levels'] if settings['DL']: print "direct deep learning" # direct deep learning sda = trainSda(x_train_minmax, y_train_minmax, x_validation_minmax, y_validation_minmax , x_test_minmax, test_y, hidden_layers_sizes = hidden_layers_sizes, corruption_levels = corruption_levels, batch_size = batch_size , \ training_epochs = training_epochs, pretraining_epochs = pretraining_epochs, pretrain_lr = pretrain_lr, finetune_lr=finetune_lr ) print 'hidden_layers_sizes:', hidden_layers_sizes print 'corruption_levels:', corruption_levels training_predicted = sda.predict(x_train_minmax) y_train = y_train_minmax isTest = False; #new analysis_scr.append((self.ddi, seq_no, fisher_mode, 'DL', isTest) + tuple(performance_score(y_train, training_predicted).values())) test_predicted = sda.predict(x_test_minmax) y_test = test_y isTest = True; #new analysis_scr.append((self.ddi, seq_no, fisher_mode, 'DL', isTest) + tuple(performance_score(y_test, test_predicted).values())) if 0: # deep learning using unlabeled data for pretraining print 'deep learning with unlabel data' pretraining_epochs_for_reduced = cal_epochs(1500, pretraining_X_minmax, batch_size = batch_size) sda_unlabel = trainSda(x_train_minmax, y_train_minmax, x_validation_minmax, y_validation_minmax , x_test_minmax, test_y, pretraining_X_minmax = pretraining_X_minmax, hidden_layers_sizes = hidden_layers_sizes, corruption_levels = corruption_levels, batch_size = batch_size , \ training_epochs = training_epochs, pretraining_epochs = pretraining_epochs_for_reduced, pretrain_lr = pretrain_lr, finetune_lr=finetune_lr ) print 'hidden_layers_sizes:', hidden_layers_sizes print 'corruption_levels:', corruption_levels training_predicted = sda_unlabel.predict(x_train_minmax) y_train = y_train_minmax isTest = False; #new analysis_scr.append((self.ddi, seq_no, fisher_mode, 'DL_U', isTest) + tuple(performance_score(y_train, training_predicted, predicted_score).values())) test_predicted = sda_unlabel.predict(x_test_minmax) y_test = test_y isTest = True; #new analysis_scr.append((self.ddi, seq_no, fisher_mode, 'DL_U', isTest) + tuple(performance_score(y_test, test_predicted, predicted_score).values())) if settings['DL_S']: # deep learning using split network print 'deep learning using split network' # get the new representation for A set. first 784-D pretraining_epochs = cal_epochs(settings['pretraining_interations'], x_train_minmax, batch_size = batch_size) hidden_layers_sizes= settings['hidden_layers_sizes'] corruption_levels = settings['corruption_levels'] x = x_train_minmax[:, :x_train_minmax.shape[1]/2] print "original shape for A", x.shape a_MAE_A = train_a_MultipleAEs(x, pretraining_epochs=pretraining_epochs, pretrain_lr=pretrain_lr, batch_size=batch_size, hidden_layers_sizes =hidden_layers_sizes, corruption_levels=corruption_levels) new_x_train_minmax_A = a_MAE_A.transform(x_train_minmax[:, :x_train_minmax.shape[1]/2]) x = x_train_minmax[:, x_train_minmax.shape[1]/2:] print "original shape for B", x.shape a_MAE_B = train_a_MultipleAEs(x, pretraining_epochs=pretraining_epochs, pretrain_lr=pretrain_lr, batch_size=batch_size, hidden_layers_sizes =hidden_layers_sizes, corruption_levels=corruption_levels) new_x_train_minmax_B = a_MAE_B.transform(x_train_minmax[:, x_train_minmax.shape[1]/2:]) new_x_test_minmax_A = a_MAE_A.transform(x_test_minmax[:, :x_test_minmax.shape[1]/2]) new_x_test_minmax_B = a_MAE_B.transform(x_test_minmax[:, x_test_minmax.shape[1]/2:]) new_x_validation_minmax_A = a_MAE_A.transform(x_validation_minmax[:, :x_validation_minmax.shape[1]/2]) new_x_validation_minmax_B = a_MAE_B.transform(x_validation_minmax[:, x_validation_minmax.shape[1]/2:]) new_x_train_minmax_whole = np.hstack((new_x_train_minmax_A, new_x_train_minmax_B)) new_x_test_minmax_whole = np.hstack((new_x_test_minmax_A, new_x_test_minmax_B)) new_x_validationt_minmax_whole = np.hstack((new_x_validation_minmax_A, new_x_validation_minmax_B)) finetune_lr = settings['finetune_lr'] batch_size = settings['batch_size'] pretraining_epochs = cal_epochs(settings['pretraining_interations'], x_train_minmax, batch_size = batch_size) #pretrain_lr=0.001 pretrain_lr = settings['pretrain_lr'] training_epochs = settings['training_epochs'] hidden_layers_sizes= settings['hidden_layers_sizes'] corruption_levels = settings['corruption_levels'] sda_transformed = trainSda(new_x_train_minmax_whole, y_train_minmax, new_x_validationt_minmax_whole, y_validation_minmax , new_x_test_minmax_whole, y_test, hidden_layers_sizes = hidden_layers_sizes, corruption_levels = corruption_levels, batch_size = batch_size , \ training_epochs = training_epochs, pretraining_epochs = pretraining_epochs, pretrain_lr = pretrain_lr, finetune_lr=finetune_lr ) print 'hidden_layers_sizes:', hidden_layers_sizes print 'corruption_levels:', corruption_levels training_predicted = sda_transformed.predict(new_x_train_minmax_whole) y_train = y_train_minmax isTest = False; #new analysis_scr.append((self.ddi, seq_no, fisher_mode, 'DL_S', isTest) + tuple(performance_score(y_train, training_predicted, predicted_score).values())) test_predicted = sda_transformed.predict(new_x_test_minmax_whole) y_test = test_y isTest = True; #new analysis_scr.append((self.ddi, seq_no, fisher_mode, 'DL_S', isTest) + tuple(performance_score(y_test, test_predicted, predicted_score).values())) report_name = filename + '_' + '_'.join(map(str, hidden_layers_sizes)) + '_' + str(pretrain_lr) + '_' + str(finetune_lr) + '_' + str(reduce_ratio)+ '_' +str(training_epochs) + '_' + current_date saveAsCsv(predicted_score, report_name, performance_score(y_test, test_predicted, predicted_score), analysis_scr) # In[29]: # In[30]: #for 10-fold cross validation def ten_fold_crossvalid_performance_for_all(ddis): for ddi in ddis: try: process_one_ddi_tenfold(ddi) except Exception,e: print str(e) logger.debug("There is a error in this ddi: %s" % ddi) logger.info(str(e)) def process_one_ddi_tenfold(ddi): """A function to waste CPU cycles""" logger.info('DDI: %s' % ddi) one_ddi_family = {} one_ddi_family[ddi] = Ten_fold_crossvalid_performance_for_one_ddi(ddi) one_ddi_family[ddi].get_ten_fold_crossvalid_perfermance(settings=settings) return None class Ten_fold_crossvalid_performance_for_one_ddi(object): """ get the performance of ddi families Attributes: ddi: string ddi name Vectors_Fishers_aaIndex_raw_folder: string, folder total_number_of_sequences: int raw_data: dict raw_data[2] """ def __init__(self, ddi): self.ddi_obj = DDI_family_base(ddi) self.ddi = ddi def get_ten_fold_crossvalid_perfermance(self, settings = None): fisher_mode = settings['fisher_mode'] analysis_scr = [] predicted_score = settings['predicted_score'] reduce_ratio = settings['reduce_ratio'] #for seq_no in range(1, self.ddi_obj.total_number_of_sequences+1): #subset_size = math.floor(self.ddi_obj.total_number_of_sequences / 10.0) kf = KFold(self.ddi_obj.total_number_of_sequences, n_folds = 10, shuffle = True) #for subset_no in range(1, 11): for ((train_index, test_index),subset_no) in izip(kf,range(1,11)): #for train_index, test_index in kf; print("Subset:", subset_no) print("Train index: ", train_index) print("Test index: ", test_index) #logger.info('subset number: ' + str(subset_no)) (train_X_10fold, train_y_10fold),(train_X_reduced, train_y_reduced), (test_X, test_y) = self.ddi_obj.get_ten_fold_crossvalid_one_subset(train_index, test_index, fisher_mode = fisher_mode, reduce_ratio = reduce_ratio) if settings['SVM']: print "SVM" standard_scaler = preprocessing.StandardScaler().fit(train_X_reduced) scaled_train_X = standard_scaler.transform(train_X_reduced) scaled_test_X = standard_scaler.transform(test_X) Linear_SVC = LinearSVC(C=1, penalty="l2") Linear_SVC.fit(scaled_train_X, train_y_reduced) predicted_test_y = Linear_SVC.predict(scaled_test_X) isTest = True; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'SVM', isTest) + tuple(performance_score(test_y, predicted_test_y).values())) #new predicted_train_y = Linear_SVC.predict(scaled_train_X) isTest = False; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'SVM', isTest) + tuple(performance_score(train_y_reduced, predicted_train_y).values())) if settings['SVM_RBF']: print "SVM_RBF" standard_scaler = preprocessing.StandardScaler().fit(train_X_reduced) scaled_train_X = standard_scaler.transform(train_X_reduced) scaled_test_X = standard_scaler.transform(test_X) L1_SVC_RBF_Selector = SVC(C=1, gamma=0.01, kernel='rbf').fit(scaled_train_X, train_y_reduced) predicted_test_y = L1_SVC_RBF_Selector.predict(scaled_test_X) isTest = True; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'SVM_RBF', isTest) + tuple(performance_score(test_y, predicted_test_y).values())) #new predicted_train_y = L1_SVC_RBF_Selector.predict(scaled_train_X) isTest = False; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'SVM_RBF', isTest) + tuple(performance_score(train_y_reduced, predicted_train_y).values())) if settings['SVM_POLY']: print "SVM_POLY" standard_scaler = preprocessing.StandardScaler().fit(train_X_reduced) scaled_train_X = standard_scaler.transform(train_X_reduced) scaled_test_X = standard_scaler.transform(test_X) L1_SVC_POLY_Selector = SVC(C=1, kernel='poly').fit(scaled_train_X, train_y_reduced) predicted_test_y = L1_SVC_POLY_Selector.predict(scaled_test_X) isTest = True; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'SVM_POLY', isTest) + tuple(performance_score(test_y, predicted_test_y).values())) #new predicted_train_y = L1_SVC_POLY_Selector.predict(scaled_train_X) isTest = False; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'SVM_POLY', isTest) + tuple(performance_score(train_y_reduced, predicted_train_y).values())) # direct deep learning min_max_scaler = Preprocessing_Scaler_with_mean_point5() X_train_pre_validation_minmax = min_max_scaler.fit(train_X_reduced) X_train_pre_validation_minmax = min_max_scaler.transform(train_X_reduced) x_test_minmax = min_max_scaler.transform(test_X) pretraining_X_minmax = min_max_scaler.transform(train_X_10fold) x_train_minmax, x_validation_minmax, y_train_minmax, y_validation_minmax = train_test_split(X_train_pre_validation_minmax, train_y_reduced , test_size=0.4, random_state=42) finetune_lr = settings['finetune_lr'] batch_size = settings['batch_size'] pretraining_epochs = cal_epochs(settings['pretraining_interations'], x_train_minmax, batch_size = batch_size) #pretrain_lr=0.001 pretrain_lr = settings['pretrain_lr'] training_epochs = settings['training_epochs'] hidden_layers_sizes= settings['hidden_layers_sizes'] corruption_levels = settings['corruption_levels'] if settings['SAE_SVM']: # SAE_SVM print 'SAE followed by SVM' x = X_train_pre_validation_minmax a_MAE_A = train_a_MultipleAEs(x, pretraining_epochs=pretraining_epochs, pretrain_lr=pretrain_lr, batch_size=batch_size, hidden_layers_sizes =hidden_layers_sizes, corruption_levels=corruption_levels) new_x_train_minmax_A = a_MAE_A.transform(X_train_pre_validation_minmax) new_x_test_minmax_A = a_MAE_A.transform(x_test_minmax) Linear_SVC = LinearSVC(C=1, penalty="l2") Linear_SVC.fit(new_x_train_minmax_A, train_y_reduced) predicted_test_y = Linear_SVC.predict(new_x_test_minmax_A) isTest = True; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'SAE_SVM', isTest) + tuple(performance_score(test_y, predicted_test_y).values())) #new predicted_train_y = Linear_SVC.predict(new_x_train_minmax_A) isTest = False; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'SAE_SVM', isTest) + tuple(performance_score(train_y_reduced, predicted_train_y).values())) if settings['DL']: print "direct deep learning" sda = trainSda(x_train_minmax, y_train_minmax, x_validation_minmax, y_validation_minmax , x_test_minmax, test_y, hidden_layers_sizes = hidden_layers_sizes, corruption_levels = corruption_levels, batch_size = batch_size , \ training_epochs = training_epochs, pretraining_epochs = pretraining_epochs, pretrain_lr = pretrain_lr, finetune_lr=finetune_lr ) print 'hidden_layers_sizes:', hidden_layers_sizes print 'corruption_levels:', corruption_levels training_predicted = sda.predict(x_train_minmax) y_train = y_train_minmax isTest = False; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'DL', isTest) + tuple(performance_score(y_train, training_predicted).values())) test_predicted = sda.predict(x_test_minmax) y_test = test_y isTest = True; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'DL', isTest) + tuple(performance_score(y_test, test_predicted).values())) if settings['DL_U']: # deep learning using unlabeled data for pretraining print 'deep learning with unlabel data' pretraining_epochs = cal_epochs(settings['pretraining_interations'], x_train_minmax, batch_size = batch_size) sda_unlabel = trainSda(x_train_minmax, y_train_minmax, x_validation_minmax, y_validation_minmax , x_test_minmax, test_y, pretraining_X_minmax = pretraining_X_minmax, hidden_layers_sizes = hidden_layers_sizes, corruption_levels = corruption_levels, batch_size = batch_size , \ training_epochs = training_epochs, pretraining_epochs = pretraining_epochs, pretrain_lr = pretrain_lr, finetune_lr=finetune_lr ) print 'hidden_layers_sizes:', hidden_layers_sizes print 'corruption_levels:', corruption_levels training_predicted = sda_unlabel.predict(x_train_minmax) y_train = y_train_minmax isTest = False; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'DL_U', isTest) + tuple(performance_score(y_train, training_predicted, predicted_score).values())) test_predicted = sda_unlabel.predict(x_test_minmax) y_test = test_y isTest = True; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'DL_U', isTest) + tuple(performance_score(y_test, test_predicted, predicted_score).values())) if settings['DL_S']: # deep learning using split network y_test = test_y print 'deep learning using split network' # get the new representation for A set. first 784-D pretraining_epochs = cal_epochs(settings['pretraining_interations'], x_train_minmax, batch_size = batch_size) x = x_train_minmax[:, :x_train_minmax.shape[1]/2] print "original shape for A", x.shape a_MAE_A = train_a_MultipleAEs(x, pretraining_epochs=pretraining_epochs, pretrain_lr=pretrain_lr, batch_size=batch_size, hidden_layers_sizes =hidden_layers_sizes, corruption_levels=corruption_levels) new_x_train_minmax_A = a_MAE_A.transform(x_train_minmax[:, :x_train_minmax.shape[1]/2]) x = x_train_minmax[:, x_train_minmax.shape[1]/2:] print "original shape for B", x.shape a_MAE_B = train_a_MultipleAEs(x, pretraining_epochs=pretraining_epochs, pretrain_lr=pretrain_lr, batch_size=batch_size, hidden_layers_sizes =hidden_layers_sizes, corruption_levels=corruption_levels) new_x_train_minmax_B = a_MAE_B.transform(x_train_minmax[:, x_train_minmax.shape[1]/2:]) new_x_test_minmax_A = a_MAE_A.transform(x_test_minmax[:, :x_test_minmax.shape[1]/2]) new_x_test_minmax_B = a_MAE_B.transform(x_test_minmax[:, x_test_minmax.shape[1]/2:]) new_x_validation_minmax_A = a_MAE_A.transform(x_validation_minmax[:, :x_validation_minmax.shape[1]/2]) new_x_validation_minmax_B = a_MAE_B.transform(x_validation_minmax[:, x_validation_minmax.shape[1]/2:]) new_x_train_minmax_whole = np.hstack((new_x_train_minmax_A, new_x_train_minmax_B)) new_x_test_minmax_whole = np.hstack((new_x_test_minmax_A, new_x_test_minmax_B)) new_x_validationt_minmax_whole = np.hstack((new_x_validation_minmax_A, new_x_validation_minmax_B)) sda_transformed = trainSda(new_x_train_minmax_whole, y_train_minmax, new_x_validationt_minmax_whole, y_validation_minmax , new_x_test_minmax_whole, y_test, hidden_layers_sizes = hidden_layers_sizes, corruption_levels = corruption_levels, batch_size = batch_size , \ training_epochs = training_epochs, pretraining_epochs = pretraining_epochs, pretrain_lr = pretrain_lr, finetune_lr=finetune_lr ) print 'hidden_layers_sizes:', hidden_layers_sizes print 'corruption_levels:', corruption_levels training_predicted = sda_transformed.predict(new_x_train_minmax_whole) y_train = y_train_minmax isTest = False; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'DL_S', isTest) + tuple(performance_score(y_train, training_predicted, predicted_score).values())) test_predicted = sda_transformed.predict(new_x_test_minmax_whole) y_test = test_y isTest = True; #new analysis_scr.append((self.ddi, subset_no, fisher_mode, 'DL_S', isTest) + tuple(performance_score(y_test, test_predicted, predicted_score).values())) report_name = filename + '_' + '_test10fold_'.join(map(str, hidden_layers_sizes)) + '_' + str(pretrain_lr) + '_' + str(finetune_lr) + '_' + str(reduce_ratio)+ '_' + str(training_epochs) + '_' + current_date saveAsCsv(predicted_score, report_name, performance_score(test_y, predicted_test_y, predicted_score), analysis_scr) # In[1]: ten_fold_crossvalid_performance_for_all(ddis[:]) # In[ ]: #LOO_out_performance_for_all(ddis) # In[25]: x = logging._handlers.copy() for i in x: log.removeHandler(i) i.flush() i.close() # In[ ]:
gpl-2.0
Seynen/egfrd
binding/disk_class.hpp
173
#ifndef BINDING_DISK_CLASS_HPP #define BINDING_DISK_CLASS_HPP namespace binding { void register_disk_class(); } // namespace binding #endif /* BINDING_DISK_CLASS_HPP */
gpl-2.0
bhirsch/voipdrupal-4.7-1.0
modules/contributions/civicrm/packages/JPSpan/js/util/typeof.js
3250
// $Id: typeof.js,v 1.1 2004/11/22 10:51:57 harryf Exp $ // Taken from http://www.webreference.com/dhtml/column68/ by Peter Belesis function JPSpan_Util_typeof( vExpression ) { var sTypeOf = typeof vExpression; if( sTypeOf == "function" ) { var sFunction = vExpression.toString(); if( ( /^\/.*\/$/ ).test( sFunction ) ) { return "regexp"; } else if( ( /^\[object.*\]$/i ).test( sFunction ) ) { sTypeOf = "object" } } if( sTypeOf != "object" ) { return sTypeOf; } switch( vExpression ) { case null: return "null"; case window: return "window"; case window.event: return "event"; } if( window.event && ( event.type == vExpression.type ) ) { return "event"; } var fConstructor = vExpression.constructor; if( fConstructor != null ) { switch( fConstructor ) { case Array: sTypeOf = "array"; break; case Date: return "date"; case RegExp: return "regexp"; case Object: sTypeOf = "jsobject"; break; case ReferenceError: return "error"; default: var sConstructor = fConstructor.toString(); var aMatch = sConstructor.match( /\s*function (.*)\(/ ); if( aMatch != null ) { return aMatch[ 1 ]; } } } var nNodeType = vExpression.nodeType; if( nNodeType != null ) { switch( nNodeType ) { case 1: if( vExpression.item == null ) { return "domelement"; } break; case 3: return "textnode"; } } if( vExpression.toString != null ) { var sExpression = vExpression.toString(); var aMatch = sExpression.match( /^\[object (.*)\]$/i ); if( aMatch != null ) { var sMatch = aMatch[ 1 ]; switch( sMatch.toLowerCase() ) { case "event": return "event"; case "math": return "math"; case "error": return "error"; case "mimetypearray": return "mimetypecollection"; case "pluginarray": return "plugincollection"; case "windowcollection": return "window"; case "nodelist": case "htmlcollection": case "elementarray": return "domcollection"; } } } if( vExpression.moveToBookmark && vExpression.moveToElementText ) { return "textrange"; } else if( vExpression.callee != null ) { return "arguments"; } else if( vExpression.item != null ) { return "domcollection"; } return sTypeOf; }
gpl-2.0
Tpo76/centreon
www/lib/HTML/QuickForm/input.php
5467
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Base class for <input /> form elements * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.01 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_01.txt If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category HTML * @package HTML_QuickForm * @author Adam Daniel <adaniel1@eesus.jnj.com> * @author Bertrand Mansion <bmansion@mamasam.com> * @copyright 2001-2011 The PHP Group * @license http://www.php.net/license/3_01.txt PHP License 3.01 * @version CVS: $Id$ * @link http://pear.php.net/package/HTML_QuickForm */ /** * Base class for form elements */ require_once 'HTML/QuickForm/element.php'; /** * Base class for <input /> form elements * * @category HTML * @package HTML_QuickForm * @author Adam Daniel <adaniel1@eesus.jnj.com> * @author Bertrand Mansion <bmansion@mamasam.com> * @version Release: 3.2.14 * @since 1.0 * @abstract */ class HTML_QuickForm_input extends HTML_QuickForm_element { // {{{ constructor /** * Class constructor * * @param string Input field name attribute * @param mixed Label(s) for the input field * @param mixed Either a typical HTML attribute string or an associative array * @since 1.0 * @access public * @return void */ function HTML_QuickForm_input($elementName=null, $elementLabel=null, $attributes=null) { $this->HTML_QuickForm_element($elementName, $elementLabel, $attributes); } //end constructor // }}} // {{{ setType() /** * Sets the element type * * @param string $type Element type * @since 1.0 * @access public * @return void */ function setType($type) { $this->_type = $type; $this->updateAttributes(array('type'=>$type)); } // end func setType // }}} // {{{ setName() /** * Sets the input field name * * @param string $name Input field name attribute * @since 1.0 * @access public * @return void */ function setName($name) { $this->updateAttributes(array('name'=>$name)); } //end func setName // }}} // {{{ getName() /** * Returns the element name * * @since 1.0 * @access public * @return string */ function getName() { return $this->getAttribute('name'); } //end func getName // }}} // {{{ setValue() /** * Sets the value of the form element * * @param string $value Default value of the form element * @since 1.0 * @access public * @return void */ function setValue($value) { $this->updateAttributes(array('value'=>$value)); } // end func setValue // }}} // {{{ getValue() /** * Returns the value of the form element * * @since 1.0 * @access public * @return string */ function getValue() { return $this->getAttribute('value'); } // end func getValue // }}} // {{{ toHtml() /** * Returns the input field in HTML * * @since 1.0 * @access public * @return string */ function toHtml() { if ($this->_flagFrozen) { return $this->getFrozenHtml(); } else { return $this->_getTabs() . '<input' . $this->_getAttrString($this->_attributes) . ' />'; } } //end func toHtml // }}} // {{{ onQuickFormEvent() /** * Called by HTML_QuickForm whenever form event is made on this element * * @param string $event Name of event * @param mixed $arg event arguments * @param object &$caller calling object * @since 1.0 * @access public * @return void * @throws */ function onQuickFormEvent($event, $arg, &$caller) { // do not use submit values for button-type elements $type = $this->getType(); if (('updateValue' != $event) || ('submit' != $type && 'reset' != $type && 'image' != $type && 'button' != $type)) { parent::onQuickFormEvent($event, $arg, $caller); } else { $value = $this->_findValue($caller->_constantValues); if (null === $value) { $value = $this->_findValue($caller->_defaultValues); } if (null !== $value) { $this->setValue($value); } } return true; } // end func onQuickFormEvent // }}} // {{{ exportValue() /** * We don't need values from button-type elements (except submit) and files */ function exportValue(&$submitValues, $assoc = false) { $type = $this->getType(); if ('reset' == $type || 'image' == $type || 'button' == $type || 'file' == $type) { return null; } else { return parent::exportValue($submitValues, $assoc); } } // }}} } // end class HTML_QuickForm_element ?>
gpl-2.0
chujieyang/ice
scripts/__init__.py
399
# ********************************************************************** # # Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** __all__ = [ "Expect", "IceGridAdmin", "IceStormUtil", "TestUtil"]
gpl-2.0
TeamOfMalaysia/X_discuz
public/discuz/source/plugin/qqconnect/connect/connect_config.php
5044
<?php /** * [Discuz!] (C)2001-2099 Comsenz Inc. * This is NOT a freeware, use is subject to license terms * * $Id: connect_config.php 33543 2013-07-03 06:01:33Z nemohou $ */ if(!defined('IN_DISCUZ')) { exit('Access Denied'); } if(empty($_G['uid'])) { showmessage('to_login', '', array(), array('showmsg' => true, 'login' => 1)); } $op = !empty($_GET['op']) ? $_GET['op'] : ''; $referer = dreferer(); if(submitcheck('connectsubmit')) { if($op == 'config') { // debug 修改QQ绑定设置 $ispublisht = !empty($_GET['ispublisht']) ? 1 : 0; C::t('#qqconnect#common_member_connect')->update($_G['uid'], array( 'conispublisht' => $ispublisht, ) ); if (!$ispublisht) { dsetcookie('connect_synpost_tip'); } showmessage('qqconnect:connect_config_success', $referer); } elseif($op == 'unbind') { $connect_member = C::t('#qqconnect#common_member_connect')->fetch($_G['uid']); $_G['member'] = array_merge($_G['member'], $connect_member); if ($connect_member['conuinsecret']) { if($_G['member']['conisregister']) { if($_G['setting']['strongpw']) { $strongpw_str = array(); if(in_array(1, $_G['setting']['strongpw']) && !preg_match("/\d+/", $_GET['newpassword1'])) { $strongpw_str[] = lang('member/template', 'strongpw_1'); } if(in_array(2, $_G['setting']['strongpw']) && !preg_match("/[a-z]+/", $_GET['newpassword1'])) { $strongpw_str[] = lang('member/template', 'strongpw_2'); } if(in_array(3, $_G['setting']['strongpw']) && !preg_match("/[A-Z]+/", $_GET['newpassword1'])) { $strongpw_str[] = lang('member/template', 'strongpw_3'); } if(in_array(4, $_G['setting']['strongpw']) && !preg_match("/[^a-zA-z0-9]+/", $_GET['newpassword1'])) { $strongpw_str[] = lang('member/template', 'strongpw_4'); } if($strongpw_str) { showmessage(lang('member/template', 'password_weak').implode(',', $strongpw_str)); } } if($_GET['newpassword1'] !== $_GET['newpassword2']) { showmessage('profile_passwd_notmatch', $referer); } if(!$_GET['newpassword1'] || $_GET['newpassword1'] != addslashes($_GET['newpassword1'])) { showmessage('profile_passwd_illegal', $referer); } } } else { // debug 因为老用户access token等信息,所以没法通知connect,所以直接在本地解绑就行了,不fopen connect if($_G['member']['conisregister']) { if($_GET['newpassword1'] !== $_GET['newpassword2']) { showmessage('profile_passwd_notmatch', $referer); } if(!$_GET['newpassword1'] || $_GET['newpassword1'] != addslashes($_GET['newpassword1'])) { showmessage('profile_passwd_illegal', $referer); } } } C::t('#qqconnect#common_member_connect')->delete($_G['uid']); C::t('common_member')->update($_G['uid'], array('conisbind' => 0)); C::t('#qqconnect#connect_memberbindlog')->insert( array( 'uid' => $_G['uid'], 'uin' => $_G['member']['conopenid'], 'type' => 2, 'dateline' => $_G['timestamp'], ) ); if($_G['member']['conisregister']) { loaducenter(); uc_user_edit(addslashes($_G['member']['username']), null, $_GET['newpassword1'], null, 1); } foreach($_G['cookie'] as $k => $v) { dsetcookie($k); } $_G['uid'] = $_G['adminid'] = 0; $_G['username'] = $_G['member']['password'] = ''; showmessage('qqconnect:connect_config_unbind_success', 'member.php?mod=logging&action=login'); } } else { if($_G[inajax] && $op == 'synconfig') { C::t('#qqconnect#common_member_connect')->update($_G['uid'], array( 'conispublisht' => 0, ) ); dsetcookie('connect_synpost_tip'); } elseif($op == 'weibosign') { if($_GET['hash'] != formhash()) { showmessage('submit_invalid'); } $connectService = Cloud::loadClass('Service_Connect'); $connectService->connectMergeMember(); if($_G['member']['conuin'] && $_G['member']['conuinsecret']) { $arr = array(); $arr['oauth_consumer_key'] = $_G['setting']['connectappid']; $arr['oauth_nonce'] = mt_rand(); $arr['oauth_timestamp'] = TIMESTAMP; $arr['oauth_signature_method'] = 'HMAC_SHA1'; $arr['oauth_token'] = $_G['member']['conuin']; ksort($arr); $arr['oauth_signature'] = $connectService->connectGetOauthSignature('http://api.discuz.qq.com/connect/getSignature', $arr, 'GET', $_G['member']['conuinsecret']); $arr['version'] = 'qzone1.0'; $utilService = Cloud::loadClass('Service_Util'); $result = $connectService->connectOutputPhp('http://api.discuz.qq.com/connect/getSignature?' . $utilService->httpBuildQuery($arr, '', '&')); if ($result['status'] == 0) { $connectService->connectAjaxOuputMessage('[wb=' . $result['result']['username'] . ']' . $result['result']['signature_url'] . '[/wb]', 0); } else { $connectService->connectAjaxOuputMessage('connect_wbsign_no_account', $result['status']); } } else { $connectService->connectAjaxOuputMessage('connect_wbsign_no_bind', -1); } } else { dheader('location: home.php?mod=spacecp&ac=plugin&id=qqconnect:spacecp'); } }
gpl-2.0
austinv11/PeripheralsPlusPlus
src/main/java/com/austinv11/peripheralsplusplus/tiles/containers/ContainerAnalyzer.java
2708
package com.austinv11.peripheralsplusplus.tiles.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class ContainerAnalyzer extends Container { private EntityPlayer player; private IInventory inv; private final int slotX = 80; private final int slotY = 34; public ContainerAnalyzer(EntityPlayer player, IInventory inv, int xSize, int ySize) { this.player = player; this.inv = inv; inv.openInventory(); layout(xSize,ySize); } protected void layout(int xSize, int ySize) { //for (int invRow = 0; invRow < inv.amountOfRows(); invRow++) { // for (int invCol = 0; invCol < inv.amountOfColumns(); invCol++) { //addSlotToContainer(inv, invCol+row*column, 12+invCol*18,8+invRow*18); // } //} addSlotToContainer(new Slot(inv,0,slotX,slotY)); int leftCol = (xSize - 162) / 2 + 1; for (int playerInvRow = 0; playerInvRow < 3; playerInvRow++) { for (int playerInvCol = 0; playerInvCol < 9; playerInvCol++) { addSlotToContainer(new Slot(player.inventory, playerInvCol + playerInvRow * 9 + 9, leftCol + playerInvCol * 18, ySize - (4 - playerInvRow) * 18 - 10)); } } for (int hotbarSlot = 0; hotbarSlot < 9; hotbarSlot++) { addSlotToContainer(new Slot(player.inventory, hotbarSlot, leftCol + hotbarSlot * 18, ySize - 24)); } } @Override public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_) { /*ItemStack itemstack = null; Slot slot = (Slot) inventorySlots.get(p_82846_2_); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (p_82846_2_ < inventorySlots.size()) { if (!mergeItemStack(itemstack1, 0, inventorySlots.size(), false)) { return null; } } else if (!mergeItemStack(itemstack1, 0, 1, true)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } } return itemstack;*/ ItemStack var2 = null; Slot var3 = (Slot)this.inventorySlots.get(p_82846_2_); if (var3 != null && var3.getHasStack()) { ItemStack var4 = var3.getStack(); var2 = var4.copy(); if (p_82846_2_ < 1) { if (!this.mergeItemStack(var4, 1, this.inventorySlots.size(), true)) { return null; } } else if (!this.mergeItemStack(var4, 0, 1, false)) return null; if (var4.stackSize == 0) var3.putStack((ItemStack)null); else var3.onSlotChanged(); } return var2; } @Override public boolean canInteractWith(EntityPlayer p_75145_1_) { return inv.isUseableByPlayer(p_75145_1_); } }
gpl-2.0
christopherstock/GC_Vital-Clean
_ASSETS/placeholder/placeholder2/js/preloader.js
917
/* //maximize screen & reset window var maxWidth = screen.availWidth; var maxHeight = screen.availHeight; window.moveTo(0,0); window.resizeTo(maxWidth,maxHeight); */ //preload all required images var myImage = new Array(); var myArray = new Array ( "images/spacer.gif" ); //the preloading-functionality function preload(i) { myImage[i] = new Image(); myImage[i].src = myArray[i]; window.status = 'Lade Bilder vor.. ' + parseInt(100*(i+1)/myArray.length) + ' % fertig (' + (i+1) + ' / ' + myArray.length + ')'; if (i+1 == myArray.length) { window.clearInterval( preloading ); window.status = 'Welcome to SR-Services - You one source'; } //endif } //endfunction i = -1; //launch the preloading-cycle frequently preloading = window.setInterval("i++, preload(i)", 10);
gpl-2.0
kolab-groupware/kdelibs
kdecore/network/ksocketfactory.cpp
5026
/* * This file is part of the KDE libraries * Copyright (C) 2007 Thiago Macieira <thiago@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "ksocketfactory.h" #include <QSslSocket> #include <QTcpSocket> #include <QTcpServer> #include <QUdpSocket> #include <QUrl> #include "klocalizedstring.h" #include <config-network.h> using namespace KSocketFactory; class _k_internal_QTcpSocketSetError: public QAbstractSocket { public: _k_internal_QTcpSocketSetError(); // not defined anywhere! using QAbstractSocket::setSocketError; using QAbstractSocket::setSocketState; using QAbstractSocket::setErrorString; }; static inline void setError(QAbstractSocket *socket, QAbstractSocket::SocketError error, const QString &errorString) { _k_internal_QTcpSocketSetError *hackSocket = static_cast<_k_internal_QTcpSocketSetError *>(socket); hackSocket->setSocketError(error); hackSocket->setErrorString(errorString); } void KSocketFactory::connectToHost(QTcpSocket *socket, const QString &protocol, const QString &host, quint16 port) { if (!socket) return; #ifndef QT_NO_NETWORKPROXY socket->setProxy(proxyForConnection(protocol, host)); #endif socket->connectToHost(host, port); } void KSocketFactory::connectToHost(QTcpSocket *socket, const QUrl &url) { connectToHost(socket, url.scheme(), url.host(), url.port()); } QTcpSocket *KSocketFactory::connectToHost(const QString &protocol, const QString &host, quint16 port, QObject *parent) { // ### TO-DO: find a way to determine if we should use QSslSocket or plain QTcpSocket QTcpSocket *socket = new QSslSocket(parent); connectToHost(socket, protocol, host, port); return socket; } QTcpSocket *KSocketFactory::connectToHost(const QUrl &url, QObject *parent) { return connectToHost(url.scheme(), url.host(), url.port(), parent); } void KSocketFactory::synchronousConnectToHost(QTcpSocket *socket, const QString &protocol, const QString &host, quint16 port, int msecs) { if (!socket) return; connectToHost(socket, protocol, host, port); if (!socket->waitForConnected(msecs)) setError(socket, QAbstractSocket::SocketTimeoutError, i18n("Timed out trying to connect to remote host")); } void KSocketFactory::synchronousConnectToHost(QTcpSocket *socket, const QUrl &url, int msecs) { synchronousConnectToHost(socket, url.scheme(), url.host(), url.port(), msecs); } QTcpSocket *KSocketFactory::synchronousConnectToHost(const QString &protocol, const QString &host, quint16 port, int msecs, QObject *parent) { QTcpSocket *socket = connectToHost(protocol, host, port, parent); if (!socket->waitForConnected(msecs)) setError(socket, QAbstractSocket::SocketTimeoutError, i18n("Timed out trying to connect to remote host")); return socket; } QTcpSocket *KSocketFactory::synchronousConnectToHost(const QUrl &url, int msecs, QObject *parent) { return synchronousConnectToHost(url.scheme(), url.host(), url.port(), msecs, parent); } QTcpServer *KSocketFactory::listen(const QString &protocol, const QHostAddress &address, quint16 port, QObject *parent) { QTcpServer *server = new QTcpServer(parent); #ifndef QT_NO_NETWORKPROXY server->setProxy(proxyForListening(protocol)); #endif server->listen(address, port); return server; } QUdpSocket *KSocketFactory::datagramSocket(const QString &protocol, const QString &host, QObject *parent) { QUdpSocket *socket = new QUdpSocket(parent); #ifndef QT_NO_NETWORKPROXY // ### do something else? socket->setProxy(proxyForDatagram(protocol, host)); #endif return socket; } #ifndef QT_NO_NETWORKPROXY QNetworkProxy KSocketFactory::proxyForConnection(const QString &, const QString &) { return QNetworkProxy::DefaultProxy; } QNetworkProxy KSocketFactory::proxyForListening(const QString &) { return QNetworkProxy::DefaultProxy; } QNetworkProxy KSocketFactory::proxyForDatagram(const QString &, const QString &) { return QNetworkProxy::DefaultProxy; } #endif
gpl-2.0
plx9421/JavaRushHomeWork
javarush/test/level22/lesson18/big01/Figure.java
3704
package com.javarush.test.level22.lesson18.big01; /** * Класс Figure описывает фигурку тетриса */ public class Figure { //метрица которая определяет форму фигурки: 1 - клетка не пустая, 0 - пустая private int[][] matrix; //координаты private int x; private int y; public Figure(int x, int y, int[][] matrix) { this.x = x; this.y = y; this.matrix = matrix; } public int getX() { return x; } public int getY() { return y; } public int[][] getMatrix() { return matrix; } /** * Поворачаиваем фигурку. * Для простоты - просто вокруг главной диагонали. */ public void rotate() { int[][] matrix2 = new int[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { matrix2[i][j] = matrix[j][i]; } } matrix = matrix2; } /** * Двигаем фигурку влево. * Проверяем не вылезла ли она за границу поля и/или не залезла ли на занятые клетки. */ public void left() { x--; if (!isCurrentPositionAvailable()) x++; } /** * Двигаем фигурку вправо. * Проверяем не вылезла ли она за границу поля и/или не залезла ли на занятые клетки. */ public void right() { x++; if (!isCurrentPositionAvailable()) x--; } /** * Двигаем фигурку вверх. * Используется, если фигурка залезла на занятые клетки. */ public void up() { y--; } /** * Двигаем фигурку вниз. */ public void down() { y++; } /** * Двигаем фигурку вниз до тех пор, пока не залезем на кого-нибудь. */ public void downMaximum() { while (isCurrentPositionAvailable()) { y++; } y--; } /** * Проверяем - может ли фигурка находится на текущей позици: * а) не вылазиет ли она за границы поля * б) не залазиет ли она на занятые клетки */ public boolean isCurrentPositionAvailable() { Field field = Tetris.game.getField(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (matrix[i][j] == 1) { if (y + i >= field.getHeight()) return false; Integer value = field.getValue(x + j, y + i); if (value == null || value == 1) return false; } } } return true; } /** * Приземляем фигурку - добавляем все ее непустые клетки к клеткам поля. */ public void landed() { Field field = Tetris.game.getField(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (matrix[i][j] == 1) field.setValue(x + j, y + i, 1); } } } }
gpl-2.0
MajorCaiger/MiscBlog
wp-includes/script-loader.php
54405
<?php /** * WordPress scripts and styles default loader. * * Most of the functionality that existed here was moved to * {@link http://backpress.automattic.com/ BackPress}. WordPress themes and * plugins will only be concerned about the filters and actions set in this * file. * * Several constants are used to manage the loading, concatenating and compression of scripts and CSS: * define('SCRIPT_DEBUG', true); loads the development (non-minified) versions of all scripts and CSS, and disables compression and concatenation, * define('CONCATENATE_SCRIPTS', false); disables compression and concatenation of scripts and CSS, * define('COMPRESS_SCRIPTS', false); disables compression of scripts, * define('COMPRESS_CSS', false); disables compression of CSS, * define('ENFORCE_GZIP', true); forces gzip for compression (default is deflate). * * The globals $concatenate_scripts, $compress_scripts and $compress_css can be set by plugins * to temporarily override the above settings. Also a compression test is run once and the result is saved * as option 'can_compress_scripts' (0/1). The test will run again if that option is deleted. * * @package WordPress */ /** BackPress: WordPress Dependencies Class */ require( ABSPATH . WPINC . '/class.wp-dependencies.php' ); /** BackPress: WordPress Scripts Class */ require( ABSPATH . WPINC . '/class.wp-scripts.php' ); /** BackPress: WordPress Scripts Functions */ require( ABSPATH . WPINC . '/functions.wp-scripts.php' ); /** BackPress: WordPress Styles Class */ require( ABSPATH . WPINC . '/class.wp-styles.php' ); /** BackPress: WordPress Styles Functions */ require( ABSPATH . WPINC . '/functions.wp-styles.php' ); /** * Register all WordPress scripts. * * Localizes some of them. * args order: $scripts->add( 'handle', 'url', 'dependencies', 'query-string', 1 ); * when last arg === 1 queues the script for the footer * * @since 2.6.0 * * @param WP_Scripts $scripts WP_Scripts object. */ function wp_default_scripts( &$scripts ) { include( ABSPATH . WPINC . '/version.php' ); // include an unmodified $wp_version $develop_src = false !== strpos( $wp_version, '-src' ); if ( ! defined( 'SCRIPT_DEBUG' ) ) { define( 'SCRIPT_DEBUG', $develop_src ); } if ( ! $guessurl = site_url() ) { $guessed_url = true; $guessurl = wp_guess_url(); } $scripts->base_url = $guessurl; $scripts->content_url = defined('WP_CONTENT_URL')? WP_CONTENT_URL : ''; $scripts->default_version = get_bloginfo( 'version' ); $scripts->default_dirs = array('/wp-admin/js/', '/wp-includes/js/'); $suffix = SCRIPT_DEBUG ? '' : '.min'; $dev_suffix = $develop_src ? '' : '.min'; $scripts->add( 'utils', "/wp-includes/js/utils$suffix.js" ); did_action( 'init' ) && $scripts->localize( 'utils', 'userSettings', array( 'url' => (string) SITECOOKIEPATH, 'uid' => (string) get_current_user_id(), 'time' => (string) time(), 'secure' => (string) ( 'https' === parse_url( site_url(), PHP_URL_SCHEME ) ), ) ); $scripts->add( 'common', "/wp-admin/js/common$suffix.js", array('jquery', 'hoverIntent', 'utils', 'list-table'), false, 1 ); did_action( 'init' ) && $scripts->localize( 'common', 'commonL10n', array( 'warnDelete' => __( "You are about to permanently delete the selected items.\n 'Cancel' to stop, 'OK' to delete." ), 'dismiss' => __( 'Dismiss this notice.' ), ) ); $scripts->add( 'wp-a11y', "/wp-includes/js/wp-a11y$suffix.js", array( 'jquery' ), false, 1 ); $scripts->add( 'sack', "/wp-includes/js/tw-sack$suffix.js", array(), '1.6.1', 1 ); $scripts->add( 'quicktags', "/wp-includes/js/quicktags$suffix.js", array(), false, 1 ); did_action( 'init' ) && $scripts->localize( 'quicktags', 'quicktagsL10n', array( 'closeAllOpenTags' => __( 'Close all open tags' ), 'closeTags' => __( 'close tags' ), 'enterURL' => __( 'Enter the URL' ), 'enterImageURL' => __( 'Enter the URL of the image' ), 'enterImageDescription' => __( 'Enter a description of the image' ), 'textdirection' => __( 'text direction' ), 'toggleTextdirection' => __( 'Toggle Editor Text Direction' ), 'dfw' => __( 'Distraction-free writing mode' ), 'strong' => __( 'Bold' ), 'strongClose' => __( 'Close bold tag' ), 'em' => __( 'Italic' ), 'emClose' => __( 'Close italic tag' ), 'link' => __( 'Insert link' ), 'blockquote' => __( 'Blockquote' ), 'blockquoteClose' => __( 'Close blockquote tag' ), 'del' => __( 'Deleted text (strikethrough)' ), 'delClose' => __( 'Close deleted text tag' ), 'ins' => __( 'Inserted text' ), 'insClose' => __( 'Close inserted text tag' ), 'image' => __( 'Insert image' ), 'ul' => __( 'Bulleted list' ), 'ulClose' => __( 'Close bulleted list tag' ), 'ol' => __( 'Numbered list' ), 'olClose' => __( 'Close numbered list tag' ), 'li' => __( 'List item' ), 'liClose' => __( 'Close list item tag' ), 'code' => __( 'Code' ), 'codeClose' => __( 'Close code tag' ), 'more' => __( 'Insert Read More tag' ), ) ); $scripts->add( 'colorpicker', "/wp-includes/js/colorpicker$suffix.js", array('prototype'), '3517m' ); $scripts->add( 'editor', "/wp-admin/js/editor$suffix.js", array('utils','jquery'), false, 1 ); // Back-compat for old DFW. To-do: remove at the end of 2016. $scripts->add( 'wp-fullscreen-stub', "/wp-admin/js/wp-fullscreen-stub$suffix.js", array(), false, 1 ); $scripts->add( 'wp-ajax-response', "/wp-includes/js/wp-ajax-response$suffix.js", array('jquery'), false, 1 ); did_action( 'init' ) && $scripts->localize( 'wp-ajax-response', 'wpAjax', array( 'noPerm' => __('You do not have permission to do that.'), 'broken' => __('An unidentified error has occurred.') ) ); $scripts->add( 'wp-pointer', "/wp-includes/js/wp-pointer$suffix.js", array( 'jquery-ui-widget', 'jquery-ui-position' ), '20111129a', 1 ); did_action( 'init' ) && $scripts->localize( 'wp-pointer', 'wpPointerL10n', array( 'dismiss' => __('Dismiss'), ) ); $scripts->add( 'autosave', "/wp-includes/js/autosave$suffix.js", array('heartbeat'), false, 1 ); $scripts->add( 'heartbeat', "/wp-includes/js/heartbeat$suffix.js", array('jquery'), false, 1 ); did_action( 'init' ) && $scripts->localize( 'heartbeat', 'heartbeatSettings', /** * Filter the Heartbeat settings. * * @since 3.6.0 * * @param array $settings Heartbeat settings array. */ apply_filters( 'heartbeat_settings', array() ) ); $scripts->add( 'wp-auth-check', "/wp-includes/js/wp-auth-check$suffix.js", array('heartbeat'), false, 1 ); did_action( 'init' ) && $scripts->localize( 'wp-auth-check', 'authcheckL10n', array( 'beforeunload' => __('Your session has expired. You can log in again from this page or go to the login page.'), /** * Filter the authentication check interval. * * @since 3.6.0 * * @param int $interval The interval in which to check a user's authentication. * Default 3 minutes in seconds, or 180. */ 'interval' => apply_filters( 'wp_auth_check_interval', 3 * MINUTE_IN_SECONDS ), ) ); $scripts->add( 'wp-lists', "/wp-includes/js/wp-lists$suffix.js", array( 'wp-ajax-response', 'jquery-color' ), false, 1 ); // WordPress no longer uses or bundles Prototype or script.aculo.us. These are now pulled from an external source. $scripts->add( 'prototype', 'https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js', array(), '1.7.1'); $scripts->add( 'scriptaculous-root', 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js', array('prototype'), '1.9.0'); $scripts->add( 'scriptaculous-builder', 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/builder.js', array('scriptaculous-root'), '1.9.0'); $scripts->add( 'scriptaculous-dragdrop', 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/dragdrop.js', array('scriptaculous-builder', 'scriptaculous-effects'), '1.9.0'); $scripts->add( 'scriptaculous-effects', 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/effects.js', array('scriptaculous-root'), '1.9.0'); $scripts->add( 'scriptaculous-slider', 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/slider.js', array('scriptaculous-effects'), '1.9.0'); $scripts->add( 'scriptaculous-sound', 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/sound.js', array( 'scriptaculous-root' ), '1.9.0' ); $scripts->add( 'scriptaculous-controls', 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/controls.js', array('scriptaculous-root'), '1.9.0'); $scripts->add( 'scriptaculous', false, array('scriptaculous-dragdrop', 'scriptaculous-slider', 'scriptaculous-controls') ); // not used in core, replaced by Jcrop.js $scripts->add( 'cropper', '/wp-includes/js/crop/cropper.js', array('scriptaculous-dragdrop') ); // jQuery $scripts->add( 'jquery', false, array( 'jquery-core', 'jquery-migrate' ), '1.11.3' ); $scripts->add( 'jquery-core', '/wp-includes/js/jquery/jquery.js', array(), '1.11.3' ); $scripts->add( 'jquery-migrate', "/wp-includes/js/jquery/jquery-migrate$suffix.js", array(), '1.2.1' ); // full jQuery UI $scripts->add( 'jquery-ui-core', "/wp-includes/js/jquery/ui/core$dev_suffix.js", array('jquery'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-core', "/wp-includes/js/jquery/ui/effect$dev_suffix.js", array('jquery'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-blind', "/wp-includes/js/jquery/ui/effect-blind$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-bounce', "/wp-includes/js/jquery/ui/effect-bounce$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-clip', "/wp-includes/js/jquery/ui/effect-clip$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-drop', "/wp-includes/js/jquery/ui/effect-drop$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-explode', "/wp-includes/js/jquery/ui/effect-explode$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-fade', "/wp-includes/js/jquery/ui/effect-fade$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-fold', "/wp-includes/js/jquery/ui/effect-fold$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-highlight', "/wp-includes/js/jquery/ui/effect-highlight$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-puff', "/wp-includes/js/jquery/ui/effect-puff$dev_suffix.js", array('jquery-effects-core', 'jquery-effects-scale'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-pulsate', "/wp-includes/js/jquery/ui/effect-pulsate$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-scale', "/wp-includes/js/jquery/ui/effect-scale$dev_suffix.js", array('jquery-effects-core', 'jquery-effects-size'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-shake', "/wp-includes/js/jquery/ui/effect-shake$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-size', "/wp-includes/js/jquery/ui/effect-size$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-slide', "/wp-includes/js/jquery/ui/effect-slide$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-effects-transfer', "/wp-includes/js/jquery/ui/effect-transfer$dev_suffix.js", array('jquery-effects-core'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-accordion', "/wp-includes/js/jquery/ui/accordion$dev_suffix.js", array('jquery-ui-core', 'jquery-ui-widget'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-autocomplete', "/wp-includes/js/jquery/ui/autocomplete$dev_suffix.js", array('jquery-ui-menu'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-button', "/wp-includes/js/jquery/ui/button$dev_suffix.js", array('jquery-ui-core', 'jquery-ui-widget'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-datepicker', "/wp-includes/js/jquery/ui/datepicker$dev_suffix.js", array('jquery-ui-core'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-dialog', "/wp-includes/js/jquery/ui/dialog$dev_suffix.js", array('jquery-ui-resizable', 'jquery-ui-draggable', 'jquery-ui-button', 'jquery-ui-position'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-draggable', "/wp-includes/js/jquery/ui/draggable$dev_suffix.js", array('jquery-ui-mouse'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-droppable', "/wp-includes/js/jquery/ui/droppable$dev_suffix.js", array('jquery-ui-draggable'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-menu', "/wp-includes/js/jquery/ui/menu$dev_suffix.js", array( 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-position' ), '1.11.4', 1 ); $scripts->add( 'jquery-ui-mouse', "/wp-includes/js/jquery/ui/mouse$dev_suffix.js", array( 'jquery-ui-core', 'jquery-ui-widget' ), '1.11.4', 1 ); $scripts->add( 'jquery-ui-position', "/wp-includes/js/jquery/ui/position$dev_suffix.js", array('jquery'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-progressbar', "/wp-includes/js/jquery/ui/progressbar$dev_suffix.js", array('jquery-ui-core', 'jquery-ui-widget'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-resizable', "/wp-includes/js/jquery/ui/resizable$dev_suffix.js", array('jquery-ui-mouse'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-selectable', "/wp-includes/js/jquery/ui/selectable$dev_suffix.js", array('jquery-ui-mouse'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-selectmenu', "/wp-includes/js/jquery/ui/selectmenu$dev_suffix.js", array('jquery-ui-menu'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-slider', "/wp-includes/js/jquery/ui/slider$dev_suffix.js", array('jquery-ui-mouse'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-sortable', "/wp-includes/js/jquery/ui/sortable$dev_suffix.js", array('jquery-ui-mouse'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-spinner', "/wp-includes/js/jquery/ui/spinner$dev_suffix.js", array( 'jquery-ui-button' ), '1.11.4', 1 ); $scripts->add( 'jquery-ui-tabs', "/wp-includes/js/jquery/ui/tabs$dev_suffix.js", array('jquery-ui-core', 'jquery-ui-widget'), '1.11.4', 1 ); $scripts->add( 'jquery-ui-tooltip', "/wp-includes/js/jquery/ui/tooltip$dev_suffix.js", array( 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-position' ), '1.11.4', 1 ); $scripts->add( 'jquery-ui-widget', "/wp-includes/js/jquery/ui/widget$dev_suffix.js", array('jquery'), '1.11.4', 1 ); // deprecated, not used in core, most functionality is included in jQuery 1.3 $scripts->add( 'jquery-form', "/wp-includes/js/jquery/jquery.form$suffix.js", array('jquery'), '3.37.0', 1 ); // jQuery plugins $scripts->add( 'jquery-color', "/wp-includes/js/jquery/jquery.color.min.js", array('jquery'), '2.1.1', 1 ); $scripts->add( 'suggest', "/wp-includes/js/jquery/suggest$suffix.js", array('jquery'), '1.1-20110113', 1 ); $scripts->add( 'schedule', '/wp-includes/js/jquery/jquery.schedule.js', array('jquery'), '20m', 1 ); $scripts->add( 'jquery-query', "/wp-includes/js/jquery/jquery.query.js", array('jquery'), '2.1.7', 1 ); $scripts->add( 'jquery-serialize-object', "/wp-includes/js/jquery/jquery.serialize-object.js", array('jquery'), '0.2', 1 ); $scripts->add( 'jquery-hotkeys', "/wp-includes/js/jquery/jquery.hotkeys$suffix.js", array('jquery'), '0.0.2m', 1 ); $scripts->add( 'jquery-table-hotkeys', "/wp-includes/js/jquery/jquery.table-hotkeys$suffix.js", array('jquery', 'jquery-hotkeys'), false, 1 ); $scripts->add( 'jquery-touch-punch', "/wp-includes/js/jquery/jquery.ui.touch-punch.js", array('jquery-ui-widget', 'jquery-ui-mouse'), '0.2.2', 1 ); // Masonry v2 depended on jQuery. v3 does not. The older jquery-masonry handle is a shiv. // It sets jQuery as a dependency, as the theme may have been implicitly loading it this way. $scripts->add( 'masonry', "/wp-includes/js/masonry.min.js", array(), '3.1.2', 1 ); $scripts->add( 'jquery-masonry', "/wp-includes/js/jquery/jquery.masonry$dev_suffix.js", array( 'jquery', 'masonry' ), '3.1.2', 1 ); $scripts->add( 'thickbox', "/wp-includes/js/thickbox/thickbox.js", array('jquery'), '3.1-20121105', 1 ); did_action( 'init' ) && $scripts->localize( 'thickbox', 'thickboxL10n', array( 'next' => __('Next &gt;'), 'prev' => __('&lt; Prev'), 'image' => __('Image'), 'of' => __('of'), 'close' => __('Close'), 'noiframes' => __('This feature requires inline frames. You have iframes disabled or your browser does not support them.'), 'loadingAnimation' => includes_url('js/thickbox/loadingAnimation.gif'), ) ); $scripts->add( 'jcrop', "/wp-includes/js/jcrop/jquery.Jcrop.min.js", array('jquery'), '0.9.12'); $scripts->add( 'swfobject', "/wp-includes/js/swfobject.js", array(), '2.2-20120417'); // error message for both plupload and swfupload $uploader_l10n = array( 'queue_limit_exceeded' => __('You have attempted to queue too many files.'), 'file_exceeds_size_limit' => __('%s exceeds the maximum upload size for this site.'), 'zero_byte_file' => __('This file is empty. Please try another.'), 'invalid_filetype' => __('This file type is not allowed. Please try another.'), 'not_an_image' => __('This file is not an image. Please try another.'), 'image_memory_exceeded' => __('Memory exceeded. Please try another smaller file.'), 'image_dimensions_exceeded' => __('This is larger than the maximum size. Please try another.'), 'default_error' => __('An error occurred in the upload. Please try again later.'), 'missing_upload_url' => __('There was a configuration error. Please contact the server administrator.'), 'upload_limit_exceeded' => __('You may only upload 1 file.'), 'http_error' => __('HTTP error.'), 'upload_failed' => __('Upload failed.'), 'big_upload_failed' => __('Please try uploading this file with the %1$sbrowser uploader%2$s.'), 'big_upload_queued' => __('%s exceeds the maximum upload size for the multi-file uploader when used in your browser.'), 'io_error' => __('IO error.'), 'security_error' => __('Security error.'), 'file_cancelled' => __('File canceled.'), 'upload_stopped' => __('Upload stopped.'), 'dismiss' => __('Dismiss'), 'crunching' => __('Crunching&hellip;'), 'deleted' => __('moved to the trash.'), 'error_uploading' => __('&#8220;%s&#8221; has failed to upload.') ); $scripts->add( 'plupload', '/wp-includes/js/plupload/plupload.full.min.js', array(), '2.1.8' ); // Back compat handles: foreach ( array( 'all', 'html5', 'flash', 'silverlight', 'html4' ) as $handle ) { $scripts->add( "plupload-$handle", false, array( 'plupload' ), '2.1.1' ); } $scripts->add( 'plupload-handlers', "/wp-includes/js/plupload/handlers$suffix.js", array( 'plupload', 'jquery' ) ); did_action( 'init' ) && $scripts->localize( 'plupload-handlers', 'pluploadL10n', $uploader_l10n ); $scripts->add( 'wp-plupload', "/wp-includes/js/plupload/wp-plupload$suffix.js", array( 'plupload', 'jquery', 'json2', 'media-models' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'wp-plupload', 'pluploadL10n', $uploader_l10n ); // keep 'swfupload' for back-compat. $scripts->add( 'swfupload', '/wp-includes/js/swfupload/swfupload.js', array(), '2201-20110113'); $scripts->add( 'swfupload-swfobject', '/wp-includes/js/swfupload/plugins/swfupload.swfobject.js', array('swfupload', 'swfobject'), '2201a'); $scripts->add( 'swfupload-queue', '/wp-includes/js/swfupload/plugins/swfupload.queue.js', array('swfupload'), '2201'); $scripts->add( 'swfupload-speed', '/wp-includes/js/swfupload/plugins/swfupload.speed.js', array('swfupload'), '2201'); $scripts->add( 'swfupload-all', false, array('swfupload', 'swfupload-swfobject', 'swfupload-queue'), '2201'); $scripts->add( 'swfupload-handlers', "/wp-includes/js/swfupload/handlers$suffix.js", array('swfupload-all', 'jquery'), '2201-20110524'); did_action( 'init' ) && $scripts->localize( 'swfupload-handlers', 'swfuploadL10n', $uploader_l10n ); $scripts->add( 'comment-reply', "/wp-includes/js/comment-reply$suffix.js", array(), false, 1 ); $scripts->add( 'json2', "/wp-includes/js/json2$suffix.js", array(), '2015-05-03' ); did_action( 'init' ) && $scripts->add_data( 'json2', 'conditional', 'lt IE 8' ); $scripts->add( 'underscore', "/wp-includes/js/underscore$dev_suffix.js", array(), '1.6.0', 1 ); $scripts->add( 'backbone', "/wp-includes/js/backbone$dev_suffix.js", array( 'underscore','jquery' ), '1.1.2', 1 ); $scripts->add( 'wp-util', "/wp-includes/js/wp-util$suffix.js", array('underscore', 'jquery'), false, 1 ); did_action( 'init' ) && $scripts->localize( 'wp-util', '_wpUtilSettings', array( 'ajax' => array( 'url' => admin_url( 'admin-ajax.php', 'relative' ), ), ) ); $scripts->add( 'wp-backbone', "/wp-includes/js/wp-backbone$suffix.js", array('backbone', 'wp-util'), false, 1 ); $scripts->add( 'revisions', "/wp-admin/js/revisions$suffix.js", array( 'wp-backbone', 'jquery-ui-slider', 'hoverIntent' ), false, 1 ); $scripts->add( 'imgareaselect', "/wp-includes/js/imgareaselect/jquery.imgareaselect$suffix.js", array('jquery'), false, 1 ); $scripts->add( 'mediaelement', "/wp-includes/js/mediaelement/mediaelement-and-player.min.js", array('jquery'), '2.17.0', 1 ); did_action( 'init' ) && $scripts->localize( 'mediaelement', 'mejsL10n', array( 'language' => get_bloginfo( 'language' ), 'strings' => array( 'Close' => __( 'Close' ), 'Fullscreen' => __( 'Fullscreen' ), 'Download File' => __( 'Download File' ), 'Download Video' => __( 'Download Video' ), 'Play/Pause' => __( 'Play/Pause' ), 'Mute Toggle' => __( 'Mute Toggle' ), 'None' => __( 'None' ), 'Turn off Fullscreen' => __( 'Turn off Fullscreen' ), 'Go Fullscreen' => __( 'Go Fullscreen' ), 'Unmute' => __( 'Unmute' ), 'Mute' => __( 'Mute' ), 'Captions/Subtitles' => __( 'Captions/Subtitles' ) ), ) ); $scripts->add( 'wp-mediaelement', "/wp-includes/js/mediaelement/wp-mediaelement.js", array('mediaelement'), false, 1 ); $mejs_settings = array( 'pluginPath' => includes_url( 'js/mediaelement/', 'relative' ), ); did_action( 'init' ) && $scripts->localize( 'mediaelement', '_wpmejsSettings', /** * Filter the MediaElement configuration settings. * * @since 4.4.0 * * @param array $mejs_settings MediaElement settings array. */ apply_filters( 'mejs_settings', $mejs_settings ) ); $scripts->add( 'froogaloop', "/wp-includes/js/mediaelement/froogaloop.min.js", array(), '2.0' ); $scripts->add( 'wp-playlist', "/wp-includes/js/mediaelement/wp-playlist.js", array( 'wp-util', 'backbone', 'mediaelement' ), false, 1 ); $scripts->add( 'zxcvbn-async', "/wp-includes/js/zxcvbn-async$suffix.js", array(), '1.0' ); did_action( 'init' ) && $scripts->localize( 'zxcvbn-async', '_zxcvbnSettings', array( 'src' => empty( $guessed_url ) ? includes_url( '/js/zxcvbn.min.js' ) : $scripts->base_url . '/wp-includes/js/zxcvbn.min.js', ) ); $scripts->add( 'password-strength-meter', "/wp-admin/js/password-strength-meter$suffix.js", array( 'jquery', 'zxcvbn-async' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'password-strength-meter', 'pwsL10n', array( 'short' => _x( 'Very weak', 'password strength' ), 'bad' => _x( 'Weak', 'password strength' ), 'good' => _x( 'Medium', 'password strength' ), 'strong' => _x( 'Strong', 'password strength' ), 'mismatch' => _x( 'Mismatch', 'password mismatch' ), ) ); $scripts->add( 'user-profile', "/wp-admin/js/user-profile$suffix.js", array( 'jquery', 'password-strength-meter', 'wp-util' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'user-profile', 'userProfileL10n', array( 'warn' => __( 'Your new password has not been saved.' ), 'show' => __( 'Show' ), 'hide' => __( 'Hide' ), 'cancel' => __( 'Cancel' ), 'ariaShow' => esc_attr__( 'Show password' ), 'ariaHide' => esc_attr__( 'Hide password' ), ) ); $scripts->add( 'language-chooser', "/wp-admin/js/language-chooser$suffix.js", array( 'jquery' ), false, 1 ); $scripts->add( 'user-suggest', "/wp-admin/js/user-suggest$suffix.js", array( 'jquery-ui-autocomplete' ), false, 1 ); $scripts->add( 'list-table', "/wp-admin/js/list-table$suffix.js", array( 'jquery' ), false, 1 ); $scripts->add( 'admin-bar', "/wp-includes/js/admin-bar$suffix.js", array(), false, 1 ); $scripts->add( 'wplink', "/wp-includes/js/wplink$suffix.js", array( 'jquery' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'wplink', 'wpLinkL10n', array( 'title' => __('Insert/edit link'), 'update' => __('Update'), 'save' => __('Add Link'), 'noTitle' => __('(no title)'), 'noMatchesFound' => __('No results found.') ) ); $scripts->add( 'wpdialogs', "/wp-includes/js/wpdialog$suffix.js", array( 'jquery-ui-dialog' ), false, 1 ); $scripts->add( 'word-count', "/wp-admin/js/word-count$suffix.js", array(), false, 1 ); did_action( 'init' ) && $scripts->localize( 'word-count', 'wordCountL10n', array( /* * translators: If your word count is based on single characters (e.g. East Asian characters), * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'. * Do not translate into your own language. */ 'type' => _x( 'words', 'Word count type. Do not translate!' ), 'shortcodes' => ! empty( $GLOBALS['shortcode_tags'] ) ? array_keys( $GLOBALS['shortcode_tags'] ) : array() ) ); $scripts->add( 'media-upload', "/wp-admin/js/media-upload$suffix.js", array( 'thickbox', 'shortcode' ), false, 1 ); $scripts->add( 'hoverIntent', "/wp-includes/js/hoverIntent$suffix.js", array('jquery'), '1.8.1', 1 ); $scripts->add( 'customize-base', "/wp-includes/js/customize-base$suffix.js", array( 'jquery', 'json2', 'underscore' ), false, 1 ); $scripts->add( 'customize-loader', "/wp-includes/js/customize-loader$suffix.js", array( 'customize-base' ), false, 1 ); $scripts->add( 'customize-preview', "/wp-includes/js/customize-preview$suffix.js", array( 'customize-base' ), false, 1 ); $scripts->add( 'customize-models', "/wp-includes/js/customize-models.js", array( 'underscore', 'backbone' ), false, 1 ); $scripts->add( 'customize-views', "/wp-includes/js/customize-views.js", array( 'jquery', 'underscore', 'imgareaselect', 'customize-models', 'media-editor', 'media-views' ), false, 1 ); $scripts->add( 'customize-controls', "/wp-admin/js/customize-controls$suffix.js", array( 'customize-base', 'wp-a11y' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'customize-controls', '_wpCustomizeControlsL10n', array( 'activate' => __( 'Save &amp; Activate' ), 'save' => __( 'Save &amp; Publish' ), 'saveAlert' => __( 'The changes you made will be lost if you navigate away from this page.' ), 'saved' => __( 'Saved' ), 'cancel' => __( 'Cancel' ), 'close' => __( 'Close' ), 'cheatin' => __( 'Cheatin&#8217; uh?' ), 'notAllowed' => __( 'You are not allowed to customize the appearance of this site.' ), 'previewIframeTitle' => __( 'Site Preview' ), 'loginIframeTitle' => __( 'Session expired' ), 'collapseSidebar' => __( 'Collapse Sidebar' ), 'expandSidebar' => __( 'Expand Sidebar' ), // Used for overriding the file types allowed in plupload. 'allowedFiles' => __( 'Allowed Files' ), ) ); $scripts->add( 'customize-widgets', "/wp-admin/js/customize-widgets$suffix.js", array( 'jquery', 'jquery-ui-sortable', 'jquery-ui-droppable', 'wp-backbone', 'customize-controls' ), false, 1 ); $scripts->add( 'customize-preview-widgets', "/wp-includes/js/customize-preview-widgets$suffix.js", array( 'jquery', 'wp-util', 'customize-preview' ), false, 1 ); $scripts->add( 'customize-nav-menus', "/wp-admin/js/customize-nav-menus$suffix.js", array( 'jquery', 'wp-backbone', 'customize-controls', 'accordion', 'nav-menu' ), false, 1 ); $scripts->add( 'customize-preview-nav-menus', "/wp-includes/js/customize-preview-nav-menus$suffix.js", array( 'jquery', 'wp-util', 'customize-preview' ), false, 1 ); $scripts->add( 'accordion', "/wp-admin/js/accordion$suffix.js", array( 'jquery' ), false, 1 ); $scripts->add( 'shortcode', "/wp-includes/js/shortcode$suffix.js", array( 'underscore' ), false, 1 ); $scripts->add( 'media-models', "/wp-includes/js/media-models$suffix.js", array( 'wp-backbone' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'media-models', '_wpMediaModelsL10n', array( 'settings' => array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'post' => array( 'id' => 0 ), ), ) ); $scripts->add( 'wp-oembed', "/wp-includes/js/wp-oembed$suffix.js" ); // To enqueue media-views or media-editor, call wp_enqueue_media(). // Both rely on numerous settings, styles, and templates to operate correctly. $scripts->add( 'media-views', "/wp-includes/js/media-views$suffix.js", array( 'utils', 'media-models', 'wp-plupload', 'jquery-ui-sortable', 'wp-mediaelement' ), false, 1 ); $scripts->add( 'media-editor', "/wp-includes/js/media-editor$suffix.js", array( 'shortcode', 'media-views' ), false, 1 ); $scripts->add( 'media-audiovideo', "/wp-includes/js/media-audiovideo$suffix.js", array( 'media-editor' ), false, 1 ); $scripts->add( 'mce-view', "/wp-includes/js/mce-view$suffix.js", array( 'shortcode', 'jquery', 'media-views', 'media-audiovideo' ), false, 1 ); if ( is_admin() ) { $scripts->add( 'admin-tags', "/wp-admin/js/tags$suffix.js", array( 'jquery', 'wp-ajax-response' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'admin-tags', 'tagsl10n', array( 'noPerm' => __('You do not have permission to do that.'), 'broken' => __('An unidentified error has occurred.') )); $scripts->add( 'admin-comments', "/wp-admin/js/edit-comments$suffix.js", array('wp-lists', 'quicktags', 'jquery-query'), false, 1 ); did_action( 'init' ) && $scripts->localize( 'admin-comments', 'adminCommentsL10n', array( 'hotkeys_highlight_first' => isset($_GET['hotkeys_highlight_first']), 'hotkeys_highlight_last' => isset($_GET['hotkeys_highlight_last']), 'replyApprove' => __( 'Approve and Reply' ), 'reply' => __( 'Reply' ), 'warnQuickEdit' => __( "Are you sure you want to edit this comment?\nThe changes you made will be lost." ), ) ); $scripts->add( 'xfn', "/wp-admin/js/xfn$suffix.js", array('jquery'), false, 1 ); $scripts->add( 'postbox', "/wp-admin/js/postbox$suffix.js", array('jquery-ui-sortable'), false, 1 ); $scripts->add( 'tags-box', "/wp-admin/js/tags-box$suffix.js", array( 'jquery', 'suggest' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'tags-box', 'tagsBoxL10n', array( 'tagDelimiter' => _x( ',', 'tag delimiter' ), ) ); $scripts->add( 'post', "/wp-admin/js/post$suffix.js", array( 'suggest', 'wp-lists', 'postbox', 'tags-box', 'underscore', 'word-count' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'post', 'postL10n', array( 'ok' => __('OK'), 'cancel' => __('Cancel'), 'publishOn' => __('Publish on:'), 'publishOnFuture' => __('Schedule for:'), 'publishOnPast' => __('Published on:'), /* translators: 1: month, 2: day, 3: year, 4: hour, 5: minute */ 'dateFormat' => __('%1$s %2$s, %3$s @ %4$s:%5$s'), 'showcomm' => __('Show more comments'), 'endcomm' => __('No more comments found.'), 'publish' => __('Publish'), 'schedule' => __('Schedule'), 'update' => __('Update'), 'savePending' => __('Save as Pending'), 'saveDraft' => __('Save Draft'), 'private' => __('Private'), 'public' => __('Public'), 'publicSticky' => __('Public, Sticky'), 'password' => __('Password Protected'), 'privatelyPublished' => __('Privately Published'), 'published' => __('Published'), 'saveAlert' => __('The changes you made will be lost if you navigate away from this page.'), 'savingText' => __('Saving Draft&#8230;'), ) ); $scripts->add( 'press-this', "/wp-admin/js/press-this$suffix.js", array( 'jquery', 'tags-box' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'press-this', 'pressThisL10n', array( 'newPost' => __( 'Title' ), 'serverError' => __( 'Connection lost or the server is busy. Please try again later.' ), 'saveAlert' => __( 'The changes you made will be lost if you navigate away from this page.' ), /* translators: %d: nth embed found in a post */ 'suggestedEmbedAlt' => __( 'Suggested embed #%d' ), /* translators: %d: nth image found in a post */ 'suggestedImgAlt' => __( 'Suggested image #%d' ), ) ); $scripts->add( 'editor-expand', "/wp-admin/js/editor-expand$suffix.js", array( 'jquery' ), false, 1 ); $scripts->add( 'link', "/wp-admin/js/link$suffix.js", array( 'wp-lists', 'postbox' ), false, 1 ); $scripts->add( 'comment', "/wp-admin/js/comment$suffix.js", array( 'jquery', 'postbox' ) ); $scripts->add_data( 'comment', 'group', 1 ); did_action( 'init' ) && $scripts->localize( 'comment', 'commentL10n', array( 'submittedOn' => __( 'Submitted on:' ), /* translators: 1: month, 2: day, 3: year, 4: hour, 5: minute */ 'dateFormat' => __( '%1$s %2$s, %3$s @ %4$s:%5$s' ) ) ); $scripts->add( 'admin-gallery', "/wp-admin/js/gallery$suffix.js", array( 'jquery-ui-sortable' ) ); $scripts->add( 'admin-widgets', "/wp-admin/js/widgets$suffix.js", array( 'jquery-ui-sortable', 'jquery-ui-draggable', 'jquery-ui-droppable' ), false, 1 ); $scripts->add( 'theme', "/wp-admin/js/theme$suffix.js", array( 'wp-backbone', 'wp-a11y' ), false, 1 ); $scripts->add( 'inline-edit-post', "/wp-admin/js/inline-edit-post$suffix.js", array( 'jquery', 'suggest' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'inline-edit-post', 'inlineEditL10n', array( 'error' => __('Error while saving the changes.'), 'ntdeltitle' => __('Remove From Bulk Edit'), 'notitle' => __('(no title)'), 'comma' => trim( _x( ',', 'tag delimiter' ) ), ) ); $scripts->add( 'inline-edit-tax', "/wp-admin/js/inline-edit-tax$suffix.js", array( 'jquery' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'inline-edit-tax', 'inlineEditL10n', array( 'error' => __('Error while saving the changes.') ) ); $scripts->add( 'plugin-install', "/wp-admin/js/plugin-install$suffix.js", array( 'jquery', 'thickbox' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'plugin-install', 'plugininstallL10n', array( 'plugin_information' => __('Plugin Information:'), 'ays' => __('Are you sure you want to install this plugin?') ) ); $scripts->add( 'updates', "/wp-admin/js/updates$suffix.js", array( 'jquery', 'wp-util', 'wp-a11y' ) ); did_action( 'init' ) && $scripts->localize( 'updates', '_wpUpdatesSettings', array( 'ajax_nonce' => wp_create_nonce( 'updates' ), 'l10n' => array( 'updating' => __( 'Updating...' ), // no ellipsis 'updated' => __( 'Updated!' ), /* translators: Error string for a failed update */ 'updateFailed' => __( 'Update Failed: %s' ), /* translators: Plugin name and version */ 'updatingLabel' => __( 'Updating %s...' ), // no ellipsis /* translators: Plugin name and version */ 'updatedLabel' => __( '%s updated!' ), /* translators: Plugin name and version */ 'updateFailedLabel' => __( '%s update failed' ), /* translators: JavaScript accessible string */ 'updatingMsg' => __( 'Updating... please wait.' ), // no ellipsis /* translators: JavaScript accessible string */ 'updatedMsg' => __( 'Update completed successfully.' ), /* translators: JavaScript accessible string */ 'updateCancel' => __( 'Update canceled.' ), 'beforeunload' => __( 'Plugin updates may not complete if you navigate away from this page.' ), ) ) ); $scripts->add( 'farbtastic', '/wp-admin/js/farbtastic.js', array('jquery'), '1.2' ); $scripts->add( 'iris', '/wp-admin/js/iris.min.js', array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), '1.0.7', 1 ); $scripts->add( 'wp-color-picker', "/wp-admin/js/color-picker$suffix.js", array( 'iris' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'wp-color-picker', 'wpColorPickerL10n', array( 'clear' => __( 'Clear' ), 'defaultString' => __( 'Default' ), 'pick' => __( 'Select Color' ), 'current' => __( 'Current Color' ), ) ); $scripts->add( 'dashboard', "/wp-admin/js/dashboard$suffix.js", array( 'jquery', 'admin-comments', 'postbox' ), false, 1 ); $scripts->add( 'list-revisions', "/wp-includes/js/wp-list-revisions$suffix.js" ); $scripts->add( 'media-grid', "/wp-includes/js/media-grid$suffix.js", array( 'media-editor' ), false, 1 ); $scripts->add( 'media', "/wp-admin/js/media$suffix.js", array( 'jquery' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'media', 'attachMediaBoxL10n', array( 'error' => __( 'An error has occurred. Please reload the page and try again.' ), )); $scripts->add( 'image-edit', "/wp-admin/js/image-edit$suffix.js", array('jquery', 'json2', 'imgareaselect'), false, 1 ); did_action( 'init' ) && $scripts->localize( 'image-edit', 'imageEditL10n', array( 'error' => __( 'Could not load the preview image. Please reload the page and try again.' ) )); $scripts->add( 'set-post-thumbnail', "/wp-admin/js/set-post-thumbnail$suffix.js", array( 'jquery' ), false, 1 ); did_action( 'init' ) && $scripts->localize( 'set-post-thumbnail', 'setPostThumbnailL10n', array( 'setThumbnail' => __( 'Use as featured image' ), 'saving' => __( 'Saving...' ), // no ellipsis 'error' => __( 'Could not set that as the thumbnail image. Try a different attachment.' ), 'done' => __( 'Done' ) ) ); // Navigation Menus $scripts->add( 'nav-menu', "/wp-admin/js/nav-menu$suffix.js", array( 'jquery-ui-sortable', 'jquery-ui-draggable', 'jquery-ui-droppable', 'wp-lists', 'postbox' ) ); did_action( 'init' ) && $scripts->localize( 'nav-menu', 'navMenuL10n', array( 'noResultsFound' => __( 'No results found.' ), 'warnDeleteMenu' => __( "You are about to permanently delete this menu. \n 'Cancel' to stop, 'OK' to delete." ), 'saveAlert' => __( 'The changes you made will be lost if you navigate away from this page.' ), 'untitled' => _x( '(no label)', 'missing menu item navigation label' ) ) ); $scripts->add( 'custom-header', "/wp-admin/js/custom-header.js", array( 'jquery-masonry' ), false, 1 ); $scripts->add( 'custom-background', "/wp-admin/js/custom-background$suffix.js", array( 'wp-color-picker', 'media-views' ), false, 1 ); $scripts->add( 'media-gallery', "/wp-admin/js/media-gallery$suffix.js", array('jquery'), false, 1 ); $scripts->add( 'svg-painter', '/wp-admin/js/svg-painter.js', array( 'jquery' ), false, 1 ); } } /** * Assign default styles to $styles object. * * Nothing is returned, because the $styles parameter is passed by reference. * Meaning that whatever object is passed will be updated without having to * reassign the variable that was passed back to the same value. This saves * memory. * * Adding default styles is not the only task, it also assigns the base_url * property, the default version, and text direction for the object. * * @since 2.6.0 * * @param WP_Styles $styles */ function wp_default_styles( &$styles ) { include( ABSPATH . WPINC . '/version.php' ); // include an unmodified $wp_version if ( ! defined( 'SCRIPT_DEBUG' ) ) define( 'SCRIPT_DEBUG', false !== strpos( $wp_version, '-src' ) ); if ( ! $guessurl = site_url() ) $guessurl = wp_guess_url(); $styles->base_url = $guessurl; $styles->content_url = defined('WP_CONTENT_URL')? WP_CONTENT_URL : ''; $styles->default_version = get_bloginfo( 'version' ); $styles->text_direction = function_exists( 'is_rtl' ) && is_rtl() ? 'rtl' : 'ltr'; $styles->default_dirs = array('/wp-admin/', '/wp-includes/css/'); $open_sans_font_url = ''; /* translators: If there are characters in your language that are not supported * by Open Sans, translate this to 'off'. Do not translate into your own language. */ if ( 'off' !== _x( 'on', 'Open Sans font: on or off' ) ) { $subsets = 'latin,latin-ext'; /* translators: To add an additional Open Sans character subset specific to your language, * translate this to 'greek', 'cyrillic' or 'vietnamese'. Do not translate into your own language. */ $subset = _x( 'no-subset', 'Open Sans font: add new subset (greek, cyrillic, vietnamese)' ); if ( 'cyrillic' == $subset ) { $subsets .= ',cyrillic,cyrillic-ext'; } elseif ( 'greek' == $subset ) { $subsets .= ',greek,greek-ext'; } elseif ( 'vietnamese' == $subset ) { $subsets .= ',vietnamese'; } // Hotlink Open Sans, for now $open_sans_font_url = "https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,300,400,600&subset=$subsets"; } // Register a stylesheet for the selected admin color scheme. $styles->add( 'colors', true, array( 'wp-admin', 'buttons', 'open-sans', 'dashicons' ) ); $suffix = SCRIPT_DEBUG ? '' : '.min'; // Admin CSS $styles->add( 'wp-admin', "/wp-admin/css/wp-admin$suffix.css", array( 'open-sans', 'dashicons' ) ); $styles->add( 'login', "/wp-admin/css/login$suffix.css", array( 'buttons', 'open-sans', 'dashicons' ) ); $styles->add( 'install', "/wp-admin/css/install$suffix.css", array( 'buttons', 'open-sans' ) ); $styles->add( 'wp-color-picker', "/wp-admin/css/color-picker$suffix.css" ); $styles->add( 'customize-controls', "/wp-admin/css/customize-controls$suffix.css", array( 'wp-admin', 'colors', 'ie', 'imgareaselect' ) ); $styles->add( 'customize-widgets', "/wp-admin/css/customize-widgets$suffix.css", array( 'wp-admin', 'colors' ) ); $styles->add( 'customize-nav-menus', "/wp-admin/css/customize-nav-menus$suffix.css", array( 'wp-admin', 'colors' ) ); $styles->add( 'press-this', "/wp-admin/css/press-this$suffix.css", array( 'open-sans', 'buttons' ) ); $styles->add( 'ie', "/wp-admin/css/ie$suffix.css" ); $styles->add_data( 'ie', 'conditional', 'lte IE 7' ); // Common dependencies $styles->add( 'buttons', "/wp-includes/css/buttons$suffix.css" ); $styles->add( 'dashicons', "/wp-includes/css/dashicons$suffix.css" ); $styles->add( 'open-sans', $open_sans_font_url ); // Includes CSS $styles->add( 'admin-bar', "/wp-includes/css/admin-bar$suffix.css", array( 'open-sans', 'dashicons' ) ); $styles->add( 'wp-auth-check', "/wp-includes/css/wp-auth-check$suffix.css", array( 'dashicons' ) ); $styles->add( 'editor-buttons', "/wp-includes/css/editor$suffix.css", array( 'dashicons' ) ); $styles->add( 'media-views', "/wp-includes/css/media-views$suffix.css", array( 'buttons', 'dashicons', 'wp-mediaelement' ) ); $styles->add( 'wp-pointer', "/wp-includes/css/wp-pointer$suffix.css", array( 'dashicons' ) ); $styles->add( 'customize-preview', "/wp-includes/css/customize-preview$suffix.css" ); // External libraries and friends $styles->add( 'imgareaselect', '/wp-includes/js/imgareaselect/imgareaselect.css', array(), '0.9.8' ); $styles->add( 'wp-jquery-ui-dialog', "/wp-includes/css/jquery-ui-dialog$suffix.css", array( 'dashicons' ) ); $styles->add( 'mediaelement', "/wp-includes/js/mediaelement/mediaelementplayer.min.css", array(), '2.17.0' ); $styles->add( 'wp-mediaelement', "/wp-includes/js/mediaelement/wp-mediaelement.css", array( 'mediaelement' ) ); $styles->add( 'thickbox', '/wp-includes/js/thickbox/thickbox.css', array( 'dashicons' ) ); // Deprecated CSS $styles->add( 'media', "/wp-admin/css/deprecated-media$suffix.css" ); $styles->add( 'farbtastic', '/wp-admin/css/farbtastic.css', array(), '1.3u1' ); $styles->add( 'jcrop', "/wp-includes/js/jcrop/jquery.Jcrop.min.css", array(), '0.9.12' ); $styles->add( 'colors-fresh', false, array( 'wp-admin', 'buttons' ) ); // Old handle. // RTL CSS $rtl_styles = array( // wp-admin 'wp-admin', 'install', 'wp-color-picker', 'customize-controls', 'customize-widgets', 'customize-nav-menus', 'ie', 'login', 'press-this', // wp-includes 'buttons', 'admin-bar', 'wp-auth-check', 'editor-buttons', 'media-views', 'wp-pointer', 'wp-jquery-ui-dialog', // deprecated 'media', 'farbtastic', ); foreach ( $rtl_styles as $rtl_style ) { $styles->add_data( $rtl_style, 'rtl', 'replace' ); if ( $suffix ) { $styles->add_data( $rtl_style, 'suffix', $suffix ); } } } /** * Reorder JavaScript scripts array to place prototype before jQuery. * * @since 2.3.1 * * @param array $js_array JavaScript scripts array * @return array Reordered array, if needed. */ function wp_prototype_before_jquery( $js_array ) { if ( false === $prototype = array_search( 'prototype', $js_array, true ) ) return $js_array; if ( false === $jquery = array_search( 'jquery', $js_array, true ) ) return $js_array; if ( $prototype < $jquery ) return $js_array; unset($js_array[$prototype]); array_splice( $js_array, $jquery, 0, 'prototype' ); return $js_array; } /** * Load localized data on print rather than initialization. * * These localizations require information that may not be loaded even by init. * * @since 2.5.0 */ function wp_just_in_time_script_localization() { wp_localize_script( 'autosave', 'autosaveL10n', array( 'autosaveInterval' => AUTOSAVE_INTERVAL, 'blog_id' => get_current_blog_id(), ) ); } /** * Administration Screen CSS for changing the styles. * * If installing the 'wp-admin/' directory will be replaced with './'. * * The $_wp_admin_css_colors global manages the Administration Screens CSS * stylesheet that is loaded. The option that is set is 'admin_color' and is the * color and key for the array. The value for the color key is an object with * a 'url' parameter that has the URL path to the CSS file. * * The query from $src parameter will be appended to the URL that is given from * the $_wp_admin_css_colors array value URL. * * @since 2.6.0 * @global array $_wp_admin_css_colors * * @param string $src Source URL. * @param string $handle Either 'colors' or 'colors-rtl'. * @return string|false URL path to CSS stylesheet for Administration Screens. */ function wp_style_loader_src( $src, $handle ) { global $_wp_admin_css_colors; if ( wp_installing() ) return preg_replace( '#^wp-admin/#', './', $src ); if ( 'colors' == $handle ) { $color = get_user_option('admin_color'); if ( empty($color) || !isset($_wp_admin_css_colors[$color]) ) $color = 'fresh'; $color = $_wp_admin_css_colors[$color]; $parsed = parse_url( $src ); $url = $color->url; if ( ! $url ) { return false; } if ( isset($parsed['query']) && $parsed['query'] ) { wp_parse_str( $parsed['query'], $qv ); $url = add_query_arg( $qv, $url ); } return $url; } return $src; } /** * Prints the script queue in the HTML head on admin pages. * * Postpones the scripts that were queued for the footer. * print_footer_scripts() is called in the footer to print these scripts. * * @since 2.8.0 * * @see wp_print_scripts() * * @global bool $concatenate_scripts * * @return array */ function print_head_scripts() { global $concatenate_scripts; if ( ! did_action('wp_print_scripts') ) { /** This action is documented in wp-includes/functions.wp-scripts.php */ do_action( 'wp_print_scripts' ); } $wp_scripts = wp_scripts(); script_concat_settings(); $wp_scripts->do_concat = $concatenate_scripts; $wp_scripts->do_head_items(); /** * Filter whether to print the head scripts. * * @since 2.8.0 * * @param bool $print Whether to print the head scripts. Default true. */ if ( apply_filters( 'print_head_scripts', true ) ) { _print_scripts(); } $wp_scripts->reset(); return $wp_scripts->done; } /** * Prints the scripts that were queued for the footer or too late for the HTML head. * * @since 2.8.0 * * @global WP_Scripts $wp_scripts * @global bool $concatenate_scripts * * @return array */ function print_footer_scripts() { global $wp_scripts, $concatenate_scripts; if ( ! ( $wp_scripts instanceof WP_Scripts ) ) { return array(); // No need to run if not instantiated. } script_concat_settings(); $wp_scripts->do_concat = $concatenate_scripts; $wp_scripts->do_footer_items(); /** * Filter whether to print the footer scripts. * * @since 2.8.0 * * @param bool $print Whether to print the footer scripts. Default true. */ if ( apply_filters( 'print_footer_scripts', true ) ) { _print_scripts(); } $wp_scripts->reset(); return $wp_scripts->done; } /** * Print scripts (internal use only) * * @ignore * * @global WP_Scripts $wp_scripts * @global bool $compress_scripts */ function _print_scripts() { global $wp_scripts, $compress_scripts; $zip = $compress_scripts ? 1 : 0; if ( $zip && defined('ENFORCE_GZIP') && ENFORCE_GZIP ) $zip = 'gzip'; if ( $concat = trim( $wp_scripts->concat, ', ' ) ) { if ( !empty($wp_scripts->print_code) ) { echo "\n<script type='text/javascript'>\n"; echo "/* <![CDATA[ */\n"; // not needed in HTML 5 echo $wp_scripts->print_code; echo "/* ]]> */\n"; echo "</script>\n"; } $concat = str_split( $concat, 128 ); $concat = 'load%5B%5D=' . implode( '&load%5B%5D=', $concat ); $src = $wp_scripts->base_url . "/wp-admin/load-scripts.php?c={$zip}&" . $concat . '&ver=' . $wp_scripts->default_version; echo "<script type='text/javascript' src='" . esc_attr($src) . "'></script>\n"; } if ( !empty($wp_scripts->print_html) ) echo $wp_scripts->print_html; } /** * Prints the script queue in the HTML head on the front end. * * Postpones the scripts that were queued for the footer. * wp_print_footer_scripts() is called in the footer to print these scripts. * * @since 2.8.0 * * @global WP_Scripts $wp_scripts * * @return array */ function wp_print_head_scripts() { if ( ! did_action('wp_print_scripts') ) { /** This action is documented in wp-includes/functions.wp-scripts.php */ do_action( 'wp_print_scripts' ); } global $wp_scripts; if ( ! ( $wp_scripts instanceof WP_Scripts ) ) { return array(); // no need to run if nothing is queued } return print_head_scripts(); } /** * Private, for use in *_footer_scripts hooks * * @since 3.3.0 */ function _wp_footer_scripts() { print_late_styles(); print_footer_scripts(); } /** * Hooks to print the scripts and styles in the footer. * * @since 2.8.0 */ function wp_print_footer_scripts() { /** * Fires when footer scripts are printed. * * @since 2.8.0 */ do_action( 'wp_print_footer_scripts' ); } /** * Wrapper for do_action('wp_enqueue_scripts') * * Allows plugins to queue scripts for the front end using wp_enqueue_script(). * Runs first in wp_head() where all is_home(), is_page(), etc. functions are available. * * @since 2.8.0 */ function wp_enqueue_scripts() { /** * Fires when scripts and styles are enqueued. * * @since 2.8.0 */ do_action( 'wp_enqueue_scripts' ); } /** * Prints the styles queue in the HTML head on admin pages. * * @since 2.8.0 * * @global bool $concatenate_scripts * * @return array */ function print_admin_styles() { global $concatenate_scripts; $wp_styles = wp_styles(); script_concat_settings(); $wp_styles->do_concat = $concatenate_scripts; $wp_styles->do_items(false); /** * Filter whether to print the admin styles. * * @since 2.8.0 * * @param bool $print Whether to print the admin styles. Default true. */ if ( apply_filters( 'print_admin_styles', true ) ) { _print_styles(); } $wp_styles->reset(); return $wp_styles->done; } /** * Prints the styles that were queued too late for the HTML head. * * @since 3.3.0 * * @global WP_Styles $wp_styles * @global bool $concatenate_scripts * * @return array|void */ function print_late_styles() { global $wp_styles, $concatenate_scripts; if ( ! ( $wp_styles instanceof WP_Styles ) ) { return; } $wp_styles->do_concat = $concatenate_scripts; $wp_styles->do_footer_items(); /** * Filter whether to print the styles queued too late for the HTML head. * * @since 3.3.0 * * @param bool $print Whether to print the 'late' styles. Default true. */ if ( apply_filters( 'print_late_styles', true ) ) { _print_styles(); } $wp_styles->reset(); return $wp_styles->done; } /** * Print styles (internal use only) * * @ignore * * @global bool $compress_css */ function _print_styles() { global $compress_css; $wp_styles = wp_styles(); $zip = $compress_css ? 1 : 0; if ( $zip && defined('ENFORCE_GZIP') && ENFORCE_GZIP ) $zip = 'gzip'; if ( !empty($wp_styles->concat) ) { $dir = $wp_styles->text_direction; $ver = $wp_styles->default_version; $href = $wp_styles->base_url . "/wp-admin/load-styles.php?c={$zip}&dir={$dir}&load=" . trim($wp_styles->concat, ', ') . '&ver=' . $ver; echo "<link rel='stylesheet' href='" . esc_attr($href) . "' type='text/css' media='all' />\n"; if ( !empty($wp_styles->print_code) ) { echo "<style type='text/css'>\n"; echo $wp_styles->print_code; echo "\n</style>\n"; } } if ( !empty($wp_styles->print_html) ) echo $wp_styles->print_html; } /** * Determine the concatenation and compression settings for scripts and styles. * * @since 2.8.0 * * @global bool $concatenate_scripts * @global bool $compress_scripts * @global bool $compress_css */ function script_concat_settings() { global $concatenate_scripts, $compress_scripts, $compress_css; $compressed_output = ( ini_get('zlib.output_compression') || 'ob_gzhandler' == ini_get('output_handler') ); if ( ! isset($concatenate_scripts) ) { $concatenate_scripts = defined('CONCATENATE_SCRIPTS') ? CONCATENATE_SCRIPTS : true; if ( ! is_admin() || ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) ) $concatenate_scripts = false; } if ( ! isset($compress_scripts) ) { $compress_scripts = defined('COMPRESS_SCRIPTS') ? COMPRESS_SCRIPTS : true; if ( $compress_scripts && ( ! get_site_option('can_compress_scripts') || $compressed_output ) ) $compress_scripts = false; } if ( ! isset($compress_css) ) { $compress_css = defined('COMPRESS_CSS') ? COMPRESS_CSS : true; if ( $compress_css && ( ! get_site_option('can_compress_scripts') || $compressed_output ) ) $compress_css = false; } }
gpl-2.0
DailyShana/ygopro-scripts
c22493811.lua
1540
--アリの増殖 function c22493811.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c22493811.cost) e1:SetTarget(c22493811.target) e1:SetOperation(c22493811.activate) c:RegisterEffect(e1) end function c22493811.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsRace,1,nil,RACE_INSECT) end local g=Duel.SelectReleaseGroup(tp,Card.IsRace,1,1,nil,RACE_INSECT) Duel.Release(g,REASON_COST) end function c22493811.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,22493812,0,0x4011,500,1200,4,RACE_INSECT,ATTRIBUTE_EARTH) end Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,2,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,0,0) end function c22493811.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and Duel.IsPlayerCanSpecialSummonMonster(tp,22493812,0,0x4011,500,1200,4,RACE_INSECT,ATTRIBUTE_EARTH) then for i=1,2 do local token=Duel.CreateToken(tp,22493812) Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UNRELEASABLE_SUM) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetValue(1) e1:SetReset(RESET_EVENT+0x1fe0000) token:RegisterEffect(e1,true) end Duel.SpecialSummonComplete() end end
gpl-2.0
debugger06/MiroX
tv/osx/plat/script_codes.py
5132
# Miro - an RSS based video player application # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 # Participatory Culture Foundation # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # # You must obey the GNU General Public License in all respects for all of # the code used other than OpenSSL. If you modify file(s) with this # exception, you may extend this exception to your version of the file(s), # but you are not obligated to do so. If you do not wish to do so, delete # this exception statement from your version. If you delete this exception # statement from all source files in the program, then also delete it here. def map_to_two_letters_code(code): for pair in OSX_SCRIPT_CODES_LIST: if pair[0] == code and pair[1] is not None: return pair[1] return None OSX_SCRIPT_CODES_LIST = [ (0, "en"), # English (1, "fr"), # French (2, "de"), # German (3, "it"), # Italian (4, "nl"), # Dutch (5, "sv"), # Swedish (6, "es"), # Spanish (7, "da"), # Danish (8, "pt"), # Portuguese (9, "no"), # Norwegian (10, "he"), # Hebrew (11, "ja"), # Japanese (12, "ar"), # Arabic (13, "fi"), # Finnish (14, "el"), # Greek (15, "is"), # Icelandic (16, "mt"), # Maltese (17, "tr"), # Turkish (18, "hr"), # Croatian (19, "zh"), # TradChinese (20, "ur"), # Urdu (21, "hi"), # Hindi (22, "th"), # Thai (23, "ko"), # Korean (24, "lt"), # Lithuanian (25, "pl"), # Polish (26, "hu"), # Hungarian (27, "et"), # Estonian (28, "lv"), # Latvian (29, "se"), # Sami (30, "fo"), # Faroese (31, None), # Farsi (31, "fa"), # Persian (32, "ru"), # Russian (33, None), # SimpChinese (34, None), # Flemish (35, "ga"), # IrishGaelic (36, "sq"), # Albanian (37, "ro"), # Romanian (38, "cz"), # Czech (39, "sk"), # Slovak (40, "sl"), # Slovenian (41, "yi"), # Yiddish (42, "sr"), # Serbian (43, "mk"), # Macedonian (44, "bg"), # Bulgarian (45, "uk"), # Ukrainian (46, None), # Belorussian (47, "uz"), # Uzbek (48, "kk"), # Kazakh (49, "az"), # Azerbaijani (50, None), # AzerbaijanAr (51, "hy"), # Armenian (52, "ka"), # Georgian (53, "mo"), # Moldavian (54, "ky"), # Kirghiz (55, "tg"), # Tajiki (56, "tk"), # Turkmen (57, "mn"), # Mongolian (58, None), # MongolianCyr (59, None), # Pashto (60, "ku"), # Kurdish (61, "ks"), # Kashmiri (62, "sd"), # Sindhi (63, "bo"), # Tibetan (64, "ne"), # Nepali (65, "sa"), # Sanskrit (66, "mr"), # Marathi (67, "bn"), # Bengali (68, "as"), # Assamese (69, "gu"), # Gujarati (70, "pa"), # Punjabi (71, "or"), # Oriya (72, "ml"), # Malayalam (73, "kn"), # Kannada (74, "ta"), # Tamil (75, "te"), # Telugu (76, "si"), # Sinhalese (77, "my"), # Burmese (78, "km"), # Khmer (79, "lo"), # Lao (80, "vi"), # Vietnamese (81, "id"), # Indonesian (82, "tl"), # Tagalog (83, "ms"), # MalayRoman (84, "ml"), # MalayArabic (85, "am"), # Amharic (86, "ti"), # Tigrinya (87, "om"), # Oromo (88, "so"), # Somali (89, "sw"), # Swahili (90, "rw"), # Kinyarwanda (90, None), # Ruanda (91, "rn"), # Rundi (92, "ny"), # Nyanja (92, None), # Chewa (93, "mg"), # Malagasy (94, "eo"), # Esperanto (128, "cy"), # Welsh (129, "eu"), # Basque (130, "ca"), # Catalan (131, "la"), # Latin (132, "qu"), # Quechua (133, "gn"), # Guarani (134, "ay"), # Aymara (135, "tt"), # Tatar (136, "ug"), # Uighur (137, "dz"), # Dzongkha (138, "jv"), # JavaneseRom (139, "su"), # SundaneseRom (140, "gl"), # Galician (141, "af"), # Afrikaans (142, "br"), # Breton (143, None), # Inuktitut (144, "gd"), # ScottishGaelic (145, "gv"), # ManxGaelic (146, "ga"), # IrishGaelicScript (147, "tog"), # Tongan (148, "grc"), # GreekAncient (149, "kl"), # Greenlandic (150, None), # AzerbaijanRoman (151, "nn") # Nynorsk ]
gpl-2.0
JMC47/dolphin
Source/Core/DiscIO/Enums.cpp
22645
// Copyright 2016 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include <map> #include <string> #include "Common/Assert.h" #include "Common/Common.h" #include "Common/CommonTypes.h" #include "Common/Logging/Log.h" #include "Common/MsgHandler.h" #include "DiscIO/Enums.h" namespace DiscIO { std::string GetName(Country country, bool translate) { std::string name; switch (country) { case Country::Europe: name = _trans("Europe"); break; case Country::Japan: name = _trans("Japan"); break; case Country::USA: name = _trans("USA"); break; case Country::Australia: name = _trans("Australia"); break; case Country::France: name = _trans("France"); break; case Country::Germany: name = _trans("Germany"); break; case Country::Italy: name = _trans("Italy"); break; case Country::Korea: name = _trans("Korea"); break; case Country::Netherlands: name = _trans("Netherlands"); break; case Country::Russia: name = _trans("Russia"); break; case Country::Spain: name = _trans("Spain"); break; case Country::Taiwan: name = _trans("Taiwan"); break; case Country::World: name = _trans("World"); break; default: name = _trans("Unknown"); break; } return translate ? Common::GetStringT(name.c_str()) : name; } std::string GetName(Language language, bool translate) { std::string name; switch (language) { case Language::Japanese: name = _trans("Japanese"); break; case Language::English: name = _trans("English"); break; case Language::German: name = _trans("German"); break; case Language::French: name = _trans("French"); break; case Language::Spanish: name = _trans("Spanish"); break; case Language::Italian: name = _trans("Italian"); break; case Language::Dutch: name = _trans("Dutch"); break; case Language::SimplifiedChinese: name = _trans("Simplified Chinese"); break; case Language::TraditionalChinese: name = _trans("Traditional Chinese"); break; case Language::Korean: name = _trans("Korean"); break; default: name = _trans("Unknown"); break; } return translate ? Common::GetStringT(name.c_str()) : name; } bool IsDisc(Platform volume_type) { return volume_type == Platform::GameCubeDisc || volume_type == Platform::WiiDisc; } bool IsWii(Platform volume_type) { return volume_type == Platform::WiiDisc || volume_type == Platform::WiiWAD; } bool IsNTSC(Region region) { return region == Region::NTSC_J || region == Region::NTSC_U || region == Region::NTSC_K; } int ToGameCubeLanguage(Language language) { if (language < Language::English || language > Language::Dutch) return 0; else return static_cast<int>(language) - 1; } Language FromGameCubeLanguage(int language) { if (language < 0 || language > 5) return Language::Unknown; else return static_cast<Language>(language + 1); } // Increment CACHE_REVISION (GameFileCache.cpp) if the code below is modified Country TypicalCountryForRegion(Region region) { switch (region) { case Region::NTSC_J: return Country::Japan; case Region::NTSC_U: return Country::USA; case Region::PAL: return Country::Europe; case Region::NTSC_K: return Country::Korea; default: return Country::Unknown; } } Region SysConfCountryToRegion(u8 country_code) { if (country_code == 0) return Region::Unknown; if (country_code < 0x08) // Japan return Region::NTSC_J; if (country_code < 0x40) // Americas return Region::NTSC_U; if (country_code < 0x80) // Europe, Oceania, parts of Africa return Region::PAL; if (country_code < 0xa8) // Southeast Asia return country_code == 0x88 ? Region::NTSC_K : Region::NTSC_J; if (country_code < 0xc0) // Middle East return Region::NTSC_U; return Region::Unknown; } Region CountryCodeToRegion(u8 country_code, Platform platform, Region expected_region, std::optional<u16> revision) { switch (country_code) { case '\2': return expected_region; // Wii Menu (same title ID for all regions) case 'J': return Region::NTSC_J; case 'W': if (expected_region == Region::PAL) return Region::PAL; // Only the Nordic version of Ratatouille (Wii) else return Region::NTSC_J; // Korean GC games in English or Taiwanese Wii games case 'E': if (platform != Platform::GameCubeDisc) return Region::NTSC_U; // The most common country code for NTSC-U if (revision) { if (*revision >= 0x30) return Region::NTSC_J; // Korean GC games in English else return Region::NTSC_U; // The most common country code for NTSC-U } else { if (expected_region == Region::NTSC_J) return Region::NTSC_J; // Korean GC games in English else return Region::NTSC_U; // The most common country code for NTSC-U } case 'B': case 'N': return Region::NTSC_U; case 'X': case 'Y': case 'Z': // Additional language versions, store-exclusive versions, other special versions return expected_region == Region::NTSC_U ? Region::NTSC_U : Region::PAL; case 'D': case 'F': case 'H': case 'I': case 'L': case 'M': case 'P': case 'R': case 'S': case 'U': case 'V': return Region::PAL; case 'K': case 'Q': case 'T': // All of these country codes are Korean, but the NTSC-K region doesn't exist on GC return platform == Platform::GameCubeDisc ? Region::NTSC_J : Region::NTSC_K; default: return Region::Unknown; } } Country CountryCodeToCountry(u8 country_code, Platform platform, Region region, std::optional<u16> revision) { switch (country_code) { // Worldwide case 'A': return Country::World; // Mixed regions case 'X': case 'Y': case 'Z': // Additional language versions, store-exclusive versions, other special versions return region == Region::NTSC_U ? Country::USA : Country::Europe; case 'W': if (platform == Platform::GameCubeDisc) return Country::Korea; // GC games in English released in Korea else if (region == Region::PAL) return Country::Europe; // Only the Nordic version of Ratatouille (Wii) else return Country::Taiwan; // Wii games in traditional Chinese released in Taiwan // PAL case 'D': return Country::Germany; case 'L': // NTSC-J games released on PAL VC case 'M': // NTSC-U games released on PAL VC case 'V': // Used by some Nordic Wii releases case 'P': // The most common country code for PAL return Country::Europe; case 'U': return Country::Australia; case 'F': return Country::France; case 'I': return Country::Italy; case 'H': return Country::Netherlands; case 'R': return Country::Russia; case 'S': return Country::Spain; // NTSC case 'E': if (platform != Platform::GameCubeDisc) return Country::USA; // The most common country code for NTSC-U if (revision) { if (*revision >= 0x30) return Country::Korea; // GC games in English released in Korea else return Country::USA; // The most common country code for NTSC-U } else { if (region == Region::NTSC_J) return Country::Korea; // GC games in English released in Korea else return Country::USA; // The most common country code for NTSC-U } case 'B': // PAL games released on NTSC-U VC case 'N': // NTSC-J games released on NTSC-U VC return Country::USA; case 'J': return Country::Japan; case 'K': // Games in Korean released in Korea case 'Q': // NTSC-J games released on NTSC-K VC case 'T': // NTSC-U games released on NTSC-K VC return Country::Korea; default: if (country_code > 'A') // Silently ignore IOS wads WARN_LOG_FMT(DISCIO, "Unknown Country Code! {}", static_cast<char>(country_code)); return Country::Unknown; } } Region GetSysMenuRegion(u16 title_version) { switch (title_version & 0xf) { case 0: return Region::NTSC_J; case 1: return Region::NTSC_U; case 2: return Region::PAL; case 6: return Region::NTSC_K; default: return Region::Unknown; } } std::string GetSysMenuVersionString(u16 title_version) { std::string version; char region_letter = '\0'; switch (GetSysMenuRegion(title_version)) { case Region::NTSC_J: region_letter = 'J'; break; case Region::NTSC_U: region_letter = 'U'; break; case Region::PAL: region_letter = 'E'; break; case Region::NTSC_K: region_letter = 'K'; break; case Region::Unknown: WARN_LOG_FMT(DISCIO, "Unknown region for Wii Menu version {}", title_version); break; } switch (title_version & 0xff0) { case 32: version = "1.0"; break; case 96: case 128: version = "2.0"; break; case 160: version = "2.1"; break; case 192: version = "2.2"; break; case 224: version = "3.0"; break; case 256: version = "3.1"; break; case 288: version = "3.2"; break; case 320: case 352: version = "3.3"; break; case 384: version = (region_letter != 'K' ? "3.4" : "3.5"); break; case 416: version = "4.0"; break; case 448: version = "4.1"; break; case 480: version = "4.2"; break; case 512: version = "4.3"; break; default: version = "?.?"; break; } if (region_letter != '\0') version += region_letter; return version; } const std::string& GetCompanyFromID(const std::string& company_id) { static const std::map<std::string, std::string> companies = { {"01", "Nintendo"}, {"02", "Nintendo"}, {"08", "Capcom"}, {"0A", "Jaleco / Jaleco Entertainment"}, {"0L", "Warashi"}, {"0M", "Entertainment Software Publishing"}, {"0Q", "IE Institute"}, {"13", "Electronic Arts Japan"}, {"18", "Hudson Soft / Hudson Entertainment"}, {"1K", "Titus Software"}, {"20", "DSI Games / ZOO Digital Publishing"}, {"28", "Kemco Japan"}, {"29", "SETA Corporation"}, {"2K", "NEC Interchannel"}, {"2L", "Agatsuma Entertainment"}, {"2M", "Jorudan"}, {"2N", "Smilesoft / Rocket Company"}, {"2Q", "MediaKite"}, {"36", "Codemasters"}, {"41", "Ubisoft"}, {"4F", "Eidos Interactive"}, {"4Q", "Disney Interactive Studios / Buena Vista Games"}, {"4Z", "Crave Entertainment / Red Wagon Games"}, {"51", "Acclaim Entertainment"}, {"52", "Activision"}, {"54", "Take-Two Interactive / GameTek / Rockstar Games / Global Star Software"}, {"5D", "Midway Games / Tradewest"}, {"5G", "Majesco Entertainment"}, {"5H", "3DO / Global Star Software"}, {"5L", "NewKidCo"}, {"5S", "Evolved Games / Xicat Interactive"}, {"5V", "Agetec"}, {"5Z", "Data Design / Conspiracy Entertainment"}, {"60", "Titus Interactive / Titus Software"}, {"64", "LucasArts"}, {"68", "Bethesda Softworks / Mud Duck Productions / Vir2L Studios"}, {"69", "Electronic Arts"}, {"6E", "Sega"}, {"6K", "UFO Interactive Games"}, {"6L", "BAM! Entertainment"}, {"6M", "System 3"}, {"6N", "Midas Interactive Entertainment"}, {"6S", "TDK Mediactive"}, {"6U", "The Adventure Company / DreamCatcher Interactive"}, {"6V", "JoWooD Entertainment"}, {"6W", "Sega"}, {"6X", "Wanadoo Edition"}, {"6Z", "NDS Software"}, {"70", "Atari (Infogrames)"}, {"71", "Interplay Entertainment"}, {"75", "SCi Games"}, {"78", "THQ / Play THQ"}, {"7D", "Sierra Entertainment / Vivendi Games / Universal Interactive Studios"}, {"7F", "Kemco"}, {"7G", "Rage Software"}, {"7H", "Encore Software"}, {"7J", "Zushi Games / ZOO Digital Publishing"}, {"7K", "Kiddinx Entertainment"}, {"7L", "Simon & Schuster Interactive"}, {"7M", "Badland Games"}, {"7N", "Empire Interactive / Xplosiv"}, {"7S", "Rockstar Games"}, {"7T", "Scholastic"}, {"7U", "Ignition Entertainment"}, {"82", "Namco"}, {"8G", "NEC Interchannel"}, {"8J", "Kadokawa Shoten"}, {"8M", "CyberFront"}, {"8N", "Success"}, {"8P", "Sega"}, {"91", "Chunsoft"}, {"99", "Marvelous Entertainment / Victor Entertainment / Pack-In-Video / Rising Star Games"}, {"9B", "Tecmo"}, {"9G", "Take-Two Interactive / Global Star Software / Gotham Games / Gathering of Developers"}, {"9S", "Brother International"}, {"9Z", "Crunchyroll"}, {"A4", "Konami"}, {"A7", "Takara"}, {"AF", "Namco Bandai Games"}, {"AU", "Alternative Software"}, {"AX", "Vivendi"}, {"B0", "Acclaim Japan"}, {"B2", "Bandai Games"}, {"BB", "Sunsoft"}, {"BL", "MTO"}, {"BM", "XING"}, {"BN", "Sunrise Interactive"}, {"BP", "Global A Entertainment"}, {"C0", "Taito"}, {"C8", "Koei"}, {"CM", "Konami Computer Entertainment Osaka"}, {"CQ", "From Software"}, {"D9", "Banpresto"}, {"DA", "Tomy / Takara Tomy"}, {"DQ", "Compile Heart / Idea Factory"}, {"E5", "Epoch"}, {"E6", "Game Arts"}, {"E7", "Athena"}, {"E8", "Asmik Ace Entertainment"}, {"E9", "Natsume"}, {"EB", "Atlus"}, {"EL", "Spike"}, {"EM", "Konami Computer Entertainment Tokyo"}, {"EP", "Sting Entertainment"}, {"ES", "Starfish-SD"}, {"EY", "Vblank Entertainment"}, {"FH", "Easy Interactive"}, {"FJ", "Virtual Toys"}, {"FK", "The Game Factory"}, {"FP", "Mastiff"}, {"FR", "Digital Tainment Pool"}, {"FS", "XS Games"}, {"G0", "Alpha Unit"}, {"G2", "Yuke's"}, {"G6", "SIMS"}, {"G9", "D3 Publisher"}, {"GA", "PIN Change"}, {"GD", "Square Enix"}, {"GE", "Kids Station"}, {"GG", "O3 Entertainment"}, {"GJ", "Detn8 Games"}, {"GK", "Genki"}, {"GL", "Gameloft / Ubisoft"}, {"GM", "Gamecock Media Group"}, {"GN", "Oxygen Games"}, {"GR", "GSP"}, {"GT", "505 Games"}, {"GX", "Commodore"}, {"GY", "The Game Factory"}, {"GZ", "Gammick Entertainment"}, {"H3", "Zen United"}, {"H4", "SNK Playmore"}, {"HA", "Nobilis"}, {"HE", "Gust"}, {"HF", "Level-5"}, {"HG", "Graffiti Entertainment"}, {"HH", "Focus Home Interactive"}, {"HJ", "Genius Products"}, {"HK", "D2C Games"}, {"HL", "Frontier Developments"}, {"HM", "HMH Interactive"}, {"HN", "High Voltage Software"}, {"HQ", "Abstraction Games"}, {"HS", "Tru Blu"}, {"HT", "Big Blue Bubble"}, {"HU", "Ghostfire Games"}, {"HW", "Incredible Technologies"}, {"HY", "Reef Entertainment"}, {"HZ", "Nordcurrent"}, {"J8", "D4 Enterprise"}, {"J9", "AQ Interactive"}, {"JD", "SKONEC Entertainment"}, {"JE", "E Frontier"}, {"JF", "Arc System Works"}, {"JG", "The Games Company"}, {"JH", "City Interactive"}, {"JJ", "Deep Silver"}, {"JP", "redspotgames"}, {"JR", "Engine Software"}, {"JS", "Digital Leisure"}, {"JT", "Empty Clip Studios"}, {"JU", "Riverman Media"}, {"JV", "JV Games"}, {"JW", "BigBen Interactive"}, {"JX", "Shin'en Multimedia"}, {"JY", "Steel Penny Games"}, {"JZ", "505 Games"}, {"K2", "Coca-Cola (Japan) Company"}, {"K3", "Yudo"}, {"K6", "Nihon System"}, {"KB", "Nippon Ichi Software"}, {"KG", "Kando Games"}, {"KH", "Joju Games"}, {"KJ", "Studio Zan"}, {"KK", "DK Games"}, {"KL", "Abylight"}, {"KM", "Deep Silver"}, {"KN", "Gameshastra"}, {"KP", "Purple Hills"}, {"KQ", "Over the Top Games"}, {"KR", "KREA Medie"}, {"KT", "The Code Monkeys"}, {"KW", "Semnat Studios"}, {"KY", "Medaverse Studios"}, {"L3", "G-Mode"}, {"L8", "FujiSoft"}, {"LB", "Tryfirst"}, {"LD", "Studio Zan"}, {"LF", "Kemco"}, {"LG", "Black Bean Games"}, {"LJ", "Legendo Entertainment"}, {"LL", "HB Studios"}, {"LN", "GameOn"}, {"LP", "Left Field Productions"}, {"LR", "Koch Media"}, {"LT", "Legacy Interactive"}, {"LU", "Lexis Num\xc3\xa9rique"}, // We can't use a u8 prefix due to C++20's u8string {"LW", "Grendel Games"}, {"LY", "Icon Games / Super Icon"}, {"M0", "Studio Zan"}, {"M1", "Grand Prix Games"}, {"M2", "HomeMedia"}, {"M4", "Cybird"}, {"M6", "Perpetuum"}, {"MB", "Agenda"}, {"MD", "Ateam"}, {"ME", "Silver Star Japan"}, {"MF", "Yamasa"}, {"MH", "Mentor Interactive"}, {"MJ", "Mumbo Jumbo"}, {"ML", "DTP Young Entertainment"}, {"MM", "Big John Games"}, {"MN", "Mindscape"}, {"MR", "Mindscape"}, {"MS", "Milestone / UFO Interactive Games"}, {"MT", "Blast! Entertainment"}, {"MV", "Marvelous Entertainment"}, {"MZ", "Mad Catz"}, {"N0", "Exkee"}, {"N4", "Zoom"}, {"N7", "T&S"}, {"N9", "Tera Box"}, {"NA", "Tom Create"}, {"NB", "HI Games & Publishing"}, {"NE", "Kosaido"}, {"NF", "Peakvox"}, {"NG", "Nordic Games"}, {"NH", "Gevo Entertainment"}, {"NJ", "Enjoy Gaming"}, {"NK", "Neko Entertainment"}, {"NL", "Nordic Softsales"}, {"NN", "Nnooo"}, {"NP", "Nobilis"}, {"NQ", "Namco Bandai Partners"}, {"NR", "Destineer Publishing / Bold Games"}, {"NS", "Nippon Ichi Software America"}, {"NT", "Nocturnal Entertainment"}, {"NV", "Nicalis"}, {"NW", "Deep Fried Entertainment"}, {"NX", "Barnstorm Games"}, {"NY", "Nicalis"}, {"P1", "Poisoft"}, {"PH", "Playful Entertainment"}, {"PK", "Knowledge Adventure"}, {"PL", "Playlogic Entertainment"}, {"PM", "Warner Bros. Interactive Entertainment"}, {"PN", "P2 Games"}, {"PQ", "PopCap Games"}, {"PS", "Bplus"}, {"PT", "Firemint"}, {"PU", "Pub Company"}, {"PV", "Pan Vision"}, {"PY", "Playstos Entertainment"}, {"PZ", "GameMill Publishing"}, {"Q2", "Santa Entertainment"}, {"Q3", "Asterizm"}, {"Q4", "Hamster"}, {"Q5", "Recom"}, {"QA", "Miracle Kidz"}, {"QC", "Kadokawa Shoten / Enterbrain"}, {"QH", "Virtual Play Games"}, {"QK", "MACHINE Studios"}, {"QM", "Object Vision Software"}, {"QQ", "Gamelion"}, {"QR", "Lapland Studio"}, {"QT", "CALARIS"}, {"QU", "QubicGames"}, {"QV", "Ludia"}, {"QW", "Kaasa Solution"}, {"QX", "Press Play"}, {"QZ", "Hands-On Mobile"}, {"RA", "Office Create"}, {"RG", "Ronimo Games"}, {"RH", "h2f Games"}, {"RM", "Rondomedia"}, {"RN", "Mastiff / N3V Games"}, {"RQ", "GolemLabs & Zoozen"}, {"RS", "Brash Entertainment"}, {"RT", "RTL Enterprises"}, {"RV", "bitComposer Games"}, {"RW", "RealArcade"}, {"RX", "Reflexive Entertainment"}, {"RZ", "Akaoni Studio"}, {"S5", "SouthPeak Games"}, {"SH", "Sabarasa"}, {"SJ", "Cosmonaut Games"}, {"SP", "Blade Interactive Studios"}, {"SQ", "Sonalysts"}, {"SR", "SnapDragon Games"}, {"SS", "Sanuk Games"}, {"ST", "Stickmen Studios"}, {"SU", "Slitherine"}, {"SV", "SevenOne Intermedia"}, {"SZ", "Storm City Games"}, {"TH", "Kolkom"}, {"TJ", "Broken Rules"}, {"TL", "Telltale Games"}, {"TR", "Tetris Online"}, {"TS", "Triangle Studios"}, {"TV", "Tivola"}, {"TW", "Two Tribes"}, {"TY", "Teyon"}, {"UG", "Data Design Interactive / Popcorn Arcade / Metro 3D"}, {"UH", "Intenium Console"}, {"UJ", "Ghostlight"}, {"UK", "iFun4all"}, {"UN", "Chillingo"}, {"UP", "EnjoyUp Games"}, {"UR", "Sudden Games"}, {"US", "USM"}, {"UU", "Onteca"}, {"UV", "Fugazo"}, {"UW", "Coresoft"}, {"VG", "Vogster Entertainment"}, {"VK", "Sandlot Games"}, {"VL", "Eko Software"}, {"VN", "Valcon Games"}, {"VP", "Virgin Play"}, {"VS", "Korner Entertainment"}, {"VT", "Microforum Games"}, {"VU", "Double Jungle"}, {"VV", "Pixonauts"}, {"VX", "Frontline Studios"}, {"VZ", "Little Orbit"}, {"WD", "Amazon"}, {"WG", "2D Boy"}, {"WH", "NinjaBee"}, {"WJ", "Studio Walljump"}, {"WL", "Wired Productions"}, {"WN", "tons of bits"}, {"WP", "White Park Bay Software"}, {"WQ", "Revistronic"}, {"WR", "Warner Bros. Interactive Entertainment"}, {"WS", "MonkeyPaw Games"}, {"WW", "Slang Publishing"}, {"WY", "WayForward Technologies"}, {"WZ", "Wizarbox"}, {"X0", "SDP Games"}, {"X3", "CK Games"}, {"X4", "Easy Interactive"}, {"XB", "Hulu"}, {"XG", "XGen Studios"}, {"XJ", "XSEED Games"}, {"XK", "Exkee"}, {"XM", "DreamBox Games"}, {"XN", "Netflix"}, {"XS", "Aksys Games"}, {"XT", "Funbox Media"}, {"XU", "Shanblue Interactive"}, {"XV", "Keystone Game Studio"}, {"XW", "Lemon Games"}, {"XY", "Gaijin Games"}, {"Y1", "Tubby Games"}, {"Y5", "Easy Interactive"}, {"Y6", "Motiviti"}, {"Y7", "The Learning Company"}, {"Y9", "RadiationBurn"}, {"YC", "NECA"}, {"YD", "Infinite Dreams"}, {"YF", "O2 Games"}, {"YG", "Maximum Family Games"}, {"YJ", "Frozen Codebase"}, {"YK", "MAD Multimedia"}, {"YN", "Game Factory"}, {"YS", "Yullaby"}, {"YT", "Corecell Technology"}, {"YV", "KnapNok Games"}, {"YX", "Selectsoft"}, {"YY", "FDG Entertainment"}, {"Z4", "Ntreev Soft"}, {"Z5", "Shinsegae I&C"}, {"ZA", "WBA Interactive"}, {"ZG", "Zallag"}, {"ZH", "Internal Engine"}, {"ZJ", "Performance Designed Products"}, {"ZK", "Anima Game Studio"}, {"ZP", "Fishing Cactus"}, {"ZS", "Zinkia Entertainment"}, {"ZV", "RedLynx"}, {"ZW", "Judo Baby"}, {"ZX", "TopWare Interactive"}}; static const std::string EMPTY_STRING; auto iterator = companies.find(company_id); if (iterator != companies.end()) return iterator->second; else return EMPTY_STRING; } } // namespace DiscIO
gpl-2.0
tonvinh/ez
ezpublish_legacy/extension/ngsymfonytools/classes/ngsymfonytoolscontrolleroperator.php
3547
<?php use Symfony\Component\HttpKernel\Controller\ControllerReference; class NgSymfonyToolsControllerOperator { /** * Returns the list of template operators this class supports * * @return array */ function operatorList() { return array( 'symfony_controller' ); } /** * Indicates if the template operators have named parameters * * @return bool */ function namedParameterPerOperator() { return true; } /** * Returns the list of template operator parameters * * @return array */ function namedParameterList() { return array( 'symfony_controller' => array( 'controller' => array( 'type' => 'string', 'required' => true ), 'attributes' => array( 'type' => 'array', 'required' => false, 'default' => array() ), 'query' => array( 'type' => 'array', 'required' => false, 'default' => array() ) ) ); } /** * Executes the template operator * * @param eZTemplate $tpl * @param string $operatorName * @param mixed $operatorParameters * @param string $rootNamespace * @param string $currentNamespace * @param mixed $operatorValue * @param array $namedParameters * @param mixed $placement */ function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement ) { if ( !is_string( $namedParameters['controller'] ) && empty( $namedParameters['controller'] ) ) { $tpl->error( $operatorName, "$operatorName parameter 'controller' must be a non empty string.", $placement ); return; } $controller = $namedParameters['controller']; if ( $namedParameters['attributes'] !== null && !is_array( $namedParameters['attributes'] ) ) { $tpl->error( $operatorName, "$operatorName parameter 'attributes' must be a hash array.", $placement ); return; } $attributes = $namedParameters['attributes'] !== null ? $namedParameters['attributes'] : array(); if ( $namedParameters['query'] !== null && !is_array( $namedParameters['query'] ) ) { $tpl->error( $operatorName, "$operatorName parameter 'query' must be a hash array.", $placement ); return; } $query = $namedParameters['query'] !== null ? $namedParameters['query'] : array(); $apiContentConverter = NgSymfonyToolsApiContentConverter::instance(); foreach ( $attributes as $attributeName => $attributeValue ) { $attributes[$attributeName] = $apiContentConverter->convert( $attributeValue ); } $operatorValue = self::getController( $controller, $attributes, $query ); } /** * Returns the controller reference for the specified controller name * * @param string $controller * @param array $attributes * @param array $query * * @return \Symfony\Component\HttpKernel\Controller\ControllerReference */ public static function getController( $controller, $attributes = array(), $query = array() ) { return new ControllerReference( $controller, $attributes, $query ); } }
gpl-2.0
mzmine/mzmine2
src/main/java/net/sf/mzmine/modules/tools/mzrangecalculator/MzRangeMassCalculatorModule.java
2616
/* * Copyright 2006-2018 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with MZmine 2; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.sf.mzmine.modules.tools.mzrangecalculator; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.Range; import net.sf.mzmine.main.MZmineCore; import net.sf.mzmine.modules.MZmineModule; import net.sf.mzmine.parameters.ParameterSet; import net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance; import net.sf.mzmine.util.ExitCode; /** * m/z range calculator module. Calculates m/z range from a given mass and m/z tolerance. */ public class MzRangeMassCalculatorModule implements MZmineModule { private static final String MODULE_NAME = "m/z range calculator from formula"; @Override public @Nonnull String getName() { return MODULE_NAME; } @Override public @Nonnull Class<? extends ParameterSet> getParameterSetClass() { return MzRangeMassCalculatorParameters.class; } /** * Shows the calculation dialog and returns the calculated m/z range. May return null in case user * clicked Cancel. */ @Nullable public static Range<Double> showRangeCalculationDialog() { ParameterSet myParameters = MZmineCore.getConfiguration().getModuleParameters(MzRangeMassCalculatorModule.class); if (myParameters == null) return null; ExitCode exitCode = myParameters.showSetupDialog(null, true); if (exitCode != ExitCode.OK) return null; Double mz = myParameters.getParameter(MzRangeMassCalculatorParameters.mz).getValue(); MZTolerance mzTolerance = myParameters.getParameter(MzRangeMassCalculatorParameters.mzTolerance).getValue(); if ((mz == null) || (mzTolerance == null)) return null; Range<Double> mzRange = mzTolerance.getToleranceRange(mz); return mzRange; } }
gpl-2.0
SuriyaaKudoIsc/wikia-app-test
lib/vendor/php-nlp-tools/documents/training_document.php
662
<?php namespace NlpTools\Documents; /** * A TrainingDocument is a document that "decorates" any other document * to add the real class of the document. It is used while training * together with the training set. */ class TrainingDocument implements Document { protected $d; protected $class; /** * @param string $class The actual class of the Document $d * @param Document $d The document to be decorated */ public function __construct($class, Document $d) { $this->d = $d; $this->class = $class; } public function getDocumentData() { return $this->d->getDocumentData(); } public function getClass() { return $this->class; } } ?>
gpl-2.0
rex-xxx/mt6572_x201
frameworks/wilhelm/src/android/BufferQueueSource.cpp
6355
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //#define USE_LOG SLAndroidLogLevel_Verbose #include "sles_allinclusive.h" #include "android/BufferQueueSource.h" #include <media/stagefright/foundation/ADebug.h> #include <sys/types.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> namespace android { const SLuint32 BufferQueueSource::kItemProcessed[NB_BUFFEREVENT_ITEM_FIELDS] = { SL_ANDROID_ITEMKEY_BUFFERQUEUEEVENT, // item key sizeof(SLuint32), // item size SL_ANDROIDBUFFERQUEUEEVENT_PROCESSED // item data }; BufferQueueSource::BufferQueueSource(IAndroidBufferQueue *androidBufferQueue) : mAndroidBufferQueueSource(androidBufferQueue), mStreamToBqOffset(0), mEosReached(false) { } BufferQueueSource::~BufferQueueSource() { SL_LOGD("BufferQueueSource::~BufferQueueSource"); } //-------------------------------------------------------------------------- status_t BufferQueueSource::initCheck() const { return mAndroidBufferQueueSource != NULL ? OK : NO_INIT; } ssize_t BufferQueueSource::readAt(off64_t offset, void *data, size_t size) { SL_LOGD("BufferQueueSource::readAt(offset=%lld, data=%p, size=%d)", offset, data, size); if (mEosReached) { // once EOS has been received from the buffer queue, you can't read anymore return 0; } ssize_t readSize; slAndroidBufferQueueCallback callback = NULL; void* pBufferContext, *pBufferData, *callbackPContext; uint32_t dataSize, dataUsed; interface_lock_exclusive(mAndroidBufferQueueSource); if (mAndroidBufferQueueSource->mState.count == 0) { readSize = 0; } else { assert(mAndroidBufferQueueSource->mFront != mAndroidBufferQueueSource->mRear); AdvancedBufferHeader *oldFront = mAndroidBufferQueueSource->mFront; AdvancedBufferHeader *newFront = &oldFront[1]; // where to read from char *pSrc = NULL; // can this read operation cause us to call the buffer queue callback // (either because there was a command with no data, or all the data has been consumed) bool queueCallbackCandidate = false; // consume events when starting to read data from a buffer for the first time if (oldFront->mDataSizeConsumed == 0) { if (oldFront->mItems.mAdtsCmdData.mAdtsCmdCode & ANDROID_ADTSEVENT_EOS) { mEosReached = true; // EOS has no associated data queueCallbackCandidate = true; } oldFront->mItems.mAdtsCmdData.mAdtsCmdCode = ANDROID_ADTSEVENT_NONE; } //assert(mStreamToBqOffset <= offset); CHECK_LE(mStreamToBqOffset, offset); if (offset + size <= mStreamToBqOffset + oldFront->mDataSize) { pSrc = ((char*)oldFront->mDataBuffer) + (offset - mStreamToBqOffset); if (offset - mStreamToBqOffset + size == oldFront->mDataSize) { // consumed buffer entirely oldFront->mDataSizeConsumed = oldFront->mDataSize; mStreamToBqOffset += oldFront->mDataSize; queueCallbackCandidate = true; // move queue to next buffer if (newFront == &mAndroidBufferQueueSource-> mBufferArray[mAndroidBufferQueueSource->mNumBuffers + 1]) { // reached the end, circle back newFront = mAndroidBufferQueueSource->mBufferArray; } mAndroidBufferQueueSource->mFront = newFront; // update the queue state mAndroidBufferQueueSource->mState.count--; mAndroidBufferQueueSource->mState.index++; SL_LOGV("BufferQueueSource moving to next buffer"); } } // consume data: copy to given destination if (NULL != pSrc) { memcpy(data, pSrc, size); readSize = size; } else { readSize = 0; } if (queueCallbackCandidate) { // data has been consumed, and the buffer queue state has been updated // we will notify the client if applicable if (mAndroidBufferQueueSource->mCallbackEventsMask & SL_ANDROIDBUFFERQUEUEEVENT_PROCESSED) { callback = mAndroidBufferQueueSource->mCallback; // save callback data while under lock callbackPContext = mAndroidBufferQueueSource->mContext; pBufferContext = (void *)oldFront->mBufferContext; pBufferData = (void *)oldFront->mDataBuffer; dataSize = oldFront->mDataSize; dataUsed = oldFront->mDataSizeConsumed; } } } interface_unlock_exclusive(mAndroidBufferQueueSource); // notify client if (NULL != callback) { SLresult result = (*callback)(&mAndroidBufferQueueSource->mItf, callbackPContext, pBufferContext, pBufferData, dataSize, dataUsed, // no messages during playback other than marking the buffer as processed (const SLAndroidBufferItem*)(&kItemProcessed) /* pItems */, NB_BUFFEREVENT_ITEM_FIELDS * sizeof(SLuint32) /* itemsLength */ ); if (SL_RESULT_SUCCESS != result) { // Reserved for future use SL_LOGW("Unsuccessful result %d returned from AndroidBufferQueueCallback", result); } } return readSize; } status_t BufferQueueSource::getSize(off64_t *size) { SL_LOGD("BufferQueueSource::getSize()"); // we're streaming, we don't know how much there is *size = 0; return ERROR_UNSUPPORTED; } } // namespace android
gpl-2.0
futurice/vdsm
vdsm_hooks/nestedvt/before_vm_start.py
1521
#!/usr/bin/python # # Copyright 2012 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # import hooking cpu_nested_features = { "kvm_intel": "vmx", "kvm_amd": "svm", } for kvm_mod in ("kvm_intel", "kvm_amd"): kvm_mod_path = "/sys/module/%s/parameters/nested" % kvm_mod try: with file(kvm_mod_path) as f: if f.readline().strip() in ("Y", "1"): break except IOError: pass else: kvm_mod = None if kvm_mod: domxml = hooking.read_domxml() feature_vmx = domxml.createElement("feature") feature_vmx.setAttribute("name", cpu_nested_features[kvm_mod]) feature_vmx.setAttribute("policy", "require") domxml.getElementsByTagName("cpu")[0].appendChild(feature_vmx) hooking.write_domxml(domxml)
gpl-2.0
ReichardtIT/modified-inkl-bootstrap-by-karl
lang/german/modules/shipping/dp.php
5734
<?php /* ----------------------------------------------------------------------------------------- $Id: dp.php 899 2005-04-29 02:40:57Z hhgag $ XT-Commerce - community made shopping http://www.xt-commerce.com Copyright (c) 2003 XT-Commerce ----------------------------------------------------------------------------------------- based on: (c) 2000-2001 The Exchange Project (earlier name of osCommerce) (c) 2002-2003 osCommerce(dp.php,v 1.4 2003/02/18 04:28:00); www.oscommerce.com (c) 2003 nextcommerce (dp.php,v 1.5 2003/08/13); www.nextcommerce.org Released under the GNU General Public License ----------------------------------------------------------------------------------------- Third Party contributions: German Post (Deutsche Post WorldNet) Autor: Copyright (C) 2002 - 2003 TheMedia, Dipl.-Ing Thomas Plänkers | http://www.themedia.at & http://www.oscommerce.at Released under the GNU General Public License ---------------------------------------------------------------------------------------*/ define('MODULE_SHIPPING_DP_TEXT_TITLE', 'Deutsche Post'); define('MODULE_SHIPPING_DP_TEXT_DESCRIPTION', 'Deutsche Post - Weltweites Versandmodul'); define('MODULE_SHIPPING_DP_TEXT_WAY', 'Versand nach'); define('MODULE_SHIPPING_DP_TEXT_UNITS', 'kg'); define('MODULE_SHIPPING_DP_INVALID_ZONE', 'Es ist leider kein Versand in dieses Land m&ouml;glich'); define('MODULE_SHIPPING_DP_UNDEFINED_RATE', 'Die Versandkosten k&ouml;nnen im Moment nicht errechnet werden'); define('MODULE_SHIPPING_DP_STATUS_TITLE' , 'Deutsche Post WorldNet'); define('MODULE_SHIPPING_DP_STATUS_DESC' , 'Wollen Sie den Versand &uuml;ber die deutsche Post anbieten?'); define('MODULE_SHIPPING_DP_HANDLING_TITLE' , 'Handling Fee'); define('MODULE_SHIPPING_DP_HANDLING_DESC' , 'Bearbeitungsgeb&uuml;hr f&uuml;r diese Versandart in Euro'); define('MODULE_SHIPPING_DP_TAX_CLASS_TITLE' , 'Steuersatz'); define('MODULE_SHIPPING_DP_TAX_CLASS_DESC' , 'W&auml;hlen Sie den MwSt.-Satz f&uuml;r diese Versandart aus.'); define('MODULE_SHIPPING_DP_ZONE_TITLE' , 'Versand Zone'); define('MODULE_SHIPPING_DP_ZONE_DESC' , 'Wenn Sie eine Zone ausw&auml;hlen, wird diese Versandart nur in dieser Zone angeboten.'); define('MODULE_SHIPPING_DP_SORT_ORDER_TITLE' , 'Reihenfolge der Anzeige'); define('MODULE_SHIPPING_DP_SORT_ORDER_DESC' , 'Niedrigste wird zuerst angezeigt.'); define('MODULE_SHIPPING_DP_ALLOWED_TITLE' , 'Einzelne Versandzonen'); define('MODULE_SHIPPING_DP_ALLOWED_DESC' , 'Geben Sie <b>einzeln</b> die Zonen an, in welche ein Versand m&ouml;glich sein soll. zb AT,DE'); define('MODULE_SHIPPING_DP_COUNTRIES_1_TITLE' , 'DP Zone 1 Countries'); define('MODULE_SHIPPING_DP_COUNTRIES_1_DESC' , 'Comma separated list of two character ISO country codes that are part of Zone 1'); define('MODULE_SHIPPING_DP_COST_1_TITLE' , 'DP Zone 1 Shipping Table'); define('MODULE_SHIPPING_DP_COST_1_DESC' , 'Shipping rates to Zone 1 destinations based on a range of order weights. Example: 0-3:8.50,3-7:10.50,... Weights greater than 0 and less than or equal to 3 would cost 14.57 for Zone 1 destinations.'); define('MODULE_SHIPPING_DP_COUNTRIES_2_TITLE' , 'DP Zone 2 Countries'); define('MODULE_SHIPPING_DP_COUNTRIES_2_DESC' , 'Comma separated list of two character ISO country codes that are part of Zone 2'); define('MODULE_SHIPPING_DP_COST_2_TITLE' , 'DP Zone 2 Shipping Table'); define('MODULE_SHIPPING_DP_COST_2_DESC' , 'Shipping rates to Zone 2 destinations based on a range of order weights. Example: 0-3:8.50,3-7:10.50,... Weights greater than 0 and less than or equal to 3 would cost 23.78 for Zone 2 destinations.'); define('MODULE_SHIPPING_DP_COUNTRIES_3_TITLE' , 'DP Zone 3 Countries'); define('MODULE_SHIPPING_DP_COUNTRIES_3_DESC' , 'Comma separated list of two character ISO country codes that are part of Zone 3'); define('MODULE_SHIPPING_DP_COST_3_TITLE' , 'DP Zone 3 Shipping Table'); define('MODULE_SHIPPING_DP_COST_3_DESC' , 'Shipping rates to Zone 3 destinations based on a range of order weights. Example: 0-3:8.50,3-7:10.50,... Weights greater than 0 and less than or equal to 3 would cost 26.84 for Zone 3 destinations.'); define('MODULE_SHIPPING_DP_COUNTRIES_4_TITLE' , 'DP Zone 4 Countries'); define('MODULE_SHIPPING_DP_COUNTRIES_4_DESC' , 'Comma separated list of two character ISO country codes that are part of Zone 4'); define('MODULE_SHIPPING_DP_COST_4_TITLE' , 'DP Zone 4 Shipping Table'); define('MODULE_SHIPPING_DP_COST_4_DESC' , 'Shipping rates to Zone 4 destinations based on a range of order weights. Example: 0-3:8.50,3-7:10.50,... Weights greater than 0 and less than or equal to 3 would cost 32.98 for Zone 4 destinations.'); define('MODULE_SHIPPING_DP_COUNTRIES_5_TITLE' , 'DP Zone 5 Countries'); define('MODULE_SHIPPING_DP_COUNTRIES_5_DESC' , 'Comma separated list of two character ISO country codes that are part of Zone 5'); define('MODULE_SHIPPING_DP_COST_5_TITLE' , 'DP Zone 5 Shipping Table'); define('MODULE_SHIPPING_DP_COST_5_DESC' , 'Shipping rates to Zone 5 destinations based on a range of order weights. Example: 0-3:8.50,3-7:10.50,... Weights greater than 0 and less than or equal to 3 would cost 32.98 for Zone 5 destinations.'); define('MODULE_SHIPPING_DP_COUNTRIES_6_TITLE' , 'DP Zone 6 Countries'); define('MODULE_SHIPPING_DP_COUNTRIES_6_DESC' , 'Comma separated list of two character ISO country codes that are part of Zone 6'); define('MODULE_SHIPPING_DP_COST_6_TITLE' , 'DP Zone 6 Shipping Table'); define('MODULE_SHIPPING_DP_COST_6_DESC' , 'Shipping rates to Zone 6 destinations based on a range of order weights. Example: 0-3:8.50,3-7:10.50,... Weights greater than 0 and less than or equal to 3 would cost 5.62 for Zone 6 destinations.'); ?>
gpl-2.0
vanasisf/DeathCore_4.3.4
src/server/game/AI/SmartScripts/SmartScriptMgr.cpp
60495
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "DatabaseEnv.h" #include "ObjectMgr.h" #include "ObjectDefines.h" #include "GridDefines.h" #include "GridNotifiers.h" #include "SpellMgr.h" #include "GridNotifiersImpl.h" #include "Cell.h" #include "CellImpl.h" #include "InstanceScript.h" #include "ScriptedCreature.h" #include "GameEventMgr.h" #include "CreatureTextMgr.h" #include "SpellMgr.h" #include "SpellInfo.h" #include "SmartScriptMgr.h" void SmartWaypointMgr::LoadFromDB() { uint32 oldMSTime = getMSTime(); for (std::unordered_map<uint32, WPPath*>::iterator itr = waypoint_map.begin(); itr != waypoint_map.end(); ++itr) { for (WPPath::iterator pathItr = itr->second->begin(); pathItr != itr->second->end(); ++pathItr) delete pathItr->second; delete itr->second; } waypoint_map.clear(); PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_SMARTAI_WP); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) { TC_LOG_INFO("server.loading", ">> Loaded 0 SmartAI Waypoint Paths. DB table `waypoints` is empty."); return; } uint32 count = 0; uint32 total = 0; uint32 last_entry = 0; uint32 last_id = 1; do { Field* fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); uint32 id = fields[1].GetUInt32(); float x, y, z; x = fields[2].GetFloat(); y = fields[3].GetFloat(); z = fields[4].GetFloat(); if (last_entry != entry) { waypoint_map[entry] = new WPPath(); last_id = 1; count++; } if (last_id != id) TC_LOG_ERROR("sql.sql", "SmartWaypointMgr::LoadFromDB: Path entry %u, unexpected point id %u, expected %u.", entry, id, last_id); last_id++; (*waypoint_map[entry])[id] = new WayPoint(id, x, y, z); last_entry = entry; total++; } while (result->NextRow()); TC_LOG_INFO("server.loading", ">> Loaded %u SmartAI waypoint paths (total %u waypoints) in %u ms", count, total, GetMSTimeDiffToNow(oldMSTime)); } SmartWaypointMgr::~SmartWaypointMgr() { for (std::unordered_map<uint32, WPPath*>::iterator itr = waypoint_map.begin(); itr != waypoint_map.end(); ++itr) { for (WPPath::iterator pathItr = itr->second->begin(); pathItr != itr->second->end(); ++pathItr) delete pathItr->second; delete itr->second; } } void SmartAIMgr::LoadSmartAIFromDB() { LoadHelperStores(); uint32 oldMSTime = getMSTime(); for (uint8 i = 0; i < SMART_SCRIPT_TYPE_MAX; i++) mEventMap[i].clear(); //Drop Existing SmartAI List PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_SMART_SCRIPTS); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) { TC_LOG_INFO("server.loading", ">> Loaded 0 SmartAI scripts. DB table `smartai_scripts` is empty."); return; } uint32 count = 0; do { Field* fields = result->Fetch(); SmartScriptHolder temp; temp.entryOrGuid = fields[0].GetInt32(); SmartScriptType source_type = (SmartScriptType)fields[1].GetUInt8(); if (source_type >= SMART_SCRIPT_TYPE_MAX) { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: invalid source_type (%u), skipped loading.", uint32(source_type)); continue; } if (temp.entryOrGuid >= 0) { switch (source_type) { case SMART_SCRIPT_TYPE_CREATURE: { CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate((uint32)temp.entryOrGuid); if (!creatureInfo) { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Creature entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); continue; } if (creatureInfo->AIName != "SmartAI") { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Creature entry (%u) is not using SmartAI, skipped loading.", uint32(temp.entryOrGuid)); continue; } break; } case SMART_SCRIPT_TYPE_GAMEOBJECT: { GameObjectTemplate const* gameObjectInfo = sObjectMgr->GetGameObjectTemplate((uint32)temp.entryOrGuid); if (!gameObjectInfo) { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: GameObject entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); continue; } if (gameObjectInfo->AIName != "SmartGameObjectAI") { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: GameObject entry (%u) is not using SmartGameObjectAI, skipped loading.", uint32(temp.entryOrGuid)); continue; } break; } case SMART_SCRIPT_TYPE_AREATRIGGER: { if (!sAreaTriggerStore.LookupEntry((uint32)temp.entryOrGuid)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: AreaTrigger entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); continue; } break; } case SMART_SCRIPT_TYPE_TIMED_ACTIONLIST: break;//nothing to check, really default: TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: not yet implemented source_type %u", (uint32)source_type); continue; } } else { CreatureData const* creature = sObjectMgr->GetCreatureData(uint32(std::abs(temp.entryOrGuid))); if (!creature) { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Creature guid (%u) does not exist, skipped loading.", uint32(std::abs(temp.entryOrGuid))); continue; } CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(creature->id); if (!creatureInfo) { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Creature entry (%u) guid (%u) does not exist, skipped loading.", creature->id, uint32(std::abs(temp.entryOrGuid))); continue; } if (creatureInfo->AIName != "SmartAI") { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Creature entry (%u) guid (%u) is not using SmartAI, skipped loading.", creature->id, uint32(std::abs(temp.entryOrGuid))); continue; } } temp.source_type = source_type; temp.event_id = fields[2].GetUInt16(); temp.link = fields[3].GetUInt16(); temp.event.type = (SMART_EVENT)fields[4].GetUInt8(); temp.event.event_phase_mask = fields[5].GetUInt8(); temp.event.event_chance = fields[6].GetUInt8(); temp.event.event_flags = fields[7].GetUInt8(); temp.event.raw.param1 = fields[8].GetUInt32(); temp.event.raw.param2 = fields[9].GetUInt32(); temp.event.raw.param3 = fields[10].GetUInt32(); temp.event.raw.param4 = fields[11].GetUInt32(); temp.action.type = (SMART_ACTION)fields[12].GetUInt8(); temp.action.raw.param1 = fields[13].GetUInt32(); temp.action.raw.param2 = fields[14].GetUInt32(); temp.action.raw.param3 = fields[15].GetUInt32(); temp.action.raw.param4 = fields[16].GetUInt32(); temp.action.raw.param5 = fields[17].GetUInt32(); temp.action.raw.param6 = fields[18].GetUInt32(); temp.target.type = (SMARTAI_TARGETS)fields[19].GetUInt8(); temp.target.raw.param1 = fields[20].GetUInt32(); temp.target.raw.param2 = fields[21].GetUInt32(); temp.target.raw.param3 = fields[22].GetUInt32(); temp.target.x = fields[23].GetFloat(); temp.target.y = fields[24].GetFloat(); temp.target.z = fields[25].GetFloat(); temp.target.o = fields[26].GetFloat(); //check target if (!IsTargetValid(temp)) continue; // check all event and action params if (!IsEventValid(temp)) continue; // creature entry / guid not found in storage, create empty event list for it and increase counters if (mEventMap[source_type].find(temp.entryOrGuid) == mEventMap[source_type].end()) { ++count; SmartAIEventList eventList; mEventMap[source_type][temp.entryOrGuid] = eventList; } // store the new event mEventMap[source_type][temp.entryOrGuid].push_back(temp); } while (result->NextRow()); // Post Loading Validation for (uint8 i = 0; i < SMART_SCRIPT_TYPE_MAX; ++i) { for (SmartAIEventMap::iterator itr = mEventMap[i].begin(); itr != mEventMap[i].end(); ++itr) { for (SmartScriptHolder const& e : itr->second) { if (e.link) { if (!FindLinkedEvent(itr->second, e.link)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Entry %d SourceType %u, Event %u, Link Event %u not found or invalid.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.link); } } if (e.GetEventType() == SMART_EVENT_LINK) { if (!FindLinkedSourceEvent(itr->second, e.event_id)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Entry %d SourceType %u, Event %u, Link Source Event not found or invalid. Event will never trigger.", e.entryOrGuid, e.GetScriptType(), e.event_id); } } } } } TC_LOG_INFO("server.loading", ">> Loaded %u SmartAI scripts in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); UnLoadHelperStores(); } bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) { if (std::abs(e.target.o) > 2 * float(M_PI)) TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u has abs(`target.o` = %f) > 2*PI (orientation is expressed in radians)", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.o); if (e.GetActionType() == SMART_ACTION_INSTALL_AI_TEMPLATE) return true; // AI template has special handling switch (e.GetTargetType()) { case SMART_TARGET_CREATURE_DISTANCE: case SMART_TARGET_CREATURE_RANGE: { if (e.target.unitDistance.creature && !sObjectMgr->GetCreatureTemplate(e.target.unitDistance.creature)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.unitDistance.creature); return false; } break; } case SMART_TARGET_GAMEOBJECT_DISTANCE: case SMART_TARGET_GAMEOBJECT_RANGE: { if (e.target.goDistance.entry && !sObjectMgr->GetGameObjectTemplate(e.target.goDistance.entry)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.goDistance.entry); return false; } break; } case SMART_TARGET_CREATURE_GUID: { if (e.target.unitGUID.entry && !IsCreatureValid(e, e.target.unitGUID.entry)) return false; break; } case SMART_TARGET_GAMEOBJECT_GUID: { if (e.target.goGUID.entry && !IsGameObjectValid(e, e.target.goGUID.entry)) return false; break; } case SMART_TARGET_PLAYER_DISTANCE: case SMART_TARGET_CLOSEST_PLAYER: { if (e.target.playerDistance.dist == 0) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u has maxDist 0 as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } break; } case SMART_TARGET_PLAYER_RANGE: case SMART_TARGET_SELF: case SMART_TARGET_VICTIM: case SMART_TARGET_HOSTILE_SECOND_AGGRO: case SMART_TARGET_HOSTILE_LAST_AGGRO: case SMART_TARGET_HOSTILE_RANDOM: case SMART_TARGET_HOSTILE_RANDOM_NOT_TOP: case SMART_TARGET_ACTION_INVOKER: case SMART_TARGET_INVOKER_PARTY: case SMART_TARGET_POSITION: case SMART_TARGET_NONE: case SMART_TARGET_ACTION_INVOKER_VEHICLE: case SMART_TARGET_OWNER_OR_SUMMONER: case SMART_TARGET_THREAT_LIST: case SMART_TARGET_CLOSEST_GAMEOBJECT: case SMART_TARGET_CLOSEST_CREATURE: case SMART_TARGET_CLOSEST_ENEMY: case SMART_TARGET_CLOSEST_FRIENDLY: case SMART_TARGET_STORED: break; default: TC_LOG_ERROR("sql.sql", "SmartAIMgr: Not handled target_type(%u), Entry %d SourceType %u Event %u Action %u, skipped.", e.GetTargetType(), e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } return true; } bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.event.type >= SMART_EVENT_END) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid %d using event(%u) has invalid event type (%u), skipped.", e.entryOrGuid, e.event_id, e.GetEventType()); return false; } // in SMART_SCRIPT_TYPE_TIMED_ACTIONLIST all event types are overriden by core if (e.GetScriptType() != SMART_SCRIPT_TYPE_TIMED_ACTIONLIST && !(SmartAIEventMask[e.event.type][1] & SmartAITypeMask[e.GetScriptType()][1])) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid %d, event type %u can not be used for Script type %u", e.entryOrGuid, e.GetEventType(), e.GetScriptType()); return false; } if (e.action.type <= 0 || e.action.type >= SMART_ACTION_END) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid %d using event(%u) has invalid action type (%u), skipped.", e.entryOrGuid, e.event_id, e.GetActionType()); return false; } if (e.event.event_phase_mask > SMART_EVENT_PHASE_ALL) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid %d using event(%u) has invalid phase mask (%u), skipped.", e.entryOrGuid, e.event_id, e.event.event_phase_mask); return false; } if (e.event.event_flags > SMART_EVENT_FLAGS_ALL) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid %d using event(%u) has invalid event flags (%u), skipped.", e.entryOrGuid, e.event_id, e.event.event_flags); return false; } if (e.link && e.link == e.event_id) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid %d SourceType %u, Event %u, Event is linking self (infinite loop), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id); return false; } if (e.GetScriptType() == SMART_SCRIPT_TYPE_TIMED_ACTIONLIST) { e.event.type = SMART_EVENT_UPDATE_OOC;//force default OOC, can change when calling the script! if (!IsMinMaxValid(e, e.event.minMaxRepeat.min, e.event.minMaxRepeat.max)) return false; if (!IsMinMaxValid(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax)) return false; } else { switch (e.GetEventType()) { case SMART_EVENT_UPDATE: case SMART_EVENT_UPDATE_IC: case SMART_EVENT_UPDATE_OOC: case SMART_EVENT_HEALT_PCT: case SMART_EVENT_MANA_PCT: case SMART_EVENT_TARGET_HEALTH_PCT: case SMART_EVENT_TARGET_MANA_PCT: case SMART_EVENT_RANGE: case SMART_EVENT_DAMAGED: case SMART_EVENT_DAMAGED_TARGET: case SMART_EVENT_RECEIVE_HEAL: if (!IsMinMaxValid(e, e.event.minMaxRepeat.min, e.event.minMaxRepeat.max)) return false; if (!IsMinMaxValid(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax)) return false; break; case SMART_EVENT_SPELLHIT: case SMART_EVENT_SPELLHIT_TARGET: if (e.event.spellHit.spell) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(e.event.spellHit.spell); if (!spellInfo) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Spell entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.spellHit.spell); return false; } if (e.event.spellHit.school && (e.event.spellHit.school & spellInfo->SchoolMask) != spellInfo->SchoolMask) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses Spell entry %u with invalid school mask, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.spellHit.spell); return false; } } if (!IsMinMaxValid(e, e.event.spellHit.cooldownMin, e.event.spellHit.cooldownMax)) return false; break; case SMART_EVENT_OOC_LOS: case SMART_EVENT_IC_LOS: if (!IsMinMaxValid(e, e.event.los.cooldownMin, e.event.los.cooldownMax)) return false; break; case SMART_EVENT_RESPAWN: if (e.event.respawn.type == SMART_SCRIPT_RESPAWN_CONDITION_MAP && !sMapStore.LookupEntry(e.event.respawn.map)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Map entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.respawn.map); return false; } if (e.event.respawn.type == SMART_SCRIPT_RESPAWN_CONDITION_AREA && !GetAreaEntryByAreaID(e.event.respawn.area)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Area entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.respawn.area); return false; } break; case SMART_EVENT_FRIENDLY_HEALTH: if (!NotNULL(e, e.event.friendlyHealth.radius)) return false; if (!IsMinMaxValid(e, e.event.friendlyHealth.repeatMin, e.event.friendlyHealth.repeatMax)) return false; break; case SMART_EVENT_FRIENDLY_IS_CC: if (!IsMinMaxValid(e, e.event.friendlyCC.repeatMin, e.event.friendlyCC.repeatMax)) return false; break; case SMART_EVENT_FRIENDLY_MISSING_BUFF: { if (!IsSpellValid(e, e.event.missingBuff.spell)) return false; if (!NotNULL(e, e.event.missingBuff.radius)) return false; if (!IsMinMaxValid(e, e.event.missingBuff.repeatMin, e.event.missingBuff.repeatMax)) return false; break; } case SMART_EVENT_KILL: if (!IsMinMaxValid(e, e.event.kill.cooldownMin, e.event.kill.cooldownMax)) return false; if (e.event.kill.creature && !IsCreatureValid(e, e.event.kill.creature)) return false; break; case SMART_EVENT_VICTIM_CASTING: if (e.event.targetCasting.spellId > 0 && !sSpellMgr->GetSpellInfo(e.event.targetCasting.spellId)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Spell entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.spellHit.spell); return false; } if (!IsMinMaxValid(e, e.event.targetCasting.repeatMin, e.event.targetCasting.repeatMax)) return false; break; case SMART_EVENT_PASSENGER_BOARDED: case SMART_EVENT_PASSENGER_REMOVED: if (!IsMinMaxValid(e, e.event.minMax.repeatMin, e.event.minMax.repeatMax)) return false; break; case SMART_EVENT_SUMMON_DESPAWNED: case SMART_EVENT_SUMMONED_UNIT: if (e.event.summoned.creature && !IsCreatureValid(e, e.event.summoned.creature)) return false; if (!IsMinMaxValid(e, e.event.summoned.cooldownMin, e.event.summoned.cooldownMax)) return false; break; case SMART_EVENT_ACCEPTED_QUEST: case SMART_EVENT_REWARD_QUEST: if (e.event.quest.quest && !IsQuestValid(e, e.event.quest.quest)) return false; break; case SMART_EVENT_RECEIVE_EMOTE: { if (e.event.emote.emote && !IsTextEmoteValid(e, e.event.emote.emote)) return false; if (!IsMinMaxValid(e, e.event.emote.cooldownMin, e.event.emote.cooldownMax)) return false; break; } case SMART_EVENT_HAS_AURA: case SMART_EVENT_TARGET_BUFFED: { if (!IsSpellValid(e, e.event.aura.spell)) return false; if (!IsMinMaxValid(e, e.event.aura.repeatMin, e.event.aura.repeatMax)) return false; break; } case SMART_EVENT_TRANSPORT_ADDCREATURE: { if (e.event.transportAddCreature.creature && !IsCreatureValid(e, e.event.transportAddCreature.creature)) return false; break; } case SMART_EVENT_MOVEMENTINFORM: { if (e.event.movementInform.type > NULL_MOTION_TYPE) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid Motion type %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.movementInform.type); return false; } break; } case SMART_EVENT_DATA_SET: { if (!IsMinMaxValid(e, e.event.dataSet.cooldownMin, e.event.dataSet.cooldownMax)) return false; break; } case SMART_EVENT_AREATRIGGER_ONTRIGGER: { if (e.event.areatrigger.id && !IsAreaTriggerValid(e, e.event.areatrigger.id)) return false; break; } case SMART_EVENT_TEXT_OVER: if (!IsTextValid(e, e.event.textOver.textGroupID)) return false; break; case SMART_EVENT_DUMMY_EFFECT: { if (!IsSpellValid(e, e.event.dummy.spell)) return false; if (e.event.dummy.effIndex > EFFECT_2) return false; break; } case SMART_EVENT_IS_BEHIND_TARGET: { if (!IsMinMaxValid(e, e.event.behindTarget.cooldownMin, e.event.behindTarget.cooldownMax)) return false; break; } case SMART_EVENT_GAME_EVENT_START: case SMART_EVENT_GAME_EVENT_END: { GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); if (e.event.gameEvent.gameEventId >= events.size() || !events[e.event.gameEvent.gameEventId].isValid()) return false; break; } case SMART_EVENT_ACTION_DONE: { if (e.event.doAction.eventId > EVENT_CHARGE) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid event id %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.doAction.eventId); return false; } break; } case SMART_EVENT_FRIENDLY_HEALTH_PCT: if (!IsMinMaxValid(e, e.event.friendlyHealthPct.repeatMin, e.event.friendlyHealthPct.repeatMax)) return false; if (e.event.friendlyHealthPct.maxHpPct > 100 || e.event.friendlyHealthPct.minHpPct > 100) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u has pct value above 100, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } switch (e.GetTargetType()) { case SMART_TARGET_CREATURE_RANGE: case SMART_TARGET_CREATURE_GUID: case SMART_TARGET_CREATURE_DISTANCE: case SMART_TARGET_CLOSEST_CREATURE: case SMART_TARGET_CLOSEST_PLAYER: case SMART_TARGET_PLAYER_RANGE: case SMART_TARGET_PLAYER_DISTANCE: break; default: TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid target_type %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.GetTargetType()); return false; } break; case SMART_EVENT_DISTANCE_CREATURE: if (e.event.distance.guid == 0 && e.event.distance.entry == 0) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE did not provide creature guid or entry, skipped."); return false; } if (e.event.distance.guid != 0 && e.event.distance.entry != 0) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE provided both an entry and guid, skipped."); return false; } if (e.event.distance.guid != 0 && !sObjectMgr->GetCreatureData(e.event.distance.guid)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE using invalid creature guid %u, skipped.", e.event.distance.guid); return false; } if (e.event.distance.entry != 0 && !sObjectMgr->GetCreatureTemplate(e.event.distance.entry)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE using invalid creature entry %u, skipped.", e.event.distance.entry); return false; } break; case SMART_EVENT_DISTANCE_GAMEOBJECT: if (e.event.distance.guid == 0 && e.event.distance.entry == 0) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT did not provide gameobject guid or entry, skipped."); return false; } if (e.event.distance.guid != 0 && e.event.distance.entry != 0) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT provided both an entry and guid, skipped."); return false; } if (e.event.distance.guid != 0 && !sObjectMgr->GetGOData(e.event.distance.guid)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT using invalid gameobject guid %u, skipped.", e.event.distance.guid); return false; } if (e.event.distance.entry != 0 && !sObjectMgr->GetGameObjectTemplate(e.event.distance.entry)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT using invalid gameobject entry %u, skipped.", e.event.distance.entry); return false; } break; case SMART_EVENT_LINK: case SMART_EVENT_GO_STATE_CHANGED: case SMART_EVENT_GO_EVENT_INFORM: case SMART_EVENT_TIMED_EVENT_TRIGGERED: case SMART_EVENT_INSTANCE_PLAYER_ENTER: case SMART_EVENT_TRANSPORT_RELOCATE: case SMART_EVENT_CHARMED: case SMART_EVENT_CHARMED_TARGET: case SMART_EVENT_CORPSE_REMOVED: case SMART_EVENT_AI_INIT: case SMART_EVENT_TRANSPORT_ADDPLAYER: case SMART_EVENT_TRANSPORT_REMOVE_PLAYER: case SMART_EVENT_AGGRO: case SMART_EVENT_DEATH: case SMART_EVENT_EVADE: case SMART_EVENT_REACHED_HOME: case SMART_EVENT_RESET: case SMART_EVENT_QUEST_ACCEPTED: case SMART_EVENT_QUEST_OBJ_COPLETETION: case SMART_EVENT_QUEST_COMPLETION: case SMART_EVENT_QUEST_REWARDED: case SMART_EVENT_QUEST_FAIL: case SMART_EVENT_JUST_SUMMONED: case SMART_EVENT_WAYPOINT_START: case SMART_EVENT_WAYPOINT_REACHED: case SMART_EVENT_WAYPOINT_PAUSED: case SMART_EVENT_WAYPOINT_RESUMED: case SMART_EVENT_WAYPOINT_STOPPED: case SMART_EVENT_WAYPOINT_ENDED: case SMART_EVENT_GOSSIP_SELECT: case SMART_EVENT_GOSSIP_HELLO: case SMART_EVENT_JUST_CREATED: case SMART_EVENT_FOLLOW_COMPLETED: case SMART_EVENT_ON_SPELLCLICK: break; default: TC_LOG_ERROR("sql.sql", "SmartAIMgr: Not handled event_type(%u), Entry %d SourceType %u Event %u Action %u, skipped.", e.GetEventType(), e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } } switch (e.GetActionType()) { case SMART_ACTION_TALK: case SMART_ACTION_SIMPLE_TALK: if (!IsTextValid(e, e.action.talk.textGroupID)) return false; break; case SMART_ACTION_SET_FACTION: if (e.action.faction.factionID && !sFactionTemplateStore.LookupEntry(e.action.faction.factionID)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Faction %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.faction.factionID); return false; } break; case SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: case SMART_ACTION_MOUNT_TO_ENTRY_OR_MODEL: if (e.action.morphOrMount.creature || e.action.morphOrMount.model) { if (e.action.morphOrMount.creature > 0 && !sObjectMgr->GetCreatureTemplate(e.action.morphOrMount.creature)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.morphOrMount.creature); return false; } if (e.action.morphOrMount.model) { if (e.action.morphOrMount.creature) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u has ModelID set with also set CreatureId, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } else if (!sCreatureDisplayInfoStore.LookupEntry(e.action.morphOrMount.model)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Model id %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.morphOrMount.model); return false; } } } break; case SMART_ACTION_SOUND: if (!IsSoundValid(e, e.action.sound.sound)) return false; break; case SMART_ACTION_SET_EMOTE_STATE: case SMART_ACTION_PLAY_EMOTE: if (!IsEmoteValid(e, e.action.emote.emote)) return false; break; case SMART_ACTION_FAIL_QUEST: case SMART_ACTION_ADD_QUEST: if (!e.action.quest.quest || !IsQuestValid(e, e.action.quest.quest)) return false; break; case SMART_ACTION_ACTIVATE_TAXI: { if (!sTaxiPathStore.LookupEntry(e.action.taxi.id)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid Taxi path ID %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.taxi.id); return false; } break; } case SMART_ACTION_RANDOM_EMOTE: if (e.action.randomEmote.emote1 && !IsEmoteValid(e, e.action.randomEmote.emote1)) return false; if (e.action.randomEmote.emote2 && !IsEmoteValid(e, e.action.randomEmote.emote2)) return false; if (e.action.randomEmote.emote3 && !IsEmoteValid(e, e.action.randomEmote.emote3)) return false; if (e.action.randomEmote.emote4 && !IsEmoteValid(e, e.action.randomEmote.emote4)) return false; if (e.action.randomEmote.emote5 && !IsEmoteValid(e, e.action.randomEmote.emote5)) return false; if (e.action.randomEmote.emote6 && !IsEmoteValid(e, e.action.randomEmote.emote6)) return false; break; case SMART_ACTION_CAST: { if (!IsSpellValid(e, e.action.cast.spell)) return false; SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(e.action.cast.spell); for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (spellInfo->Effects[j].IsEffect(SPELL_EFFECT_KILL_CREDIT) || spellInfo->Effects[j].IsEffect(SPELL_EFFECT_KILL_CREDIT2)) { if (spellInfo->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER) TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u Effect: SPELL_EFFECT_KILL_CREDIT: (SpellId: %u targetA: %u - targetB: %u) has invalid target for this Action", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.cast.spell, spellInfo->Effects[j].TargetA.GetTarget(), spellInfo->Effects[j].TargetB.GetTarget()); } } break; } case SMART_ACTION_ADD_AURA: case SMART_ACTION_INVOKER_CAST: if (!IsSpellValid(e, e.action.cast.spell)) return false; break; case SMART_ACTION_CALL_AREAEXPLOREDOREVENTHAPPENS: case SMART_ACTION_CALL_GROUPEVENTHAPPENS: if (Quest const* qid = sObjectMgr->GetQuestTemplate(e.action.quest.quest)) { if (!qid->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u SpecialFlags for Quest entry %u does not include FLAGS_EXPLORATION_OR_EVENT(2), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.quest.quest); return false; } } else { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Quest entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.quest.quest); return false; } break; case SMART_ACTION_SET_EVENT_PHASE: if (e.action.setEventPhase.phase >= SMART_EVENT_PHASE_MAX) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set phase %u. Phase mask cannot be used past phase %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setEventPhase.phase, SMART_EVENT_PHASE_MAX-1); return false; } break; case SMART_ACTION_INC_EVENT_PHASE: if (!e.action.incEventPhase.inc && !e.action.incEventPhase.dec) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u is incrementing phase by 0, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } else if (e.action.incEventPhase.inc > SMART_EVENT_PHASE_MAX || e.action.incEventPhase.dec > SMART_EVENT_PHASE_MAX) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to increment phase by too large value, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } break; case SMART_ACTION_REMOVEAURASFROMSPELL: if (e.action.removeAura.spell != 0 && !IsSpellValid(e, e.action.removeAura.spell)) return false; break; case SMART_ACTION_RANDOM_PHASE: { if (e.action.randomPhase.phase1 >= SMART_EVENT_PHASE_MAX || e.action.randomPhase.phase2 >= SMART_EVENT_PHASE_MAX || e.action.randomPhase.phase3 >= SMART_EVENT_PHASE_MAX || e.action.randomPhase.phase4 >= SMART_EVENT_PHASE_MAX || e.action.randomPhase.phase5 >= SMART_EVENT_PHASE_MAX || e.action.randomPhase.phase6 >= SMART_EVENT_PHASE_MAX) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } } break; case SMART_ACTION_RANDOM_PHASE_RANGE: //PhaseMin, PhaseMax { if (e.action.randomPhaseRange.phaseMin >= SMART_EVENT_PHASE_MAX || e.action.randomPhaseRange.phaseMax >= SMART_EVENT_PHASE_MAX) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } if (!IsMinMaxValid(e, e.action.randomPhaseRange.phaseMin, e.action.randomPhaseRange.phaseMax)) return false; break; } case SMART_ACTION_SUMMON_CREATURE: { if (!IsCreatureValid(e, e.action.summonCreature.creature)) return false; CacheSpellContainerBounds sBounds = GetSummonCreatureSpellContainerBounds(e.action.summonCreature.creature); for (CacheSpellContainer::const_iterator itr = sBounds.first; itr != sBounds.second; ++itr) TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u creature summon: There is a summon spell for creature entry %u (SpellId: %u, effect: %u)", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.summonCreature.creature, itr->second.first, itr->second.second); if (e.action.summonCreature.type < TEMPSUMMON_TIMED_OR_DEAD_DESPAWN || e.action.summonCreature.type > TEMPSUMMON_MANUAL_DESPAWN) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses incorrect TempSummonType %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.summonCreature.type); return false; } break; } case SMART_ACTION_CALL_KILLEDMONSTER: { if (!IsCreatureValid(e, e.action.killedMonster.creature)) return false; CacheSpellContainerBounds sBounds = GetKillCreditSpellContainerBounds(e.action.killedMonster.creature); for (CacheSpellContainer::const_iterator itr = sBounds.first; itr != sBounds.second; ++itr) TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u Kill Credit: There is a killcredit spell for creatureEntry %u (SpellId: %u effect: %u)", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.killedMonster.creature, itr->second.first, itr->second.second); if (e.GetTargetType() == SMART_TARGET_POSITION) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses incorrect TargetType %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.GetTargetType()); return false; } break; } case SMART_ACTION_UPDATE_TEMPLATE: if (!IsCreatureValid(e, e.action.updateTemplate.creature)) return false; break; case SMART_ACTION_SET_SHEATH: if (e.action.setSheath.sheath && e.action.setSheath.sheath >= MAX_SHEATH_STATE) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses incorrect Sheath state %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setSheath.sheath); return false; } break; case SMART_ACTION_SET_REACT_STATE: { if (e.action.react.state > REACT_AGGRESSIVE) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Creature %d Event %u Action %u uses invalid React State %u, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.react.state); return false; } break; } case SMART_ACTION_SUMMON_GO: { if (!IsGameObjectValid(e, e.action.summonGO.entry)) return false; CacheSpellContainerBounds sBounds = GetSummonGameObjectSpellContainerBounds(e.action.summonGO.entry); for (CacheSpellContainer::const_iterator itr = sBounds.first; itr != sBounds.second; ++itr) TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u gameobject summon: There is a summon spell for gameobject entry %u (SpellId: %u, effect: %u)", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.summonGO.entry, itr->second.first, itr->second.second); break; } case SMART_ACTION_REMOVE_ITEM: if (!IsItemValid(e, e.action.item.entry)) return false; if (!NotNULL(e, e.action.item.count)) return false; break; case SMART_ACTION_ADD_ITEM: { if (!IsItemValid(e, e.action.item.entry)) return false; if (!NotNULL(e, e.action.item.count)) return false; CacheSpellContainerBounds sBounds = GetCreateItemSpellContainerBounds(e.action.item.entry); for (CacheSpellContainer::const_iterator itr = sBounds.first; itr != sBounds.second; ++itr) TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u Create Item: There is a create item spell for item %u (SpellId: %u effect: %u)", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.item.entry, itr->second.first, itr->second.second); break; } case SMART_ACTION_TELEPORT: if (!sMapStore.LookupEntry(e.action.teleport.mapID)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Map entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.teleport.mapID); return false; } break; case SMART_ACTION_INSTALL_AI_TEMPLATE: if (e.action.installTtemplate.id >= SMARTAI_TEMPLATE_END) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Creature %d Event %u Action %u uses non-existent AI template id %u, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.installTtemplate.id); return false; } break; case SMART_ACTION_WP_STOP: if (e.action.wpStop.quest && !IsQuestValid(e, e.action.wpStop.quest)) return false; break; case SMART_ACTION_WP_START: { if (!sSmartWaypointMgr->GetPath(e.action.wpStart.pathID)) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Creature %d Event %u Action %u uses non-existent WaypointPath id %u, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.pathID); return false; } if (e.action.wpStart.quest && !IsQuestValid(e, e.action.wpStart.quest)) return false; if (e.action.wpStart.reactState > REACT_AGGRESSIVE) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Creature %d Event %u Action %u uses invalid React State %u, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.reactState); return false; } break; } case SMART_ACTION_CREATE_TIMED_EVENT: { if (!IsMinMaxValid(e, e.action.timeEvent.min, e.action.timeEvent.max)) return false; if (!IsMinMaxValid(e, e.action.timeEvent.repeatMin, e.action.timeEvent.repeatMax)) return false; break; } case SMART_ACTION_CALL_RANDOM_RANGE_TIMED_ACTIONLIST: { if (!IsMinMaxValid(e, e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2)) return false; break; } case SMART_ACTION_SET_POWER: case SMART_ACTION_ADD_POWER: case SMART_ACTION_REMOVE_POWER: if (e.action.power.powerType > MAX_POWERS) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Power %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.power.powerType); return false; } break; case SMART_ACTION_GAME_EVENT_STOP: { uint32 eventId = e.action.gameEventStop.id; GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); if (eventId < 1 || eventId >= events.size()) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStop.id); return false; } GameEventData const& eventData = events[eventId]; if (!eventData.isValid()) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStop.id); return false; } break; } case SMART_ACTION_GAME_EVENT_START: { uint32 eventId = e.action.gameEventStart.id; GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); if (eventId < 1 || eventId >= events.size()) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStart.id); return false; } GameEventData const& eventData = events[eventId]; if (!eventData.isValid()) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStart.id); return false; } break; } case SMART_ACTION_EQUIP: { if (e.GetScriptType() == SMART_SCRIPT_TYPE_CREATURE) { int8 equipId = (int8)e.action.equip.entry; if (equipId) { EquipmentInfo const* einfo = sObjectMgr->GetEquipmentInfo(e.entryOrGuid, equipId); if (!einfo) { TC_LOG_ERROR("sql.sql", "SmartScript: SMART_ACTION_EQUIP uses non-existent equipment info id %u for creature %u, skipped.", equipId, e.entryOrGuid); return false; } } } break; } case SMART_ACTION_SET_INGAME_PHASE_ID: { uint32 phaseId = e.action.ingamePhaseId.id; uint32 apply = e.action.ingamePhaseId.apply; if (apply != 0 && apply != 1) { TC_LOG_ERROR("sql.sql", "SmartScript: SMART_ACTION_SET_INGAME_PHASE_ID uses invalid apply value %u (Should be 0 or 1) for creature %u, skipped", apply, e.entryOrGuid); return false; } PhaseEntry const* phase = sPhaseStore.LookupEntry(phaseId); if (!phase) { TC_LOG_ERROR("sql.sql", "SmartScript: SMART_ACTION_SET_INGAME_PHASE_ID uses invalid phaseid %u for creature %u, skipped", phaseId, e.entryOrGuid); return false; } break; } case SMART_ACTION_SET_INGAME_PHASE_GROUP: { uint32 phaseGroup = e.action.ingamePhaseGroup.groupId; uint32 apply = e.action.ingamePhaseGroup.apply; if (apply != 0 && apply != 1) { TC_LOG_ERROR("sql.sql", "SmartScript: SMART_ACTION_SET_INGAME_PHASE_GROUP uses invalid apply value %u (Should be 0 or 1) for creature %u, skipped", apply, e.entryOrGuid); return false; } PhaseGroupEntry const* phase = sPhaseGroupStore.LookupEntry(phaseGroup); if (!phase) { TC_LOG_ERROR("sql.sql", "SmartScript: SMART_ACTION_SET_INGAME_PHASE_GROUP uses invalid phase group id %u for creature %u, skipped", phaseGroup, e.entryOrGuid); return false; } break; } case SMART_ACTION_START_CLOSEST_WAYPOINT: case SMART_ACTION_FOLLOW: case SMART_ACTION_SET_ORIENTATION: case SMART_ACTION_STORE_TARGET_LIST: case SMART_ACTION_EVADE: case SMART_ACTION_FLEE_FOR_ASSIST: case SMART_ACTION_DIE: case SMART_ACTION_SET_IN_COMBAT_WITH_ZONE: case SMART_ACTION_SET_ACTIVE: case SMART_ACTION_WP_RESUME: case SMART_ACTION_KILL_UNIT: case SMART_ACTION_SET_INVINCIBILITY_HP_LEVEL: case SMART_ACTION_RESET_GOBJECT: case SMART_ACTION_ATTACK_START: case SMART_ACTION_THREAT_ALL_PCT: case SMART_ACTION_THREAT_SINGLE_PCT: case SMART_ACTION_SET_INST_DATA: case SMART_ACTION_SET_INST_DATA64: case SMART_ACTION_AUTO_ATTACK: case SMART_ACTION_ALLOW_COMBAT_MOVEMENT: case SMART_ACTION_CALL_FOR_HELP: case SMART_ACTION_SET_DATA: case SMART_ACTION_MOVE_FORWARD: case SMART_ACTION_SET_VISIBILITY: case SMART_ACTION_WP_PAUSE: case SMART_ACTION_SET_FLY: case SMART_ACTION_SET_RUN: case SMART_ACTION_SET_SWIM: case SMART_ACTION_FORCE_DESPAWN: case SMART_ACTION_SET_UNIT_FLAG: case SMART_ACTION_REMOVE_UNIT_FLAG: case SMART_ACTION_PLAYMOVIE: case SMART_ACTION_MOVE_TO_POS: case SMART_ACTION_RESPAWN_TARGET: case SMART_ACTION_CLOSE_GOSSIP: case SMART_ACTION_TRIGGER_TIMED_EVENT: case SMART_ACTION_REMOVE_TIMED_EVENT: case SMART_ACTION_OVERRIDE_SCRIPT_BASE_OBJECT: case SMART_ACTION_RESET_SCRIPT_BASE_OBJECT: case SMART_ACTION_ACTIVATE_GOBJECT: case SMART_ACTION_CALL_SCRIPT_RESET: case SMART_ACTION_SET_RANGED_MOVEMENT: case SMART_ACTION_CALL_TIMED_ACTIONLIST: case SMART_ACTION_SET_NPC_FLAG: case SMART_ACTION_ADD_NPC_FLAG: case SMART_ACTION_REMOVE_NPC_FLAG: case SMART_ACTION_CROSS_CAST: case SMART_ACTION_CALL_RANDOM_TIMED_ACTIONLIST: case SMART_ACTION_RANDOM_MOVE: case SMART_ACTION_SET_UNIT_FIELD_BYTES_1: case SMART_ACTION_REMOVE_UNIT_FIELD_BYTES_1: case SMART_ACTION_INTERRUPT_SPELL: case SMART_ACTION_SEND_GO_CUSTOM_ANIM: case SMART_ACTION_SET_DYNAMIC_FLAG: case SMART_ACTION_ADD_DYNAMIC_FLAG: case SMART_ACTION_REMOVE_DYNAMIC_FLAG: case SMART_ACTION_JUMP_TO_POS: case SMART_ACTION_SEND_GOSSIP_MENU: case SMART_ACTION_GO_SET_LOOT_STATE: case SMART_ACTION_SEND_TARGET_TO_TARGET: case SMART_ACTION_SET_HOME_POS: case SMART_ACTION_SET_HEALTH_REGEN: case SMART_ACTION_SET_ROOT: case SMART_ACTION_SET_GO_FLAG: case SMART_ACTION_ADD_GO_FLAG: case SMART_ACTION_REMOVE_GO_FLAG: case SMART_ACTION_SUMMON_CREATURE_GROUP: break; default: TC_LOG_ERROR("sql.sql", "SmartAIMgr: Not handled action_type(%u), event_type(%u), Entry %d SourceType %u Event %u, skipped.", e.GetActionType(), e.GetEventType(), e.entryOrGuid, e.GetScriptType(), e.event_id); return false; } return true; } bool SmartAIMgr::IsTextValid(SmartScriptHolder const& e, uint32 id) { if (e.GetScriptType() != SMART_SCRIPT_TYPE_CREATURE) return true; uint32 entry = 0; if (e.GetEventType() == SMART_EVENT_TEXT_OVER) { entry = e.event.textOver.creatureEntry; } else { switch (e.GetTargetType()) { case SMART_TARGET_CREATURE_DISTANCE: case SMART_TARGET_CREATURE_RANGE: case SMART_TARGET_CLOSEST_CREATURE: return true; // ignore default: if (e.entryOrGuid < 0) { entry = uint32(std::abs(e.entryOrGuid)); CreatureData const* data = sObjectMgr->GetCreatureData(entry); if (!data) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u using non-existent Creature guid %d, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } else entry = data->id; } else entry = uint32(e.entryOrGuid); break; } } if (!entry || !sCreatureTextMgr->TextExist(entry, uint8(id))) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u using non-existent Text id %d, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), id); return false; } return true; } void SmartAIMgr::LoadHelperStores() { uint32 oldMSTime = getMSTime(); SpellInfo const* spellInfo = NULL; for (uint32 i = 0; i < sSpellMgr->GetSpellInfoStoreSize(); ++i) { spellInfo = sSpellMgr->GetSpellInfo(i); if (!spellInfo) continue; for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (spellInfo->Effects[j].IsEffect(SPELL_EFFECT_SUMMON)) SummonCreatureSpellStore.insert(std::make_pair(uint32(spellInfo->Effects[j].MiscValue), std::make_pair(i, SpellEffIndex(j)))); else if (spellInfo->Effects[j].IsEffect(SPELL_EFFECT_SUMMON_OBJECT_WILD)) SummonGameObjectSpellStore.insert(std::make_pair(uint32(spellInfo->Effects[j].MiscValue), std::make_pair(i, SpellEffIndex(j)))); else if (spellInfo->Effects[j].IsEffect(SPELL_EFFECT_KILL_CREDIT) || spellInfo->Effects[j].IsEffect(SPELL_EFFECT_KILL_CREDIT2)) KillCreditSpellStore.insert(std::make_pair(uint32(spellInfo->Effects[j].MiscValue), std::make_pair(i, SpellEffIndex(j)))); else if (spellInfo->Effects[j].IsEffect(SPELL_EFFECT_CREATE_ITEM)) CreateItemSpellStore.insert(std::make_pair(uint32(spellInfo->Effects[j].ItemType), std::make_pair(i, SpellEffIndex(j)))); } } TC_LOG_INFO("server.loading", ">> Loaded SmartAIMgr Helpers in %u ms", GetMSTimeDiffToNow(oldMSTime)); } void SmartAIMgr::UnLoadHelperStores() { SummonCreatureSpellStore.clear(); SummonGameObjectSpellStore.clear(); KillCreditSpellStore.clear(); CreateItemSpellStore.clear(); } CacheSpellContainerBounds SmartAIMgr::GetSummonCreatureSpellContainerBounds(uint32 creatureEntry) const { return SummonCreatureSpellStore.equal_range(creatureEntry); } CacheSpellContainerBounds SmartAIMgr::GetSummonGameObjectSpellContainerBounds(uint32 gameObjectEntry) const { return SummonGameObjectSpellStore.equal_range(gameObjectEntry); } CacheSpellContainerBounds SmartAIMgr::GetKillCreditSpellContainerBounds(uint32 killCredit) const { return KillCreditSpellStore.equal_range(killCredit); } CacheSpellContainerBounds SmartAIMgr::GetCreateItemSpellContainerBounds(uint32 itemId) const { return CreateItemSpellStore.equal_range(itemId); }
gpl-2.0
uthopiko/Joomla
administrator/components/com_community/install.community.php
2525
<?php /** * @category Core * @package JomSocial * @copyright (C) 2008 by Slashes & Dots Sdn Bhd - All rights reserved! * @license GNU/GPL, see LICENSE.php */ // Disallow direct access to this file defined('_JEXEC') or die('Restricted access'); /** * This file and method will automatically get called by Joomla * during the installation process **/ jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.file'); if ( ! class_exists('JURI')) { jimport('joomla.environment.uri'); } function com_install() { // get the installing com_community version $installer = JInstaller::getInstance(); $path = $installer->getPath('manifest'); $communityVersion = $installer->getManifest()->version; if (JVERSION < '2.5.6' and $communityVersion >= '2.8.0') { JError::raiseNotice(1, 'JomSocial 2.8.x require minimum Joomla! CMS 2.5.6'); return false; } $lang = JFactory::getLanguage(); $lang->load('com_community', JPATH_ROOT.'/administrator'); $destination = JPATH_ROOT.'/administrator/components/com_community/'; $buffer = "installing"; if( ! JFile::write($destination.'installer.dummy.ini', $buffer)) { ob_start(); ?> <table width="100%" border="0"> <tr> <td> There was an error while trying to create an installation file. Please ensure that the path <strong><?php echo $destination; ?></strong> has correct permissions and try again. </td> </tr> </table> <?php $html = ob_get_contents(); @ob_end_clean(); } else { $link = rtrim(JURI::root(), '/').'/administrator/index.php?option=com_community'; ob_start(); ?> <style type="text/css"> .adminform {text-align:left;} .adminform > tbody > tr > th { font-size:20px;} .button-next { margin:20px 0px 40px; padding:10px 20px; color:#fefefe; font-size:16px; line-height:16px; text-align: center; font-weight: normal; color: #333; background: #9c3; border: solid 1px #690; cursor: pointer; } </style> <table width="100%" border="0"> <tr> <td> Thank you for choosing JomSocial, please click on the following button to complete your installation. </td> </tr> <tr> <td> <input type="button" class="button-next" onclick="window.location = '<?php echo $link; ?>'" value="<?php echo JText::_('COM_COMMUNITY_INSTALLATION_COMPLETE_YOUR_INSTALLATION');?>"/> </td> </tr> </table> <?php $html = ob_get_contents(); @ob_end_clean(); } echo $html; }
gpl-2.0
rjeschmi/easybuild-easyblocks
easybuild/easyblocks/m/matlab.py
6124
## # Copyright 2009-2013 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (http://www.herculesstichting.be/in_English) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation v2. # # EasyBuild is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for installing MATLAB, implemented as an easyblock @author: Stijn De Weirdt (Ghent University) @author: Dries Verdegem (Ghent University) @author: Kenneth Hoste (Ghent University) @author: Pieter De Baets (Ghent University) @author: Jens Timmerman (Ghent University) @author: Fotis Georgatos (University of Luxembourg) """ import re import os import shutil from easybuild.framework.easyblock import EasyBlock from easybuild.framework.easyconfig import CUSTOM from easybuild.tools.filetools import run_cmd class EB_MATLAB(EasyBlock): """Support for installing MATLAB.""" def __init__(self, *args, **kwargs): """Add extra config options specific to MATLAB.""" super(EB_MATLAB, self).__init__(*args, **kwargs) self.comp_fam = None self.configfilename = "my_installer_input.txt" @staticmethod def extra_options(): extra_vars = { 'java_options': ['-Xmx256m', "$_JAVA_OPTIONS value set for install and in module file.", CUSTOM], } return EasyBlock.extra_options(extra_vars) def configure_step(self): """Configure MATLAB installation: create license file.""" # create license file licserv = self.cfg['license_server'] licport = self.cfg['license_server_port'] lictxt = '\n'.join([ "SERVER %s 000000000000 %s" % (licserv, licport), "USE_SERVER", ]) licfile = "%s/matlab.lic" % self.builddir try: f = file(licfile, "w") f.write(lictxt) f.close() except IOError, err: self.log.error("Failed to create license file %s: %s" % (licfile, err)) configfile = os.path.join(self.builddir, self.configfilename) try: shutil.copyfile("%s/%s/installer_input.txt" % (self.builddir, self.version), configfile) config = file(configfile).read() regdest = re.compile(r"^# destinationFolder=.*", re.M) regkey = re.compile(r"^# fileInstallationKey=.*", re.M) regagree = re.compile(r"^# agreeToLicense=.*", re.M) regmode = re.compile(r"^# mode=.*", re.M) reglicpath = re.compile(r"^# licensePath=.*", re.M) config = regdest.sub("destinationFolder=%s" % self.installdir, config) key = self.cfg['key'] config = regkey.sub("fileInstallationKey=%s" % key, config) config = regagree.sub("agreeToLicense=Yes", config) config = regmode.sub("mode=silent", config) config = reglicpath.sub("licensePath=%s" % licfile, config) f = open(configfile, 'w') f.write(config) f.close() except IOError, err: self.log.error("Failed to create installation config file %s: %s" % (configfile, err)) self.log.debug('configuration file written to %s:\n %s' % (configfile, config)) def build_step(self): """No building of MATLAB, no sources available.""" pass def install_step(self): """MATLAB install procedure using 'install' command.""" src = os.path.join(self.cfg['start_dir'], 'install') # make sure install script is executable try: if os.path.isfile(src): self.log.info("Doing chmod on source file %s" % src) os.chmod(src, 0755) else: self.log.info("Did not find source file %s" % src) except OSError, err: self.log.error("Failed to chmod install script: %s" % err) # make sure $DISPLAY is not defined, which may lead to (hard to trace) problems # this is a workaround for not being able to specify --nodisplay to the install scripts if 'DISPLAY' in os.environ: os.environ.pop('DISPLAY') if not '_JAVA_OPTIONS' in self.cfg['preinstallopts']: self.cfg['preinstallopts'] = ('export _JAVA_OPTIONS="%s" && ' % self.cfg['java_options']) + self.cfg['preinstallopts'] configfile = "%s/%s" % (self.builddir, self.configfilename) cmd = "%s ./install -v -inputFile %s %s" % (self.cfg['preinstallopts'], configfile, self.cfg['installopts']) run_cmd(cmd, log_all=True, simple=True) def sanity_check_step(self): """Custom sanity check for MATLAB.""" custom_paths = { 'files': ["bin/matlab", "bin/mcc", "bin/glnxa64/MATLAB", "bin/glnxa64/mcc", "runtime/glnxa64/libmwmclmcrrt.so", "toolbox/local/classpath.txt"], 'dirs': ["java/jar", "toolbox/compiler"], } super(EB_MATLAB, self).sanity_check_step(custom_paths=custom_paths) def make_module_extra(self): """Extend PATH and set proper _JAVA_OPTIONS (e.g., -Xmx).""" txt = super(EB_MATLAB, self).make_module_extra() txt += self.moduleGenerator.set_environment('_JAVA_OPTIONS', self.cfg['java_options']) return txt
gpl-2.0
jagnoha/website
profiles/varbase/profiles/varbase/libraries/ckeditor/plugins/about/lang/ar.js
519
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'about', 'ar', { copy: 'حقوق النشر &copy; $1. جميع الحقوق محفوظة.', dlgTitle: 'عن CKEditor', help: 'راجع $1 من أجل المساعدة', moreInfo: 'للحصول على معلومات الترخيص ، يرجى زيارة موقعنا:', title: 'عن CKEditor', userGuide: 'دليل مستخدم CKEditor.' } );
gpl-2.0
nightflyza/Ubilling
openpayz/frontend/liqpaymulti/index.php
4331
<?php /* * Фронтенд платежной системы LiqPay получающий ответы в виде POST XML * согласно протокола: https://www.liqpay.ua/documentation/api/aquiring/checkout/ */ //достаем конфиг $liqConf = parse_ini_file('config/liqpay.ini'); // подключаем API OpenPayz include ("../../libs/api.openpayz.php"); /** * Gets user associated agent data JSON * * @param string $userlogin * * @return string */ function getAgentData($userlogin) { $result = ''; global $liqConf; $action = $liqConf['API_URL'] . '?module=remoteapi&key=' . $liqConf['API_KEY'] . '&action=getagentdata&param=' . $userlogin; @$result = file_get_contents($action); if (!empty($result)) { $result = json_decode($result, true); } return ($result); } /** * * Check for POST have needed variables * * @param $params array of POST variables to check * @return bool * */ function lq_CheckPost($params) { $result = true; if (!empty($params)) { foreach ($params as $eachparam) { if (isset($_POST[$eachparam])) { if (empty($_POST[$eachparam])) { $result = false; } } else { $result = false; } } } return ($result); } /* * Check is transaction unique? * * @param $hash - transaction hash * * @return bool */ function lq_CheckTransaction($hash) { $hash = mysql_real_escape_string($hash); $query = "SELECT `id` from `op_transactions` WHERE `hash`='" . $hash . "'"; $data = simple_query($query); if (!empty($data)) { return (false); } else { return (true); } } //пытаемся ловить объязательные параметры от LiqPay if (lq_CheckPost(array('data', 'signature'))) { global $liqConf; $data = $_POST['data']; $reqSig = $_POST['signature']; $data_decoded = base64_decode($data); if (!empty($data_decoded)) { $data_js = json_decode($data_decoded); if (!json_last_error()) { if ($data_js->status == 'success') { $hash = $data_js->order_id; $customerid = $data_js->description; $summ = $data_js->amount; $addCommission = (isset($liqConf['ADD_COMMISSION'])) ? $liqConf['ADD_COMMISSION'] : 1; $summ = round(($summ / $addCommission), 2); //Зачисляем сумму без процентов $paysys = "LIQPAY"; $note = "TRANSACTION ID: " . $data_js->transaction_id; if (lq_CheckTransaction($hash)) { $allcustomers = op_CustomersGetAll(); if (isset($allcustomers[$customerid])) { $customerLogin = $allcustomers[$customerid]; $agentData = getAgentData($customerLogin); if (isset($liqConf['SIGNATURE'][$agentData['id']])) { $private_key = $liqConf['SIGNATURE'][$agentData['id']]; } else { $private_key = $liqConf['SIGNATURE']['default']; } $signature = base64_encode(sha1($private_key . $data . $private_key, 1)); if ($reqSig == $signature) { //регистрируем новую транзакцию op_TransactionAdd($hash, $summ, $customerid, $paysys, $note); //вызываем обработчики необработанных транзакций op_ProcessHandlers(); //тихонько помираем die('TRANSACTION_OK'); } else { die('MISSING_SIGNATURE'); } } else { die('ERROR_NO_SUCH_USER'); } } else { die('DOUBLE_PAYMENT'); } } } else { die('ERROR_INVALID_JSON_DATA'); } } else { die('ERROR_EMPTY_DATA'); } } else { die('ERROR_NO_POST_DATA'); } ?>
gpl-2.0
jawug/wugms
web/js/i18n/af.js
866
/*! Select2 4.0.11 | https://github.com/select2/select2/blob/master/LICENSE.md */ !function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;e.define("select2/i18n/af",[],function(){return{errorLoading:function(){return"Die resultate kon nie gelaai word nie."},inputTooLong:function(e){var n=e.input.length-e.maximum,r="Verwyders asseblief "+n+" character";return 1!=n&&(r+="s"),r},inputTooShort:function(e){return"Voer asseblief "+(e.minimum-e.input.length)+" of meer karakters"},loadingMore:function(){return"Meer resultate word gelaai…"},maximumSelected:function(e){var n="Kies asseblief net "+e.maximum+" item";return 1!=e.maximum&&(n+="s"),n},noResults:function(){return"Geen resultate gevind"},searching:function(){return"Besig…"},removeAllItems:function(){return"Verwyder alle items"}}}),e.define,e.require}();
gpl-2.0
xiqingongzi/AMH
VERSION/3.1/Model/tasks.php
6805
<?php class tasks extends AmysqlModel { // 取得任务 function get_task($id = null, $crontab_md5 = null) { $where = ''; $where .= (!empty($id)) ? " AND crontab_id = '$id' " : ''; $where .= (!empty($crontab_md5)) ? " AND crontab_md5 = '$crontab_md5' " : ''; $sql = "SELECT * FROM amh_crontab WHERE 1 $where "; Return $this -> _row($sql); } // 取得任务属性 function get_task_value($tag) { foreach ($_POST as $key=>$val) { if(strpos($key, $tag) !== false) { if(strpos($key, 'time') !== false) Return $_POST[$tag . '_time']; elseif(strpos($key, 'period') !== false) Return $_POST[$tag . '_period_start'] . '-' . $_POST[$tag . '_period_end']; elseif(strpos($key, 'average') !== false) Return $_POST[$tag . '_average_start'] . '-' . $_POST[$tag . '_average_end'] . '/' . $_POST[$tag . '_average_input']; elseif(strpos($key, 'respectively') !== false) Return implode(',', $_POST[$tag . '_respectively']); } } } // 新增任务 function insert_task() { $crontab_ssh = trim($_POST['crontab_ssh']); if(substr($crontab_ssh, 0, 3) != 'amh') Return false; $crontab_ssh = Functions::trim_cmd($crontab_ssh); $crontab_minute = $this -> get_task_value('minute'); $crontab_hour = $this -> get_task_value('hour'); $crontab_day = $this -> get_task_value('day'); $crontab_month = $this -> get_task_value('month'); $crontab_week = $this -> get_task_value('week'); $crontab_type = 'web'; $crontab_tmp = '/home/wwwroot/index/tmp/crontab.tmp'; $cmd = "amh crontab -l > $crontab_tmp"; $result = shell_exec($cmd); $crontab_content = file_get_contents($crontab_tmp) . $crontab_minute . ' ' . $crontab_hour . ' ' . $crontab_day . ' ' . $crontab_month . ' ' . $crontab_week . ' ' . $crontab_ssh . "\n"; file_put_contents($crontab_tmp, $crontab_content, LOCK_EX); $cmd = "amh crontab $crontab_tmp"; $result = shell_exec($cmd); $crontab_md5 = md5($crontab_minute.$crontab_hour.$crontab_day.$crontab_month.$crontab_week.$crontab_ssh); Return $this -> _insert('amh_crontab', array('crontab_minute' => $crontab_minute, 'crontab_hour' => $crontab_hour, 'crontab_day' => $crontab_day, 'crontab_month' => $crontab_month, 'crontab_week' => $crontab_week, 'crontab_ssh' => $crontab_ssh, 'crontab_type' => $crontab_type, 'crontab_md5' => $crontab_md5)); } // 删除任务 function del_task($id = null, $crontab_md5 = null) { if (!empty($id)) { $task = $this -> get_task($id); if (!isset($task['crontab_id'])) Return false; } if(!empty($crontab_md5)) $task['crontab_md5'] = $crontab_md5; $cmd = 'amh crontab -l'; $result = shell_exec($cmd); $task_list = explode("\n", $result); $crontab_content = ''; $crontab_tmp = '/home/wwwroot/index/tmp/crontab.tmp'; foreach ($task_list as $key=>$val) { $val_arr = explode(' ', ereg_replace("[ ]{1,}", " ", trim($val))); if($val_arr[0] != '#' && $val_arr[0][0] != '#' && count($val_arr) > 5) { $crontab_ssh = ''; foreach ($val_arr as $k=>$v) { if($k > 4) $crontab_ssh .= ' ' . $v; } $crontab_ssh = trim($crontab_ssh); $crontab_md5 = md5($val_arr[0].$val_arr[1].$val_arr[2].$val_arr[3].$val_arr[4].$crontab_ssh); if ($crontab_md5 != $task['crontab_md5']) $crontab_content .= $val . "\n"; } } file_put_contents($crontab_tmp, $crontab_content, LOCK_EX); $cmd = "amh crontab $crontab_tmp"; shell_exec($cmd); Return true; } // 保存任务 function save_task($id) { $task = $this -> get_task($id); if (!isset($task['crontab_id']) || $task['crontab_type'] == 'ssh') Return false; $crontab_ssh = trim($_POST['crontab_ssh']); if(substr($crontab_ssh, 0, 3) != 'amh') Return false; $crontab_ssh = Functions::trim_cmd($crontab_ssh); $crontab_minute = $this -> get_task_value('minute'); $crontab_hour = $this -> get_task_value('hour'); $crontab_day = $this -> get_task_value('day'); $crontab_month = $this -> get_task_value('month'); $crontab_week = $this -> get_task_value('week'); $crontab_type = 'web'; $crontab_md5 = md5($crontab_minute.$crontab_hour.$crontab_day.$crontab_month.$crontab_week.$crontab_ssh); $this -> _update('amh_crontab', array('crontab_minute' => $crontab_minute, 'crontab_hour' => $crontab_hour, 'crontab_day' => $crontab_day, 'crontab_month' => $crontab_month, 'crontab_week' => $crontab_week, 'crontab_ssh' => $crontab_ssh, 'crontab_type' => $crontab_type, 'crontab_md5' => $crontab_md5), " WHERE crontab_id = '$id' "); $this -> del_task(null, $task['crontab_md5']); $crontab_tmp = '/home/wwwroot/index/tmp/crontab.tmp'; $cmd = "amh crontab -l > $crontab_tmp"; $result = shell_exec($cmd); $crontab_content = file_get_contents($crontab_tmp) . $crontab_minute . ' ' . $crontab_hour . ' ' . $crontab_day . ' ' . $crontab_month . ' ' . $crontab_week . ' ' . $crontab_ssh . "\n"; file_put_contents($crontab_tmp, $crontab_content, LOCK_EX); $cmd = "amh crontab $crontab_tmp"; $result = shell_exec($cmd); Return true; } // 取得任务列表 function get_task_list() { $cmd = 'amh crontab -l'; $result = shell_exec($cmd); $task_list = explode("\n", $result); foreach ($task_list as $key=>$val) { $val_arr = explode(' ', ereg_replace("[ ]{1,}", " ", trim($val))); if($val_arr[0] != '#' && $val_arr[0][0] != '#' && count($val_arr) > 5) { $crontab_minute = $val_arr[0]; $crontab_hour = $val_arr[1]; $crontab_day = $val_arr[2]; $crontab_month = $val_arr[3]; $crontab_week = $val_arr[4]; $crontab_ssh = ''; $crontab_type = 'ssh'; foreach ($val_arr as $k=>$v) { if($k > 4) $crontab_ssh .= ' ' . $v; } $crontab_ssh = trim($crontab_ssh); $crontab_md5 = md5($crontab_minute.$crontab_hour.$crontab_day.$crontab_month.$crontab_week.$crontab_ssh); $all_task_list[] = $crontab_md5; $task_info = $this -> get_task(null, $crontab_md5); if(!isset($task_info['crontab_id'])) { $this -> _insert('amh_crontab', array('crontab_minute' => $crontab_minute, 'crontab_hour' => $crontab_hour, 'crontab_day' => $crontab_day, 'crontab_month' => $crontab_month, 'crontab_week' => $crontab_week, 'crontab_ssh' => $crontab_ssh, 'crontab_type' => $crontab_type, 'crontab_md5' => $crontab_md5)); } } } if(count($all_task_list) > 0) { $sql = "DELETE FROM amh_crontab WHERE crontab_md5 NOT IN ('" . implode("','", $all_task_list) . "')"; $this -> _query($sql); } else { $sql = "TRUNCATE TABLE `amh_crontab`"; $this -> _query($sql); } $sql = "SELECT * FROM amh_crontab ORDER BY crontab_id ASC "; Return $this -> _all($sql); } } ?>
gpl-2.0
GiGa-Emulator/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/quest/greater_stigma/_11276StigmaEnlightenment.java
3774
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package quest.greater_stigma; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; /** * @author vlog */ public class _11276StigmaEnlightenment extends QuestHandler { private static final int questId = 11276; public _11276StigmaEnlightenment() { super(questId); } @Override public void register() { qe.registerQuestNpc(798909).addOnQuestStart(questId); qe.registerQuestNpc(798909).addOnTalkEvent(questId); } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); int targetId = env.getTargetId(); DialogAction dialog = env.getDialog(); if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 798909) { // Reemul switch (dialog) { case QUEST_SELECT: { return sendQuestDialog(env, 1011); } default: { return sendQuestStartDialog(env); } } } } else if (qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (targetId == 798909) { // Reemul switch (dialog) { case QUEST_SELECT: case SELECT_QUEST_REWARD: { if (var == 0) { qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); return sendQuestDialog(env, 2375); } } } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 798909) { // Reemul switch (dialog) { case SELECT_QUEST_REWARD: { return sendQuestDialog(env, 5); } default: { return sendQuestEndDialog(env); } } } } return false; } }
gpl-2.0
haivuong/kistech
administrator/components/com_mobilize/libraries/joomlashine/mobilize.php
8315
<?php /** * @version $Id: mobilize.php 15520 2012-08-27 08:20:36Z cuongnm $ * @package JSN_Mobilize * @subpackage AdminComponent * @author JoomlaShine Team <support@joomlashine.com> * @copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved. * @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html * * Websites: http://www.joomlashine.com * Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html */ // No direct access to this file defined('_JEXEC') or die('Restricted access'); /** * Layout class. * * @package JSN_Mobilize * @subpackage AdminComponent * @since 1.0.0 */ class JSNMobilize { private $_contentData = null; private $_dataModules = null; /** * Class constructor. * * @param string $contentData Preset content. */ public function __construct($contentData = null) { $this->_contentData = $contentData; $this->_dataModules = $this->getModules(); } /** * Generate HTML content block. * * @param type $name Name of content block. * * @param type $class Class style * * @return string */ function getBlockContent($name, $class = '') { $edition = defined('JSN_MOBILIZE_EDITION') ? JSN_MOBILIZE_EDITION : "free"; if (strtolower($edition) == "free" && in_array($name, array('mobilize-user-top-left', 'mobilize-user-top-right', 'mobilize-content-top-left', 'mobilize-content-top-right', 'mobilize-user-bottom-left', 'mobilize-user-bottom-right', 'mobilize-content-bottom-left', 'mobilize-content-bottom-right'))) { $html = '<div id="' . $name . '" class="jsn-column ' . $class . '"> <div class="jsn-element-disabale-container"></div> <div class="mobile-phone-block-action row-fluid"> <input type="hidden" name="jsnmobilize[' . $name . '][]" value="" /> <a class="jsn-add-more" title="' . JText::_('JSN_MOBILIZE_ADD_ELEMENT') . '" href="javascript:void(0);">' . JText::_('JSN_MOBILIZE_ADD_ELEMENT') . ' <span class="label label-important">PRO</span></a> </div> </div>'; } else { $html = '<div id="' . $name . '" class="jsn-column ' . $class . '"> <div class="jsn-element-container"> ' . $this->getItemsBlockContent($name) . ' </div> <div class="mobile-phone-block-action row-fluid"> <input type="hidden" name="jsnmobilize[' . $name . '][]" value="" /> <a class="jsn-add-more" title="' . JText::_('JSN_MOBILIZE_ADD_ELEMENT') . '" href="javascript:void(0);">' . JText::_('JSN_MOBILIZE_ADD_ELEMENT') . '</a> </div> </div>'; } return $html; } /** * Get items content block. * * @param type $name Name of content block. * * @return string */ function getItemsBlockContent($name) { $html = ''; $mobilizeBlockContent = isset($this->_contentData[$name]) ? $this->_contentData[$name] : ''; if (!empty($mobilizeBlockContent) && count($mobilizeBlockContent)) { foreach ($mobilizeBlockContent as $value => $type) { if ($type == "module") { $nameItem = isset($this->_dataModules['getById'][$value]) ? $this->_dataModules['getById'][$value] : ''; } else { $nameItem = $value; } $html .= '<div class="jsn-element ui-state-default jsn-iconbar-trigger" data-value="' . $value . '" data-type="' . $type . '" >'; $html .= ' <div class="jsn-element-content"> <span class="type-element">' . Jtext::_("JSN_MOBILIZE_TYPE_" . strtoupper($type)) . ': </span> <span class="name-element">' . $nameItem . '</span> <input type="hidden" class="data-block-mobilize" name="jsnmobilize[' . $name . '][]" value=\'' . json_encode(array($value => $type)) . '\' /> </div>'; $html .= '<div class="jsn-iconbar"> <a class="element-edit" title="Change ' . Jtext::_("JSN_MOBILIZE_TYPE_" . strtoupper($type)) . '" href="javascript:void(0)"><i class="icon-pencil"></i></a> <a class="element-delete" title="Delete ' . Jtext::_("JSN_MOBILIZE_TYPE_" . strtoupper($type)) . '" href="javascript:void(0)"><i class="icon-trash"></i></a> </div> </div>'; } } return $html; } /** * Get items logo * * @param type $name Logo name * @param type $title Logo title * * @return string */ function getItemsLogo($name, $title) { $mobilizeLogo = isset($this->_contentData[$name]) ? $this->_contentData[$name] : ''; $mobilizeLogoSrc = !empty($mobilizeLogo) && is_object($mobilizeLogo) && key($mobilizeLogo) != '_empty_' ? key($mobilizeLogo) : ''; $mobilizeLogoSlogan = isset($mobilizeLogo->$mobilizeLogoSrc) ? $mobilizeLogo->$mobilizeLogoSrc : ''; if (empty($mobilizeLogoSlogan) && !empty($mobilizeLogo->_empty_)) { $mobilizeLogoSlogan = $mobilizeLogo->_empty_; } $text = ""; $class = ""; if (!empty($mobilizeLogoSrc)) { $text = '<span style="display:none;" class="jsn-select-logo">' . JText::_($title) . '</span><img src="' . JURI::root() . $mobilizeLogoSrc . '" alt="' . $mobilizeLogoSlogan . '" />'; } else { $class = "jsn-logo-null"; $text = '<span class="jsn-select-logo">' . JText::_($title) . '</span><img src="" />'; } $value = json_encode(array($mobilizeLogoSrc => $mobilizeLogoSlogan)); $html = '<input type="hidden" class="data-mobilize" data-id="' . $mobilizeLogoSrc . '" name="jsnmobilize[' . $name . ']" value=\'' . $value . '\'/> <a id="jsn_mobilize_select_logo" title="' . JText::_($title) . '" data-type="' . $name . '" href="javascript:void(0)" class="element-edit ' . $class . '" data-state="' . $mobilizeLogoSlogan . '" data-value="' . $mobilizeLogoSrc . '">' . $text . '</a>'; return $html; } /** * Get items menu icon. * * @param string $name Menu name. * @param string $title Menu title. * @param string $type Menu type. * @param String $icon Menu Icon * @param String $popup Position Popup * @param String $style style * @return string */ function getItemsMenuIcon($name, $title, $type = '', $icon = '', $style = '') { $mobilizeMenu = isset($this->_contentData[$name]) ? $this->_contentData[$name] : ''; $mobilizeMenuId = !empty($mobilizeMenu) && is_object($mobilizeMenu) && key($mobilizeMenu) != '_empty_' ? key($mobilizeMenu) : ''; $mobilizeMenuText = isset($mobilizeMenu->$mobilizeMenuId) ? $mobilizeMenu->$mobilizeMenuId : ''; $mobilizeMenuState = isset($mobilizeMenu->$mobilizeMenuId) ? $mobilizeMenu->$mobilizeMenuId : ''; $text = "<i style='{$style}' class=\"{$icon}\"></i>"; $value = json_encode(array($mobilizeMenuId => $mobilizeMenuText)); if ($name != "mobilize-switcher") { $html = '<li> <a title="' . JText::_($title) . '" data-type="' . $name . '" onclick="return false;" class="link-menu-mobilize" data-value="' . $mobilizeMenuId . '" href="#">' . $text . '</a> <input type="hidden" class="data-mobilize" data-id="' . $mobilizeMenuId . '" name="jsnmobilize[' . $name . ']" value=\'' . $value . '\'/> </li>'; } else { $text = !empty($mobilizeMenuId) ? $mobilizeMenuId : JText::_($title); $html = '<button title="' . JText::_($title) . '" onclick="return false;" data-value="' . $mobilizeMenuId . '" data-state="' . $mobilizeMenuState . '" data-type="' . $name . '" class="btn btn-switcher">' . $text . '</button> <input type="hidden" class="data-mobilize" name="jsnmobilize[' . $name . ']" value=\'' . $value . '\'/>'; } return $html; } /** * Get modules list. * * @return array */ function getModules() { $db = JFactory::getDBO(); $query = $db->getQuery(true); //build the list of categories $query->select('*')->from('#__modules'); $db->setQuery($query); $data = $db->loadObjectList(); $modulesList = array(); if (!empty($data) && count($data) > 1) { foreach ($data as $item) { $modulesList['getById'][$item->id] = $item->title; $modulesList['getByPosition'][$item->position][] = $item->title; } } return $modulesList; } /** * Get default site template. * * @return array */ function getTemplateDefault() { $db = JFactory::getDBO(); $query = $db->getQuery(true); //build the list of categories $query->select('template')->from('#__template_styles')->where("client_id=0")->where("home=1"); $db->setQuery($query); return $db->loadResult(); } }
gpl-2.0
Myrninvollo/Server
src/net/minecraft/item/ItemAnvilBlock.java
523
package net.minecraft.item; import net.minecraft.block.Block; import net.minecraft.block.BlockAnvil; public class ItemAnvilBlock extends ItemMultiTexture { private static final String __OBFID = "CL_00001764"; public ItemAnvilBlock(Block p_i1826_1_) { super(p_i1826_1_, p_i1826_1_, BlockAnvil.field_149834_a); } /** * Returns the metadata of the block which this Item (ItemBlock) can place */ public int getMetadata(int p_77647_1_) { return p_77647_1_ << 2; } }
gpl-2.0
raidho93/buildrace
profiles/social/modules/contrib/message/src/MessageException.php
125
<?php namespace Drupal\message; /** * Message module-specific exception. */ class MessageException extends \Exception {}
gpl-2.0
TakingInitiative/wesnoth
src/game_initialization/playcampaign.hpp
2499
/* Copyright (C) 2003-2005 by David White <dave@whitevine.net> Copyright (C) 2005 - 2016 by Philippe Plantier <ayin@anathas.org> Part of the Battle for Wesnoth Project http://www.wesnoth.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** @file */ #ifndef PLAYCAMPAIGN_H_INCLUDED #define PLAYCAMPAIGN_H_INCLUDED #include "game_end_exceptions.hpp" #include <memory> #include <sstream> #include <set> #include <string> class CVideo; class saved_game; class terrain_type_data; class team; class playsingle_controller; typedef std::shared_ptr<terrain_type_data> ter_data_cache; class config; class wesnothd_connection; struct mp_campaign_info { mp_campaign_info(wesnothd_connection& wdc) : connected_players() , is_host() , current_turn(0) , skip_replay(false) , skip_replay_blindfolded(false) , connection(wdc) { } /// players and observers std::set<std::string> connected_players; bool is_host; unsigned current_turn; bool skip_replay; bool skip_replay_blindfolded; wesnothd_connection& connection; }; class campaign_controller { CVideo& video_; saved_game& state_; const config& game_config_; const ter_data_cache & tdata_; const bool is_unit_test_; bool is_replay_; mp_campaign_info* mp_info_; public: campaign_controller(CVideo& video, saved_game& state, const config& game_config, const ter_data_cache & tdata, bool is_unit_test = false) : video_(video) , state_(state) , game_config_(game_config) , tdata_(tdata) , is_unit_test_(is_unit_test) , is_replay_(false) , mp_info_(nullptr) { } LEVEL_RESULT play_game(); LEVEL_RESULT play_replay() { is_replay_ = true; return play_game(); } void set_mp_info(mp_campaign_info* mp_info) { mp_info_ = mp_info; } private: LEVEL_RESULT playsingle_scenario(end_level_data &end_level); LEVEL_RESULT playmp_scenario(end_level_data &end_level); void show_carryover_message(playsingle_controller& playcontroller, const end_level_data& end_level, LEVEL_RESULT res); static void report_victory(std::ostringstream &report, team& t, int finishing_bonus_per_turn, int turns_left, int finishing_bonus); }; #endif // PLAYCAMPAIGN_H_INCLUDED
gpl-2.0