{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \r\n\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914101,"cells":{"blob_id":{"kind":"string","value":"d1133eb02f7bafdce4f8d1a87d06ac2f270507fa"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"ytteroy/airtel.airshop"},"path":{"kind":"string","value":"/application/modules/cwservers/models/cwservers_model.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4386,"string":"4,386"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"load->database($this->config->item($this->module->active_module), FALSE, TRUE);\n \n // Load table structure\n $this->table_structure = $this->config->item($this->module->active_module.'_table_structure');\n \n // Private actions initialization\n $this->individual_init();\n }\n \n \n public function individual_init()\n {\n // Get name of services table\n $this->sql_services_table = $this->config->item('cwservers_sql_table');\n } \n \n \n private function get_expired_servers($table_name)\n {\n $current_time = time();\n \n $q = $this->db->where('expires <', $current_time)\n ->where('expires !=', 0)\n ->get($table_name);\n \n if($q->num_rows() > 0)\n {\n return $q->result();\n }\n }\n \n \n public function clear_expired($table_name)\n {\n // Get all expired serverss\n $expired_servers = $this->get_expired_servers($table_name);\n \n // If there is at least one expired server\n if(count($expired_servers) > 0)\n {\n // Lets work with each expired server\n foreach($expired_servers as $server)\n {\n // Load SSH lib\n $settings = $this->module->services[$server->module]['ssh'];\n \n // Load ssh lib\n $this->load->library('core/ssh', $settings);\n \n // Do SSH command\n $this->ssh->execute('screen -X -S '.$server->module.'-'.$server->port.' kill');\n \n // Set array with empty values\n $data = array(\n 'name' => '',\n 'server_rcon' => '',\n 'server_password' => '',\n 'expires' => 0,\n );\n // Update server data\n $this->occupy_server($server->id, $server->module, $data);\n }\n }\n }\n \n \n public function get_available_servers($module)\n {\n $q = $this->db->where('expires', 0)\n ->where('module', $module)\n ->get($this->sql_services_table);\n\n if($q->num_rows() > 0)\n {\n return $q->result();\n }\n }\n \n \n /**\n * Function gets occupied servers by internal active module\n * @return type\n */\n public function get_occupied_servers()\n {\n $q = $this->db->where('expires >', 0)\n ->where('module', $this->module->active_service)\n ->get($this->sql_services_table);\n \n if($q->num_rows() > 0)\n {\n return $q->result();\n }\n }\n \n \n /**\n * Function gets occupied servers by specified external service\n * @param type $service\n * @return type\n */\n public function get_occupied_servers_external($service = 'hlds')\n {\n $q = $this->db->where('expires >', 0)\n ->where('module', $service)\n ->get($this->sql_services_table);\n \n if($q->num_rows() > 0)\n {\n return $q->result();\n }\n }\n \n \n \n /**\n * Updates server row with new information. Function can be used also for clearing row.\n * @param type $server_id\n * @param type $module\n * @param type $data\n */\n public function occupy_server($server_id, $module, $data = array())\n {\n $this->db->where('id', $server_id)\n ->where('module', $module)\n ->update($this->sql_services_table, $data);\n }\n \n \n public function get_server($server_id)\n {\n $q = $this->db->where('id', $server_id)\n ->get($this->sql_services_table);\n \n if($q->num_rows() > 0)\n {\n return $q->row();\n }\n }\n \n \n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914102,"cells":{"blob_id":{"kind":"string","value":"5167ae1bf1169e578e379c92bdb9ccd368504ca8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"nwebcode/framework"},"path":{"kind":"string","value":"/src/Nweb/Framework/Application/Service/Locator.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1321,"string":"1,321"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n * @copyright Copyright (c) 2013 Krzysztof Kardasz\n * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public\n * @version 0.1-dev\n * @link https://github.com/nwebcode/framework\n * @link http://framework.nweb.pl\n */\n\nnamespace Nweb\\Framework\\Application\\Service;\n\n/**\n * Service Locator\n *\n * @category NwebFramework\n * @package Application\n * @subpackage Service\n * @author Krzysztof Kardasz \n * @copyright Copyright (c) 2013 Krzysztof Kardasz\n * @version 0.1-dev\n */\nclass Locator\n{\n /**\n * @var array\n */\n protected $services = array();\n\n /**\n * @param string $name\n * @return bool\n */\n public function has ($name)\n {\n return isset($this->services[$name]);\n }\n\n /**\n * @param string $name\n * @return object\n */\n public function get ($name)\n {\n if (!isset($this->params[$name])) {\n $params = $this->params[$name];\n }\n return $this->services[$name];\n }\n\n /**\n * @param string $name\n * @param object $serviceObj\n */\n public function set ($name, $serviceObj)\n {\n $this->services[$name] = $serviceObj;\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914103,"cells":{"blob_id":{"kind":"string","value":"c64bc66afa4af038a33afb8dd43ced6cff735d39"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"Raza448/thoughtbase"},"path":{"kind":"string","value":"/application/view_latest/vendor_only/allres_comment.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":912,"string":"912"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"db->query($sql)->result_array(); \n?>\n 0 ){ \nforeach($data_img as $row => $val ){\n?>\n
\n\n
Age: Gender: Zip:
\n
\n
\n\n
\nNo Comments yet\n
Age:~ Gender:~ Zip:~
\n
\n
\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914104,"cells":{"blob_id":{"kind":"string","value":"94aa2264fb2d4fbcf81c4eaed146b2016763f17b"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"id0612/openapi-sdk-php"},"path":{"kind":"string","value":"/src/Cms/V20180308/GetMonitoringTemplate.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1435,"string":"1,435"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"Apache-2.0\",\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"withName($name);\n }\n\n /**\n * @param string $name\n *\n * @return $this\n */\n public function withName($name)\n {\n $this->data['Name'] = $name;\n $this->options['query']['Name'] = $name;\n\n return $this;\n }\n\n /**\n * @deprecated deprecated since version 2.0, Use withId() instead.\n *\n * @param string $id\n *\n * @return $this\n */\n public function setId($id)\n {\n return $this->withId($id);\n }\n\n /**\n * @param string $id\n *\n * @return $this\n */\n public function withId($id)\n {\n $this->data['Id'] = $id;\n $this->options['query']['Id'] = $id;\n\n return $this;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914105,"cells":{"blob_id":{"kind":"string","value":"4fc011f0184c787bbdac7410df64c1e396470eb7"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"kernvalley/needs-api"},"path":{"kind":"string","value":"/roles/index.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":679,"string":"679"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"on('GET', function(API $req): void\n\t{\n\t\tif ($roles = Role::fetchAll(PDO::load())) {\n\t\t\tHeaders::contentType('application/json');\n\t\t\techo json_encode($roles);\n\t\t} else {\n\t\t\tthrow new HTTPException('Error fetching roles', HTTP::INTERNAL_SERVER_ERROR);\n\t\t}\n\t});\n\n\t$api();\n} catch (HTTPException $e) {\n\tHeaders::status($e->getCode());\n\tHeaders::contentType('application/json');\n\techo json_encode($e);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914106,"cells":{"blob_id":{"kind":"string","value":"1ea0afcddce9ffde9274b324d172296f4a719f62"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"DeDoOozZz/brighterycms"},"path":{"kind":"string","value":"/source/brightery/core/Style.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2113,"string":"2,113"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n * \n */\nclass Style {\n\n private $instance;\n private $interface;\n private $styleName;\n private $styleAssets;\n private $styleUri;\n private $styleDirection;\n public $stylePath;\n\n public function __construct() {\n Log::set('Initialize Style class');\n $this->instance = & Brightery::SuperInstance();\n $this->initialize();\n }\n\n private function initialize() {\n $this->interface = $this->instance->Twig->interface;\n $this->styleName = $this->instance->Twig->styleName;\n $this->styleDirection = $this->instance->language->getLanguageDirection();\n $this->stylePath = ROOT . '/styles/' . $this->interface . '/' . $this->styleName;\n $this->styleUri = BASE_URL . 'styles/' . $this->interface . '/' . $this->styleName;\n if (!is_dir($this->stylePath))\n Brightery::error_message($this->stylePath . \" is missed.\");\n $this->parsing();\n $this->createStyleConstants();\n }\n\n private function parsing() {\n $style_ini = $this->stylePath . '/style.ini';\n if (!file_exists($style_ini))\n Brightery::error_message($style_ini . \" is missed.\");\n $this->styleAssets = parse_ini_file($style_ini, true);\n }\n\n private function createStyleConstants() {\n $settings = $this->styleAssets[$this->styleDirection];\n define('STYLE_IMAGES', $this->styleUri . '/assets/' . $settings['images']);\n define('STYLE_JS', $this->styleUri . '/assets/' . $settings['js']);\n define('STYLE_CSS', $this->styleUri . '/assets/' . $settings['css']);\n define('MODULE_URL', BASE_URL . 'source/app/modules/');\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914107,"cells":{"blob_id":{"kind":"string","value":"506a18bd0dd3aa08eac41a157877680f69cfaa83"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"didembilgihan/Bookmark-Management-System"},"path":{"kind":"string","value":"/register.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":679,"string":"679"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"prepare($sql);\r\n $hash_password = password_hash($password, PASSWORD_DEFAULT) ;\r\n $stmt->execute([$name, $email, $hash_password]);\r\n\r\n addMessage(\"Registered\");\r\n header(\"Location: ?page=loginForm\") ;\r\n exit ;\r\n\r\n } catch(PDOException $ex) {\r\n addMessage(\"Insert Failed!\") ;\r\n header(\"Location: ?page=registerForm\");\r\n exit;\r\n }\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914108,"cells":{"blob_id":{"kind":"string","value":"24fac03e9a4d620c1c8575f84ec56252fc424fc1"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"jwmcpeak/TutsPlus-PHP-Design-Patterns"},"path":{"kind":"string","value":"/chain-of-responsibility.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1907,"string":"1,907"},"score":{"kind":"number","value":3.5625,"string":"3.5625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"nextLogger = $logger;\n }\n \n public function log(int $level, string $message) {\n if ($this->level <= $level) {\n $this->write(\"$message\\n\");\n }\n\n if ($this->nextLogger != null) {\n $this->nextLogger->log($level, $message);\n }\n }\n\n protected abstract function write(string $message);\n}\n\nclass ConsoleLog extends AbstractLog {\n public function __construct(int $logLevel) {\n $this->level = $logLevel;\n }\n\n protected function write(string $message) {\n echo \"CONSOLE: $message\";\n }\n}\n\nclass FileLog extends AbstractLog {\n public function __construct(int $logLevel) {\n $this->level = $logLevel;\n }\n\n protected function write(string $message) {\n echo \"FILE: $message\";\n }\n}\n\nclass EventLog extends AbstractLog {\n public function __construct(int $logLevel) {\n $this->level = $logLevel;\n }\n\n protected function write(string $message) {\n echo \"EVENT: $message\";\n }\n}\n\nclass AppLog {\n private $logChain;\n public function __construct() {\n $console = new ConsoleLog(LogType::Information);\n $debug = new FileLog(LogType::Debug);\n $error = new EventLog(LogType::Error);\n\n $console->setNext($debug);\n $debug->setNext($error);\n\n $this->logChain = $console;\n }\n\n public function log(int $level, string $message) {\n $this->logChain->log($level, $message);\n }\n}\n\n\n$app = new AppLog();\n\n$app->log(LogType::Information, \"This is information.\");\n$app->log(LogType::Debug, \"This is debug.\");\n$app->log(LogType::Error, \"This is error.\");\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914109,"cells":{"blob_id":{"kind":"string","value":"cc0de231c8619e429820f088d5833fd27b91758c"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"gungungggun/workspace"},"path":{"kind":"string","value":"/collatz-problem/php.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":391,"string":"391"},"score":{"kind":"number","value":3.65625,"string":"3.65625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" 'Aliliin'];\n // 设置一个偏移位置的值\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n // 检查一个偏移位置是否存在\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n // 复位一个偏移位置的值\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n // 获取一个偏移位置的值\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914111,"cells":{"blob_id":{"kind":"string","value":"542288972f173c2f99f6a4ea0a15c1cf85f82e56"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"crow1796/rev-cms"},"path":{"kind":"string","value":"/RevCMS/src/Http/Controllers/PagesController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2220,"string":"2,220"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"menuOrder = 2;\n \treturn $this->makeView('revcms.pages.index', 'Pages');\n }\n\n /**\n * Create new page.\n * @param Request $request \n * @return mixed \n */\n public function store(Request $request){\n \t$this->checkAjaxRequest($request);\n\n \t$page = $this->rev\n \t\t\t->cms()\n \t\t\t->createPage($request->all());\n\n \tif(!$page instanceof Page) {\n // If page is not equal to false/null, then return all errors with a failed status, else return failed\n return $page ? $page->errors()->all() + ['status' => false] : [0 => 'Something went wrong. Please make sure that the permalink is unique.','status' => false];\n \t}\n\n $response = ['status' => true];\n\n \treturn $response;\n }\n\n public function create(){\n $this->menuOrder = 2;\n \treturn $this->makeView('revcms.pages.create', 'New Page');\n }\n\n public function edit($id){\n dd($id);\n }\n\n /**\n * Retreive all pages.\n * @param Request $request \n * @return array \n */\n public function allPages(Request $request){\n $this->checkAjaxRequest($request);\n \n return $this->rev\n ->cms()\n ->getPageArray();\n }\n\n /**\n * Populate controllers and layouts fields.\n * @param Request $request \n * @return array \n */\n public function populateFields(Request $request){\n $fieldValues = [\n 'controllers' => $this->rev->mvc()->allControllers(),\n 'layouts' => $this->rev->cms()->getActiveThemesLayouts(),\n ];\n return $fieldValues;\n }\n\n /**\n * Generate slug and action name based on page's title.\n * @param Request $request \n * @return array \n */\n public function generateFields(Request $request){\n \t$this->checkAjaxRequest($request);\n\n \treturn $this->rev\n \t\t\t\t->cms()\n \t\t\t\t->generateFieldsFor($request->page_title);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914112,"cells":{"blob_id":{"kind":"string","value":"a8967ab776debe04d03cc200d88f94469ecb16c6"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"mobilejazz-contrib/yii2-api"},"path":{"kind":"string","value":"/app/frontend/models/PasswordResetRequestForm.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1520,"string":"1,520"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause","MIT"],"string":"[\n \"BSD-3-Clause\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" 'trim'],\n\t\t\t\t['email', 'required'],\n\t\t\t\t['email', 'email'],\n\t\t\t\t['email', 'exist',\n\t\t\t\t 'targetClass' => '\\common\\models\\User',\n\t\t\t\t 'filter' => ['status' => User::STATUS_ACTIVE],\n\t\t\t\t 'message' => 'There is no user with such email.'\n\t\t\t\t],\n\t\t\t];\n\t\t}\n\n\t\t/**\n\t\t * Sends an email with a link, for resetting the password.\n\t\t *\n\t\t * @return boolean whether the email was send\n\t\t */\n\t\tpublic function sendEmail ()\n\t\t{\n\t\t\t/* @var $user User */\n\t\t\t$user = User::findOne ([\n\t\t\t\t\t\t\t\t\t 'status' => User::STATUS_ACTIVE,\n\t\t\t\t\t\t\t\t\t 'email' => $this->email,\n\t\t\t\t\t\t\t\t ]);\n\n\t\t\tif ($user)\n\t\t\t{\n\t\t\t\tif (!User::isPasswordResetTokenValid ($user->password_reset_token))\n\t\t\t\t{\n\t\t\t\t\t$user->generatePasswordResetToken ();\n\t\t\t\t}\n\n\t\t\t\tif ($user->save ())\n\t\t\t\t{\n\t\t\t\t\t$data = [\n\t\t\t\t\t\t'name' => $user->name,\n\t\t\t\t\t\t'url' => \\Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password','token'=>$user->password_reset_token])\n\t\t\t\t\t];\n\n\t\t\t\t\treturn \\Yii::$app->mailer\n\t\t\t\t\t\t->compose ('recover-password-'.\\Yii::$app->language, $data)\n\t\t\t\t\t\t->setGlobalMergeVars ($data)\n\t\t\t\t\t\t->setTo ($this->email)\n\t\t\t\t\t\t->setSubject (\\Yii::t('app','Password reset request'))\n\t\t\t\t\t\t->enableAsync ()\n\t\t\t\t\t\t->send ();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\t}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914113,"cells":{"blob_id":{"kind":"string","value":"6e3ebe6c5d9ea851939dcca52c43e0ade43ce04d"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"cddsky2014/121"},"path":{"kind":"string","value":"/php20160504/array_keys.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":228,"string":"228"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\"lucy\",\"age\"=>23,\"addr\"=>\"USA\");\t\n\tprint_r($arr1);\t\n\tprint_r(array_keys($arr1));\n\tfunction uarray_keys($a){\t\t\n\t\t$arr = array();\n\t\tforeach($a as $k=>$v){\n\t\t\t$arr[]=$k;\n\t\t}\n\t\treturn $arr;\n\t}\n\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914114,"cells":{"blob_id":{"kind":"string","value":"5a3e69b98671dc9a55dc4728743fdf5efb07e72f"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"medV3dkO/bootcamp"},"path":{"kind":"string","value":"/admin/login.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4199,"string":"4,199"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n\n \n \n Авторизация | BOOTCAMP\n \n \n\n
\n
\n
\n
\n
\n
\n
\n Авторизуйтесь\n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n Текст ошибки\n
\n
\n \n
\n
\n
\n
\n
\n
\n
\n\n\n';\n\telse{\n\t\t//вот так данные можно отправлять без проверки вовсе, ни чего очень плохого случиться не должно. \n\t\t//PDO все заэкранирует и превратит в текст. \n\t\t//Можно разве что проверять длинну текста и какие то специфическиие данные\n\n\t\t$sql = \"SELECT * FROM admin_users WHERE login=:login AND password=:pass\";//Формируем запрос без данных\n\t\t$result = $pdo->prepare($sql);\n\t\t$result->bindvalue(':login', $_POST['login']);\t//Заполняем данные\n\t\t$result->bindvalue(':pass', md5($_POST['password']));\t//Заполняем данные. Пароли хранить в открытом виде, дело такое. Поэтому двойной md5)\n\t\t$result->execute( );\t\t\t\t\t\t\t//Выполняем запросы\n\t\t$result = $result->fetchAll();\t\t\t\t\t//переводим обьект ПДО в массив данных, для удобной работы\n\n\t\tif (count($result)>0) {//Если база вернула 1 значение, значит и логин и пароль совпали. отлично\n\t\t\techo 'Ура! Мы авторизировались! Перенаправляем в панель...'; \n\t\t\t$_SESSION['user'] = $result[0];//сохраняем обьект пользователя в сессии\n\t\t\theader(\"refresh: 3; url=https://medv3dko.xyz/admin/\");\n\t\t\t\n\t\t}else echo 'Логин или пароль не верный или пользователь не существует. Попробовать ещё раз';\n\t}\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914115,"cells":{"blob_id":{"kind":"string","value":"02acd4cbae8054282c69b34610987f6f6d578348"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"amsify42/php-domfinder"},"path":{"kind":"string","value":"/tests/TestXML.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":531,"string":"531"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"domFinder = new DOMFinder(getSample('books.xml'));\n\t}\n\n\tpublic function process()\n\t{\n\t\t$books \t= $this->domFinder->getElements('book');\n\t\tif($books->length) {\n\t\t\tforeach($books as $book) {\n\t\t\t\techo $this->domFinder->getHtml($book);\n\t\t\t}\n\t\t}\n\t\techo \"\\n\\n\";\n\t\t$book \t= $this->domFinder->find('book')->byId('bk101')->first();\n\t\tif($book) {\n\t\t\techo $this->domFinder->getHtml($book);\n\t\t}\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914116,"cells":{"blob_id":{"kind":"string","value":"c826aef2b0721c6bd99c9f626c20cefb41d94848"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"chris-peng-1244/otc-cms"},"path":{"kind":"string","value":"/app/Services/Repositories/Customer/CustomerRepository.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1017,"string":"1,017"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"get();\n }\n\n /**\n * @param int $limit\n * @return Paginator\n */\n public function paginate($limit)\n {\n return Customer::paginate($limit);\n }\n\n /**\n * @param string $query\n * @return Collection\n */\n public function searchByNameOrId($query)\n {\n if (is_numeric($query)) {\n $customer = Customer::find((int) $query);\n return $customer ? collect($customer) : collect([]);\n }\n\n return $this->searchByName($query);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914117,"cells":{"blob_id":{"kind":"string","value":"f3304a721fa0d0a3a94a8fbe60a86450aa257624"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"kuljitsingh94/HTMLParse"},"path":{"kind":"string","value":"/studyGuideGen.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3527,"string":"3,527"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" $value) {\n if(strpos($value, $tag_close) !== FALSE){\n $result[] = trim(substr($value, 0, strpos($value, $tag_close)));\n }\n }\n return $result;\n}\n\n$output = fopen('./output.txt','w');\n\nfor($hwNum = 1; $hwNum <= 5; $hwNum++) {\n if($hwNum < 10) \n $URL = $URLbegin.\"0\".$hwNum.$URLend;\n else\n $URL = $URLbegin.$hwNum.$URLend;\n#download HTML from URL and save as a string\n $file = file_get_contents($URL);\n\n#get the number of questions from the num_quests variable\n#in the HTML/JavaScript\n $NUM_QUESTIONS = tag_contents($file, \"num_quests =\",\";\");\n\n#save as an integer since tag_contents returns strings\n#also look at subscript 1 since subscript 0 is garbage\n $NUM_QUESTIONS = trim($NUM_QUESTIONS[1])+0;\n\n#remove all head tag info, leaving just the body\n#which is all we want\n $body = substr($file,strpos($file, \"
\"));\n#get all comparison expressions since this is where\n#the answers are located\n    $parsed= tag_contents($body, 'if (', ')');\n    $questions= tag_contents($body, '
', '
');\n array_unshift($questions, \"placeholder\");\n //var_dump($questions);\n $answers = array();\n $i = 0;\n\n#all string parsing below requires knowledge of the\n#structure of the\n#downloaded HTML and requires pattern recognition\n\n#traverse array full of comparison expressions\n foreach($parsed as $key){\n\n #break the comparison expressions into separate\n #variables, delimited by &&\n $ifStatment = explode(\"&&\",$key);\n\n #this checks if the if statement we grabbed\n #pertains to answers or something else\n if(!strpos($key,\"hwkform\")) {\n continue;\n }\n\n #if previous if statement fails, we have an\n #answer if statement\n $i++;\n\n #traverse each comparison expression\n foreach($ifStatment as $value){\n \n #remove whitespace\n $value = trim($value);\n \n #! tells us its a wrong answer, so \n #if the ! is not there, meaning its a\n #right answer\n if($value[0]!='!'){\n\n #grab the value of right answers,0123\n $answer = tag_contents($value, '[',']');\n \n #output formatting, convert 0123 -> ABCD\n #by ascii value usage\n if(isset($answers[$i]))\n $answers[$i].=','.chr($answer[0]+65);\n else\n $answers[$i]=chr($answer[0]+65);\n }\n }\n }\n\n#error checking, if NUM_QUESTIONS != i then we\n#got an extra if statement comparison expression\n if($i!=$NUM_QUESTIONS) {\n echo \"\\n\\n\\tERROR PARSING HTML! DOUBLE CHECK ANSWERS!!\\n\\n\\n\";\n }\n\n echo \"\\tGenerating Study Guide Output File for $hwNum\\n\";\n#output questions and answers\n \n \n //var_dump($answers);\n#write to output file\n for($i = 1; $i<=$NUM_QUESTIONS ; $i++) {\n fwrite($output, $questions[$i].\"\".$answers[$i].'');\n }\n\n foreach($answers as $question => $ans) {\n \n //usleep(0250000);\n echo \"Question $question\\t: $ans\\n\";\n }\n}\n?>\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914118,"cells":{"blob_id":{"kind":"string","value":"0ea15d126f06d7a3274cdd342b8f1c98a70630c8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"jeyroik/extas-q-crawlers-jira"},"path":{"kind":"string","value":"/src/components/quality/crawlers/jira/JiraIssueChangelogItem.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":762,"string":"762"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"config[static::FIELD__CREATED] ?? '';\n\n return $asTimestamp ? strtotime($created) : $created;\n }\n\n /**\n * @return string\n */\n protected function getSubjectForExtension(): string\n {\n return static::SUBJECT;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914119,"cells":{"blob_id":{"kind":"string","value":"1a150ec40f4d58b1d254c01c7345271e475296e9"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"LaunaKay/codingdojoserver"},"path":{"kind":"string","value":"/WishList/application/models/M_Wish.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":666,"string":"666"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"session->userdata('id');\n $wish = array\n (\n 'item' => $wish['item'],\n 'user_id' => $id['id']\n );\n $this->db->insert('wishes', $wish);\n }\n\n public function removewish($wishID)\n {\n $this->db->where('id', $wishID);\n $this->db->delete('wishes');\n $this->db->where('item_id', $wishID);\n $this->db->delete('wishlists');\n }\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914120,"cells":{"blob_id":{"kind":"string","value":"5ad38c6f4a2be085bef4680975cea39668b6d4b3"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"lazyman00/ajsas"},"path":{"kind":"string","value":"/pages/Front_end/allarticle/send_email_1.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4324,"string":"4,324"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n\nquery($sql_article);\n$row_article = $query_article->fetch_assoc();\n\nfor($i=0; $iquery($sql);\n\t\t$row = $query->fetch_assoc();\n\n// echo \"
\";\n// print_r($_POST);\n// echo \"
\";\n// exit();\n\t\t$mail = new PHPMailer;\n\t\t$mail->CharSet = \"utf-8\";\n\t\t$mail->isSMTP();\n// $mail->Debugoutput = 'html';\n\t\t$mail->Host = 'smtp.gmail.com';\n\t\t$mail->Port = 587;\n\t\t$mail->SMTPSecure = 'tls';\n\t\t$mail->SMTPAuth = true;\n\n\n$gmail_username = \"darktolightll@gmail.com\"; // gmail ที่ใช้ส่ง\n$gmail_password = \"SunandMoon00\"; // รหัสผ่าน gmail\n// ตั้งค่าอนุญาตการใช้งานได้ที่นี่ https://myaccount.google.com/lesssecureapps?pli=1\n\n\n$sender = \"Article Review Request [AJSAS]\"; // ชื่อผู้ส่ง\n$email_sender = \"noreply@ibsone.com\"; // เมล์ผู้ส่ง \n$email_receiver = $_POST[\"email\"][$i]; // เมล์ผู้รับ ***\n// $email_receiver = \"darktolightll@gmail.com\";\n\n$subject = \"จดหมายเทียบเชิญผู้ทรงคุณวุฒิ\"; // หัวข้อเมล์\n\n\n$mail->Username = $gmail_username;\n$mail->Password = $gmail_password;\n$mail->setFrom($email_sender, $sender);\n$mail->addAddress($email_receiver);\n$mail->SMTPOptions = array(\n\t'ssl' => array(\n\t\t'verify_peer' => false,\n\t\t'verify_peer_name' => false,\n\t\t'allow_self_signed' => true\n\t)\n);\n$mail->Subject = $subject;\n// $mail->SMTPDebug = 1;\n\n$email_content = \"\n\n\n\nDocument\n\n\n

Dear \".$row['pre_en_short'].\" \".$row['name_en'].\" \".$row['surname_en'].\"

\n

I believe that you would serve as an excellent reviewer of the manuscript, \".$row_article['article_name_en'].\"

\n

which has been submitted to Academic Journal of Science and Applied Science. The submission's abstract is

\n

inserted below, and I hope that you will consider undertaking this important task for us.

\n\n

Please log into the journal web site by \".$row_article['date_article'].\" to indicate whether you will undertake the

\n

review or not, as well as to access the submission and to record your review and recommendation. After this job

\n

is done, you will receive a THB 1,000 cash prize.

\n\n

The review itself is due \".$row_article['date_article'].\".

\n

Submission URL: >> ระบบวารสารวิชาการวิทยาศาสตร์และวิทยาศาสตร์ประยุกต์ <<

\n
\n

Assoc. Prof. Dr. Issara Inchan

\n

Faculty of Science and Technology, Uttaradit Rajabhat University.

\n

ajsas@uru.ac.th

\n
\n

\".$row_article['article_name_en'].\"

\n

\".$row_article['abstract_en'].\"

\n

.................

\n\n\";\n\n// ถ้ามี email ผู้รับ\nif($email_receiver){\n\t$mail->msgHTML($email_content);\n\n\tif ($mail->send()) { \n\t\t$sql = sprintf(\"INSERT INTO `tb_sendmail`(`id_sendMail`, `user_id`, `article_id`) VALUES (%s,%s,%s)\",\n\t\t\tGetSQLValueString($_POST['id_sendMail'],'text'),\n\t\t\tGetSQLValueString($_POST['user_id'][$i],'text'),\n\t\t\tGetSQLValueString($row_article['article_id'],'text'));\n\t\t$query = $conn->query($sql);\n\t}\n\t\n}\n\n$mail->smtpClose();\n\n}\n}\n// echo \"ระบบได้ส่งข้อความไปเรียบร้อย\";\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914121,"cells":{"blob_id":{"kind":"string","value":"dd89c7c961bdf80d129c570cdcd9b8654e59cc31"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"crebiz76/phptest"},"path":{"kind":"string","value":"/ch19/quiz_result.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2004,"string":"2,004"},"score":{"kind":"number","value":3.140625,"string":"3.140625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n\n\n\n\n \n \n 퀴즈 응시 결과\n\n\n

퀴즈 응시 결과

\nquery($sql);\n $count = $stmh->rowCount(); \n } catch (PDOException $Exception){\n print \"오류 :\".$Exception->getMessage();\n }\n \n $i = 0;\n $score = 0;\n while($row=$stmh->fetch(PDO::FETCH_ASSOC)){\n if($ans[$i] == $row['dap'])\n {\n $score++;\n $correct[$i] = 'O';\n }\n else\n {\n $correct[$i] = 'X';\n }\n $i++;\n }\n \n $result = '';\n switch($score)\n {\n case 0: \n case 1: $result = '미흡'; break;\n case 2: $result = '보통'; break;\n case 3: $result = '우수'; break;\n }\n\n?>\n

판정:

\n \n \n \n \n \n \n \nquery($sql);\n $count = $stmh->rowCount(); \n } catch (PDOException $Exception){\n print \"오류 :\".$Exception->getMessage();\n }\n\n $j = 0;\n while($row=$stmh->fetch(PDO::FETCH_ASSOC)){\n?>\n \n \n \n \n \n \n\n
순번선택정답결과
\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914122,"cells":{"blob_id":{"kind":"string","value":"175bc2a392f215181f29fe73a3201dc91e41b1e4"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"boukeversteegh/DecoratorModule"},"path":{"kind":"string","value":"/test/src/Fixtures/Library/lendableTrait.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":246,"string":"246"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"lending_user = $user;\n\t}\n\n\tpublic function getLendingTo()\n\t{\n\t\treturn $this->lending_user;\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914123,"cells":{"blob_id":{"kind":"string","value":"92600040e18121fbbe05ee90c35734a72af4e6c2"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"walterra/J4p5Bundle"},"path":{"kind":"string","value":"/j4p5/parse/easy_parser.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":841,"string":"841"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"call = $this->action; //array();\n $this->strategy = ($strategy ? $strategy : new default_parser_strategy());\n /*\n foreach($this->action as $k => $body) {\n $this->call[$k] = create_function( '$tokens', preg_replace('/{(\\d+)}/', '$tokens[\\\\1]', $body));\n }\n */\n }\n \n function reduce($action, $tokens) {\n $call = $this->call[$action];\n return jsly::$call($tokens);\n }\n \n function parse($symbol, $lex, $strategy = null) {\n return parent::parse($symbol, $lex, $this->strategy);\n }\n}\n\n \n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914124,"cells":{"blob_id":{"kind":"string","value":"053035df4f0eb6ebbf8b2f9204d0cf2bdfd3653b"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"HouraiSyuto/php_practice"},"path":{"kind":"string","value":"/part2/chapter5/reference_array.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":342,"string":"342"},"score":{"kind":"number","value":3.65625,"string":"3.65625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" '325674481145757',\n 'app_secret' => '',\n 'default_graph_version' => 'v2.8',\n]);\n\nMyController::$fb->setDefaultAccessToken('325674481145757|');\n\n// On demande une instance sur la class ApiController qui permet de lancer une requette à l'API Facebook\n$api = ApiController::getInstance();\n\nfunction array_sort($array, $on, $order=SORT_DESC)\n{\n $new_array = array();\n $sortable_array = array();\n\n if (count($array) > 0) {\n foreach ($array as $k => $v) {\n if (is_array($v)) {\n foreach ($v as $k2 => $v2) {\n if ($k2 == $on) {\n $sortable_array[$k] = $v2;\n }\n }\n } else {\n $sortable_array[$k] = $v;\n }\n }\n\n switch ($order) {\n case SORT_ASC:\n asort($sortable_array);\n break;\n case SORT_DESC:\n arsort($sortable_array);\n break;\n }\n\n foreach ($sortable_array as $k => $v) {\n $new_array[$k] = $array[$k];\n }\n }\n\n return $new_array;\n}\n\n\n\n\n\n// On regarde si un concours est terminé\n$request = MyController::$bdd->query('SELECT id_concours, end_date FROM concours WHERE status = 1');\n$result = $request->fetch(PDO::FETCH_ASSOC);\n\nif(!empty($result['id_concours'])) {\n $concours = $result['id_concours'];\n $today = date('U');\n $end = date('U', strtotime($result['end_date']));\n\n if($result['end_date'] <= $today) {\n // On stoppe le concours s'il est terminé\n $request = MyController::$bdd->exec('UPDATE concours SET status = 0 WHERE status = 1');\n $request = MyController::$bdd->exec('UPDATE users SET participation = 0');\n\n\n\n /* GET LIKES */\n\n $resultats = array();\n $count = 0;\n\n $request = MyController::$bdd->query('SELECT * FROM photos WHERE id_concours = '. $concours);\n $result = $request->fetchAll(PDO::FETCH_ASSOC);\n\n foreach ($result as $photo) {\n $likes = $api->getRequest($photo['link_like']);\n\n $countLikes = (isset($likes['share'])) ? $likes['share']['share_count'] : 0;\n\n $request = MyController::$bdd->query('SELECT first_name, name FROM users WHERE id_user = '. $photo['id_user']);\n $result = $request->fetch(PDO::FETCH_ASSOC);\n\n $resultats[$count]['user'] = $result['first_name'] . ' ' . $result['name'];\n $resultats[$count]['link_photo'] = $photo['link_photo'];\n $resultats[$count]['likes'] = $countLikes;\n $count++;\n }\n\n $resultats = array_sort($resultats, 'likes');\n\n\n\n $data = array(\n 'message' => 'Découvrez ci-dessous la photo du gagnant du concours pardon maman !',\n 'link' => $resultats[0]['link_photo']\n );\n\n\n // On récupère les id de tous les utilisateurs\n $request = MyController::$bdd->query('SELECT id_user FROM users');\n $result = $request->fetchAll(PDO::FETCH_ASSOC);\n\n foreach($result as $id) {\n $api->postRequest('/'.$id['id_user'].'/feed', $data);\n }\n\n\n // Send mail to admin\n\n $accounts = $api->getRequest('/app/roles', '325674481145757|2_coNBtFEJH6uQenqtAHJCLBcaY');\n\n foreach ($accounts['data'] as $key => $account) {\n if($account['role'] == 'administrators') {\n $administrators[] = $account['user'];\n }\n }\n\n foreach ($administrators as $id) {\n $email = $api->getRequest('/'.$id.'?fields=email', '325674481145757|2_coNBtFEJH6uQenqtAHJCLBcaY');\n $emails[] = $email['email'];\n }\n\n\n\n $body = \"\";\n $body .= \"\";\n $body .= \"\";\n $body .= \"\";\n $body .= \"\";\n $body .= \"\";\n $body .= \"\";\n foreach ($resultats as $resultat) {\n $body .= \"\";\n $body .= \"\";\n $body .= \"\";\n $body .= \"\";\n $body .= \"\";\n }\n $body .= \"
Userlink photolikes
\".$resultat['user'].\"\".$resultat['link_photo'].\"\".$resultat['likes'].\"
\";\n\n foreach($emails as $email) {\n\n $mail = new PHPMailer;\n $mail->isHTML(true);\n $mail->setFrom('concourspardonmaman@no-reply.fr', 'Concours Photo Pardon Maman');\n $mail->addAddress($email);\n $mail->addReplyTo('info@example.com', 'Information');\n $mail->Subject = 'Résultats du concours';\n $mail->Body = $body;\n $mail->send();\n\n }\n\n\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914126,"cells":{"blob_id":{"kind":"string","value":"7676e84c098398d2e87756aabc10b5c82ee4077f"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"nmusco/assuresign-sdk-php-v2"},"path":{"kind":"string","value":"/src/StructType/PingResult.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1265,"string":"1,265"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"setSuccess($success);\n }\n /**\n * Get Success value\n * @return bool\n */\n public function getSuccess()\n {\n return $this->Success;\n }\n /**\n * Set Success value\n * @param bool $success\n * @return \\Nmusco\\AssureSign\\v2\\StructType\\PingResult\n */\n public function setSuccess($success = null)\n {\n // validation for constraint: boolean\n if (!is_null($success) && !is_bool($success)) {\n throw new \\InvalidArgumentException(sprintf('Invalid value %s, please provide a bool, %s given', var_export($success, true), gettype($success)), __LINE__);\n }\n $this->Success = $success;\n return $this;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914127,"cells":{"blob_id":{"kind":"string","value":"c0372bf6d73553f6f6227fe1bd7dcd8672049bd8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"taufik-ashari/slightly-big-Flip"},"path":{"kind":"string","value":"/disburse/getById.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1259,"string":"1,259"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"getConnection();\n \n// prepare product object\n$disburse = new Disburse($db);\n \n// set ID property of record to read\n$disburse->id = isset($_GET['id']) ? $_GET['id'] : die();\n \n// read the details of product to be edited\n$disburse->readOne();\n \nif($disburse->id!=null){\n // create array\n $disburses_arr = array(\n \"id\" => $disburse->id,\n \"time_served\" => $disburse->time_served,\n \"receipt\" => $disburse->receipt,\n \"status\" => $disburse->status\n );\n \n // set response code - 200 OK\n http_response_code(200);\n \n // make it json format\n echo json_encode($disburses_arr);\n}\n \nelse{\n // set response code - 404 Not found\n http_response_code(404);\n \n // tell the user product does not exist\n echo json_encode(array(\"message\" => \"Disburse does not exist.\"));\n}\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914128,"cells":{"blob_id":{"kind":"string","value":"a3c53217dc2801449e58a72aab1e6d9ff4272f68"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"jamesjoel/tss_12_30"},"path":{"kind":"string","value":"/ravi/ci/application/views/admin/view_users.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1067,"string":"1,067"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n
\n
\n\n
\n

View All User

\n \n \t\n \t\t\n \t\t\n \t\t\n \t\t\n \t\t\n \t\t\n \t\n \tresult_array() as $data)\n \t{ \n \t\tif($data['status']==1)\n \t\t\t$a = \"Enable\";\n \t\telse\n \t\t\t$a = \"Disable\";\n\n \t\t?>\n \t\t\n \t\t\t\n \t\t\t\n \t\t\t\n \t\t\t\n \t\t\t\n \t\t\t\n \t\t\n \t\n
S.No.Full NameUsernameContactStatusChange
\" class=\"btn btn-sm btn-info\">Change
\n
\n
\n
\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914129,"cells":{"blob_id":{"kind":"string","value":"511c2f3a8e3ce616bc2fa8763ba767747f310b92"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"ghuysmans/php-u2flib-server"},"path":{"kind":"string","value":"/examples/pdo/login.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1546,"string":"1,546"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause","BSD-2-Clause"],"string":"[\n \"BSD-3-Clause\",\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"pdo->prepare('SELECT user_id FROM user WHERE user=?');\n $sel->execute(array($username)); //FIXME $password\n return $sel->fetchColumn(0);\n }\n\n protected function login($user_id) {\n $_SESSION['user_id'] = $user_id;\n }\n}\n\n\n$pdo = new PDO('mysql:dbname=u2f', 'test', 'bonjour');\n$login = new L($pdo);\nif (isset($_GET['force'])) {\n $_SESSION['user_id'] = $_GET['force'];\n header('Location: login.php');\n}\n$login->route();\n?>\n\n\n\nPHP U2F example\n\n\n\n\n\n\n
\n\n
\n
\n

\n \n

\n

\n

\n

\n
\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914130,"cells":{"blob_id":{"kind":"string","value":"66f48156e0cbdf7529838ce463fc6295fde2af12"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"HeleneBoivin/PHP_5_Les_tableaux"},"path":{"kind":"string","value":"/exercice1/index.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":537,"string":"537"},"score":{"kind":"number","value":3.40625,"string":"3.40625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n\n\nExercice1\n

PHP - Partie 5 - Exercice 1

\n\n\n

Créer un tableau months et l'initialiser avec les mois de l'année

\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914131,"cells":{"blob_id":{"kind":"string","value":"eba7dc0a8bd0a64a96bfc25112b8c15b634e7f43"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"salvoab/laravel-comics"},"path":{"kind":"string","value":"/database/seeds/AuthorSeeder.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":459,"string":"459"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"name = $faker->firstName();\n $author->lastname = $faker->lastName;\n $author->save();\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914132,"cells":{"blob_id":{"kind":"string","value":"c3941a123fc242017610c46abdec247cf902d342"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"loveorigami/shop_prototype"},"path":{"kind":"string","value":"/tests/widgets/AdminCreateSubcategoryWidgetTests.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7983,"string":"7,983"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"widget = new AdminCreateSubcategoryWidget();\n }\n \n /**\n * Тестирует свойства AdminCreateSubcategoryWidget\n */\n public function testProperties()\n {\n $reflection = new \\ReflectionClass(AdminCreateSubcategoryWidget::class);\n \n $this->assertTrue($reflection->hasProperty('form'));\n $this->assertTrue($reflection->hasProperty('categories'));\n $this->assertTrue($reflection->hasProperty('header'));\n $this->assertTrue($reflection->hasProperty('template'));\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::setForm\n */\n public function testSetForm()\n {\n $form = new class() extends AbstractBaseForm {};\n \n $this->widget->setForm($form);\n \n $reflection = new \\ReflectionProperty($this->widget, 'form');\n $reflection->setAccessible(true);\n $result = $reflection->getValue($this->widget);\n \n $this->assertInstanceOf(AbstractBaseForm::class, $result);\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::setCategories\n */\n public function testSetCategories()\n {\n $categories = [new class() {}];\n \n $this->widget->setCategories($categories);\n \n $reflection = new \\ReflectionProperty($this->widget, 'categories');\n $reflection->setAccessible(true);\n $result = $reflection->getValue($this->widget);\n \n $this->assertInternalType('array', $result);\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::setHeader\n */\n public function testSetHeader()\n {\n $header = 'Header';\n \n $this->widget->setHeader($header);\n \n $reflection = new \\ReflectionProperty($this->widget, 'header');\n $reflection->setAccessible(true);\n $result = $reflection->getValue($this->widget);\n \n $this->assertInternalType('string', $result);\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::setTemplate\n */\n public function testSetTemplate()\n {\n $template = 'Template';\n \n $this->widget->setTemplate($template);\n \n $reflection = new \\ReflectionProperty($this->widget, 'template');\n $reflection->setAccessible(true);\n $result = $reflection->getValue($this->widget);\n \n $this->assertInternalType('string', $result);\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::run\n * если пуст AdminCreateSubcategoryWidget::form\n * @expectedException ErrorException\n * @expectedExceptionMessage Отсутствуют необходимые данные: form\n */\n public function testRunEmptyForm()\n {\n $result = $this->widget->run();\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::run\n * если пуст AdminCreateSubcategoryWidget::categories\n * @expectedException ErrorException\n * @expectedExceptionMessage Отсутствуют необходимые данные: categories\n */\n public function testRunEmptyCategories()\n {\n $form = new class() extends AbstractBaseForm {};\n \n $reflection = new \\ReflectionProperty($this->widget, 'form');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, $form);\n \n $result = $this->widget->run();\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::run\n * если пуст AdminCreateSubcategoryWidget::header\n * @expectedException ErrorException\n * @expectedExceptionMessage Отсутствуют необходимые данные: header\n */\n public function testRunEmptyHeader()\n {\n $mock = new class() {};\n \n $reflection = new \\ReflectionProperty($this->widget, 'form');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, $mock);\n \n $reflection = new \\ReflectionProperty($this->widget, 'categories');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, [$mock]);\n \n $result = $this->widget->run();\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::run\n * если пуст AdminCreateSubcategoryWidget::template\n * @expectedException ErrorException\n * @expectedExceptionMessage Отсутствуют необходимые данные: template\n */\n public function testRunEmptyTemplate()\n {\n $mock = new class() {};\n \n $reflection = new \\ReflectionProperty($this->widget, 'form');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, $mock);\n \n $reflection = new \\ReflectionProperty($this->widget, 'categories');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, [$mock]);\n \n $reflection = new \\ReflectionProperty($this->widget, 'header');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, 'Header');\n \n $result = $this->widget->run();\n }\n \n /**\n * Тестирует метод AdminCreateSubcategoryWidget::run\n */\n public function testRun()\n {\n $form = new class() extends AbstractBaseForm {\n public $name;\n public $seocode;\n public $id_category;\n public $active;\n };\n \n $categories = [\n new class() {\n public $id = 1;\n public $name = 'One';\n },\n new class() {\n public $id = 2;\n public $name = 'Two';\n },\n ];\n \n $reflection = new \\ReflectionProperty($this->widget, 'form');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, $form);\n \n $reflection = new \\ReflectionProperty($this->widget, 'categories');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, $categories);\n \n $reflection = new \\ReflectionProperty($this->widget, 'header');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, 'Header');\n \n $reflection = new \\ReflectionProperty($this->widget, 'template');\n $reflection->setAccessible(true);\n $reflection->setValue($this->widget, 'admin-create-subcategory.twig');\n \n $result = $this->widget->run();\n \n $this->assertRegExp('#

Header

#', $result);\n $this->assertRegExp('#
#', $result);\n $this->assertRegExp('##', $result);\n $this->assertRegExp('##', $result);\n $this->assertRegExp('##', $result);\n $this->assertRegExp('##', $result);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914133,"cells":{"blob_id":{"kind":"string","value":"e2e53775768928bcf9bde6fa7b7e4efcc8b8450e"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"puterakahfi/MessageBus"},"path":{"kind":"string","value":"/src/Handler/Map/MessageHandlerMap.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":372,"string":"372"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\n * @package UnitTests\n * @subpackage Objects\n */\n\nclass SubscriberTest extends PHPUnit_Framework_TestCase {\n\n\tprotected $object;\n\t\n\tprotected function setUp () {\n\t\trequire_once(\"../../application/admin/objects/Subscriber.php\");\n\t\t$this->object = new Subscriber();\n\t}\n\t\n\tpublic function testSetEmailAddress () {\n\t\t$this->assertTrue($this->object->setEmailAddress(\"test@example.com\"));\n\t\t$this->assertFalse($this->object->setEmailAddress(\"not-a-valid-email-address!\"));\n\t\t$this->assertSame($this->object->subscriberEmail, \"test@example.com\");\n\t}\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914135,"cells":{"blob_id":{"kind":"string","value":"8458be938b47bd94a6f91ac19e678f990f2f7493"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"5baddi/lifemoz-coding-challenge"},"path":{"kind":"string","value":"/app/Http/Resources/RoomResource.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":752,"string":"752"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" $this->id,\n 'uuid' => $this->uuid,\n 'name' => $this->name,\n 'user' => $this->user ?? null,\n 'updated_at' => Carbon::parse($this->updated_at)->format('H:i d/m/Y'),\n 'created_at' => Carbon::parse($this->created_at)->format('H:i d/m/Y'),\n ];\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914136,"cells":{"blob_id":{"kind":"string","value":"01679d3ad5b3b0c9469e0d0ad55d64fd34eebcf7"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"ryanhellyer/auto-xml-backup"},"path":{"kind":"string","value":"/inc/class-auto-xml-backup-admin-notice.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":730,"string":"730"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n\t\t

' . sprintf(\n\t\t\t__( 'Email addresses need to be added to the Auto XML Backup settings page.', 'auto-xml-backup' ),\n\t\t\tesc_url( $this->get_settings_url() )\n\t\t) . '

\n\t\t
';\n\t}\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914137,"cells":{"blob_id":{"kind":"string","value":"238be97af2f39ad6ad6242aa292efa5a1b7c6d56"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"JohnHasmie/restaurant"},"path":{"kind":"string","value":"/classes/Stripe.class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1572,"string":"1,572"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"stripToken = $data['stripeToken'];\n \\Stripe\\Stripe::setApiKey('sk_test_51Ie6PpL8uWnAKjvMZ6aZwNXtiuxGyhOlUV8CXKT2JDdflqKXKyfDc96SqAzrwh92xdULc8lCX5lOMh8DSaM2vRzl00W5fOmfHN');\n }\n\n public function processPayment($orders) {\n $order = $orders[0];\n $stripToken = $this->stripToken;\n \n \\Stripe\\Charge::create ([\n \"amount\" => round($order->grand_total)*100,\n \"currency\" => 'USD',\n \"source\" => $stripToken,\n \"description\" => \"Test payment from click and collect.\" \n ]);\n \n $orderClass = new Order;\n $orderClass->payOrder($order->order_number, 'Stripe-'.$order->order_number);\n // $checkout_session = \\Stripe\\Checkout\\Session::create([\n // 'payment_method_types' => ['card'],\n // 'line_items' => [[\n // 'price_data' => [\n // 'currency' => 'USD',\n // 'unit_amount' => round($order->grand_total)*100,\n // 'product_data' => [\n // 'name' => $order->name,\n // // 'images' => [Config::PRODUCT_IMAGE],\n // ],\n // ],\n // 'quantity' => 1,\n // ]],\n // 'mode' => 'payment',\n // 'client_reference_id' => $order->id,\n // 'success_url' => BASE_URL.'/callback/stripe.cb.php?success=true',\n // 'cancel_url' => BASE_URL.'/callback/stripe.cb.php?success=false',\n // ]);\n\n // return $checkout_session;\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914138,"cells":{"blob_id":{"kind":"string","value":"a4674ae8bbb11c939aa79caf146362b96f5c693d"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"shuvro-zz/Symfony-3-ERPMedical"},"path":{"kind":"string","value":"/src/BackendBundle/Entity/TypeGender.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2417,"string":"2,417"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"genderArray = new ArrayCollection(); }\n/* Id de la Tabla *********************************************************************************************/\n private $id;\n public function getId() { return $this->id; }\n/**************************************************************************************************************/\n/* gender *****************************************************************************************************/\n private $type;\n public function setType($type = null) { $this->type = $type; return $this; }\n public function getType() { return $this->type; }\n/**************************************************************************************************************/\n /*\n * la función __toString(){ return $this->gender; } permite\n * listar los campos cuando referenciemos la tabla\n */\n public function __toString(){ return (string)$this->type; }\n/**************************************************************************************************************/\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914139,"cells":{"blob_id":{"kind":"string","value":"0b33d04a0409e60306cbc57dc3ff29e1cbecc133"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"shiroro666/Vaccination_System"},"path":{"kind":"string","value":"/index.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2460,"string":"2,460"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n\nPatient Index Page\n\n
\\n\";\n echo 'Click login to login or register if you don\\'t have an account yet.

';\n echo 'Click Signup to login if you are a provider.';\n echo \"\\n\";\n}\nelse {\n $username = htmlspecialchars($_SESSION[\"username\"]);\n $user_id = htmlspecialchars($_SESSION[\"user_id\"]);\n //echo \"4\";\n if ($stmt = $mysqli->prepare(\"select patientId, name, ssn, birthday, address, phone, email from patient where patientId=?\")){\n //echo(\"1\");\n $stmt->bind_param(\"s\", $user_id);\n $stmt->execute();\n $stmt->bind_result($pid, $name, $ssn, $birthday, $address, $phone, $email);\n if ($stmt->fetch()){\n echo \"Welcome $username. You are logged in to the system.

\\n\";\n echo \"Your Information:
\";\n echo \"UserID:\".$pid.\"
\";\n echo \"Name:\".$name.\"
\";\n echo \"SSN:\".$ssn.\"
\";\n echo \"Birthday:\".$birthday.\"
\";\n echo \"Address:\".$address.\"
\";\n echo \"Phone:\".$phone.\"
\";\n echo \"E-Mail:\".$email.\"

\";\n echo 'To view the your appointment offers, click here, ';\n echo \"

\";\n echo 'Update information: click here, ';\n echo \"

\";\n echo 'View or add preferences: click here, ';\n echo \"

\";\n echo 'Log out: click here.';\n echo \"\\n\";\n }\n $stmt->close();\n }\n \n if ($stmt = $mysqli->prepare(\"select providertype, name, phone, address from provider where providerId=?\")){\n //echo(\"2\");\n $stmt->bind_param(\"s\", $user_id);\n $stmt->execute();\n $stmt->bind_result($pt, $name, $phone, $address);\n if ($stmt->fetch()){\n echo \"Welcome $username. You are logged in to the system.

\\n\";\n echo \"Your Information:
\";\n echo \"Provider Type:\".$pt.\"
\";\n echo \"Name:\".$name.\"
\";\n echo \"Address:\".$address.\"
\";\n echo \"Phone:\".$phone.\"

\";\n echo \"To view or add appointment here.\";\n echo \"

\";\n echo 'Log out: click here.';\n echo \"\\n\";\n }\n $stmt->close();\n }\n \n}\n\n\n?>\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914140,"cells":{"blob_id":{"kind":"string","value":"6f9fc1a1c7e0ec206a848408924c01cc32ad5374"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"KrisoprasEpikuros/unbk"},"path":{"kind":"string","value":"/application/libraries/JalurState/JalurState.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":962,"string":"962"},"score":{"kind":"number","value":2.90625,"string":"2.90625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"ci =& $ci;\n $this->stateManager =& $stateManager;\n }\n \n public function &getName() {\n return $this->name;\n }\n \n public function __get($name) {\n if ($this->$name == null) {\n switch ($name) {\n case 'jenisSiswaState':\n $this->jenisSiswaState =& $this->stateManager->getJenisSiswaState();\n break;\n }\n }\n return $this->$name;\n }\n \n public abstract function validasi();\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914141,"cells":{"blob_id":{"kind":"string","value":"58bf076ad98b71b8e346dfd194630f9a7fb3ec66"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"juanda/curso_php7_ejercicios"},"path":{"kind":"string","value":"/ejercicio3/find.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":625,"string":"625"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"find($nombreRegistro);\r\n\r\nif(is_null($item)){\r\n echo \"No hay ningún registro con ese nombre\";\r\n echo PHP_EOL;\r\n}\r\nprint_r($item);\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914142,"cells":{"blob_id":{"kind":"string","value":"060996196d76d763aa438cb253cb743ae79faa4c"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"brunocaramelo/estudos"},"path":{"kind":"string","value":"/php/zendframework-modulo-1/estoque/skeleton-application/module/Estoque/src/View/Helper/PaginationHelper.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":711,"string":"711"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"url = $url;\n $this->totalItens = $itens->count();\n $this->qtdPagina = $qtdPagina;\n \n return $this;\n\n }\n\n public function render(){\n\n $count = 0;\n $totalPaginas = ceil( $this->totalItens / $this->qtdPagina );\n\n $html = \"\";\n\n return $html;\n }\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914143,"cells":{"blob_id":{"kind":"string","value":"9beaf237f0e7a9706aaf9dec1d58e2b61d188319"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"danielkiesshau/WebPractice"},"path":{"kind":"string","value":"/PHP/update.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1462,"string":"1,462"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"select(\"SELECT nome FROM MOTORISTAS WHERE sstatus = :STATUS\",array(\":STATUS\"=>1));\n$data = json_encode($rs);\n$tipo = $_GET['tipo'];\nsetcookie(\"tabela\",\"1\", time() + (400), \"/\");\n?>\n\n\n\n\n\n\n\n\n
\n
\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914144,"cells":{"blob_id":{"kind":"string","value":"ba68d0b1e36147bc60f7aef3497a3be4b8c88e73"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"stephenjohndev/renewmember-them-little"},"path":{"kind":"string","value":"/public/_system/php/api/customer/getAgeCounts.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1866,"string":"1,866"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n # Perform SQL Query\n // $stmt = $conn->prepare(\"SELECT DATE(account_created) as date, COUNT(account_id) as count FROM accounts WHERE account_created BETWEEN $start_date AND $end_date GROUP BY date\");\n $stmt = $conn->prepare(\n \"SELECT \n CASE \n WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) < 18 THEN 'Below 18' \n WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 18 AND 30 THEN '18-30' \n WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 31 AND 45 THEN '31-45' \n WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 46 AND 60 THEN '46-60' \n ELSE 'Over 60'\n END AS age_range, \n COUNT(account_id) as count \n FROM accounts \n GROUP BY age_range\"\n );\n $stmt->execute();\n # Fetch Result\n $age_ranges = array();\n $counts = array();\n while($row = $stmt->fetch(PDO::FETCH_ASSOC))\n {\n array_push($age_ranges, $row['age_range']);\n array_push($counts, $row['count']);\n }\n $result = array(\n 'age_ranges' => $age_ranges,\n 'counts' => $counts\n );\n \n # Print Result in JSON Format\n echo json_encode((object)[\n 'success' => true,\n 'data' => $result\n ],JSON_NUMERIC_CHECK);\n}\ncatch(PDOException $e)\n{\n echo json_encode((object)[\n 'success' => false,\n 'message' => \"Connection failed: \" . $e->getMessage()\n ]);\n}\n?> "},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914145,"cells":{"blob_id":{"kind":"string","value":"1acb58be632664fa589152ec5cc990dd5a3f91cb"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"stoyantodorovbg/PHP-Web-Development-Basics"},"path":{"kind":"string","value":"/PHP Associate Arrays and Functions - Lab/1 asociativeArrays/1-characterCount.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":561,"string":"561"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" $value) {\n $counter++;\n $result .= '\"';\n $result .= $key;\n $result .= '\" => \"';\n $result .= $value;\n if ($counter === count($countLetters)) {\n\n } else {\n $result .= '\", ';\n }\n\n\n}\n$result .= ']';\necho($result);\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914146,"cells":{"blob_id":{"kind":"string","value":"e6e4fc27278c55d2ac057e9d68109430ce5fde80"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"PhilippeSimier/Gestion_Inscriptions"},"path":{"kind":"string","value":"/administration/authentification/auth.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2852,"string":"2,852"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"quote($_POST['login']));\r\n $stmt = $bdd->query($sql);\r\n\r\n\t$utilisateur = $stmt->fetchObject();\r\n\t\r\n\t\r\n\t// vérification des identifiants login et md5 par rapport à ceux enregistrés dans la base\r\n\tif (!($_POST['login'] == $utilisateur->login && $_POST['md5'] == $utilisateur->passe)){\r\n\t\theader(\"Location: ../index.php?&erreur=Incorrectes! Vérifiez vos identifiant et mot de passe.\");\r\n \t\texit();\r\n\t}\r\n\r\n\t// A partir de cette ligne l'utilisateur est authentifié\r\n\t// donc nouvelle session\r\n\tsession_start();\r\n\r\n\t// écriture des variables de session pour cet utilisateur\r\n\r\n $_SESSION['last_access'] = time();\r\n $_SESSION['ipaddr']\t\t = $_SERVER['REMOTE_ADDR'];\r\n $_SESSION['ID_user'] \t = $utilisateur->ID_user;\r\n\t\t$_SESSION['login'] \t\t = $utilisateur->login;\r\n $_SESSION['identite'] \t = $utilisateur->identite;\r\n\t\t$_SESSION['email'] \t\t = $utilisateur->email;\r\n\t\t$_SESSION['droits'] \t = $utilisateur->droits;\r\n\t\t$_SESSION['path_fichier_perso'] = $utilisateur->path_fichier_perso;\r\n\r\n\r\n\t// enregistrement de la date et heure de son passage dans le champ date_connexion de la table utilisateur\r\n $ID_user = $utilisateur->ID_user;\r\n $sql = \"UPDATE `utilisateur` SET `date_connexion` = CURRENT_TIMESTAMP WHERE `utilisateur`.`ID_user` =$ID_user LIMIT 1\" ;\r\n $stmt = $bdd->query($sql);\r\n\r\n\t// Incrémentation du compteur de session\r\n $sql = \"UPDATE utilisateur SET `nb_session` = `nb_session`+1 WHERE `utilisateur`.`ID_user` =$ID_user LIMIT 1\" ;\r\n $stmt = $bdd->query($sql);\r\n \r\n\r\n\t// sélection de la page de menu en fonction des droits accordés\r\n\r\n\tswitch ($utilisateur->droits) {\r\n\t\tcase 0: // Utilisateur révoqué sans droit\r\n\t\t\t header(\"Location: ../index.php?&erreur=révoqué! \");\r\n\t\t\t break;\r\n\t\tcase 1: // Organisateurs de niveau 1\r\n\t\t\t header(\"Location: ../orga_menu.php\");\r\n\t\t\t break;\r\n\t\tcase 2: // Organisateurs de niveau 2\r\n\t\t\t header(\"Location: ../orga_menu.php\");\r\n\t\t\t break;\r\n\t\tcase 3: // Administrateurs de niveau 3\r\n\t\t\t header(\"Location: ../orga_menu.php\");\r\n\t\t\t break;\t \r\n\t\t\r\n\t\tdefault:\r\n\t\t\t header(\"Location: ../index.php\");\r\n\t}\r\n\r\n?>\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914147,"cells":{"blob_id":{"kind":"string","value":"abf3c72df1963548b31c942011da660ba2779b93"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"Mirdrack/prueba"},"path":{"kind":"string","value":"/classes/Vehicles.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1123,"string":"1,123"},"score":{"kind":"number","value":3.3125,"string":"3.3125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"sql = new SqlEngine();\n\t\t$this->sql->connect();\n\t\t$this->vehicles = array();\n\t}\n\n\tpublic function getAll()\n\t{\n\t\t$query = 'SELECT *';\n\t\t$query .= 'FROM vehicles ';\n\t\t$result = $this->sql->query($query);\n\t\tif($result != 1)\n\t\t{\n\t\t\treturn false;\n\t\t\t$this->error = $this->sql->geterror(); // This will send an error to up level\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif($this->sql->getRowsAffected() > 0 )\n\t\t\t{\n\t\t\t\twhile($row = mysql_fetch_array($this->sql->getQueryResult(), MYSQL_BOTH))\n\t\t\t\t{\n\t\t\t\t\t$current = new Vehicle();\n\t\t\t\t\t$current->setVehicle($row);\n\t\t\t\t\tarray_push($this->vehicles, $current);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$this->error = \"No vehicles\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\t\t\n\t}\n\n\tpublic function getVehicles()\n\t{\n\t\t$data = array();\n\t\tforeach ($this->vehicles as $vehicle)\n\t\t{\n\t\t\tarray_push($data, $vehicle->asArray());\n\t\t}\n\t\treturn $data;\n\t}\n\n\tpublic function getError()\n\t{\n\t\treturn $this->error;\n\t}\n}\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914148,"cells":{"blob_id":{"kind":"string","value":"c3dafcdc1cf8cf95f3f50cc73e9b549556d6380c"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"andreafiori/php-coding-dojo"},"path":{"kind":"string","value":"/src/algorithms/math/Calculator.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":580,"string":"580"},"score":{"kind":"number","value":3.859375,"string":"3.859375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"op1 + $this->op2;\n\t}\n\n /**\n * Subtraction\n *\n * @return float|int\n */\n\tpublic function subtract()\n\t{\n\t\treturn $this->op1 - $this->op2;\n\t}\n\n /**\n * Check if number is divisible\n *\n * @return bool\n */\n\tpublic function isDivisible()\n\t{\n\t\treturn $this->op1 % $this->op2 == 0;\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914149,"cells":{"blob_id":{"kind":"string","value":"1b2ef6891fc923b4957d5d139c606bad6ac070c7"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"845alex845/consultorafisi"},"path":{"kind":"string","value":"/app/model/Escuela.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":414,"string":"414"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":""},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914150,"cells":{"blob_id":{"kind":"string","value":"7e4927d6a3bf4319af1c1f81c32fe84dfdd37481"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"puiutucutu/geophp"},"path":{"kind":"string","value":"/src/functions/createUtmFromLatLng.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":339,"string":"339"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"toUTMRef();\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914151,"cells":{"blob_id":{"kind":"string","value":"65919c02274116037b4969c1fc2b4be4854335a1"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"mstremante/advent-of-code-2019"},"path":{"kind":"string","value":"/13/part2.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6654,"string":"6,654"},"score":{"kind":"number","value":3.203125,"string":"3.203125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"isFinished()) {\n $input = 0;\n if($ballX > $paddleX) {\n $input = 1;\n }\n if($ballX < $paddleX) {\n $input = -1;\n }\n $outputs = $computer->runProgram($input);\n $i = 0;\n while($i < count($outputs)) {\n if($outputs[$i] == \"-1\") {\n $score = $outputs[$i + 2];\n } else {\n if($outputs[$i + 2] == 4) {\n $ballX = $outputs[$i];\n }\n if($outputs[$i + 2] == 3) {\n $paddleX = $outputs[$i];\n }\n $screen[$outputs[$i]][$outputs[$i + 1]] = $outputs[$i + 2];\n }\n $i = $i + 3;\n }\n // Optional\n //printScreen($screen);\n }\n echo $score;\n}\n\nfunction printScreen($screen) {\n $i = 0;\n $smallX = $bigX = $smallY = $bigY = null;\n foreach($screen as $x => $y) {\n if(is_null($smallX)) {\n $smallX = $x;\n }\n if(is_null($bigX)) {\n $bigX = $x;\n }\n if($smallX > $x) {\n $smallX = $x;\n }\n if($bigX < $x) {\n $bigX = $x;\n }\n foreach($y as $id => $tile) {\n if(is_null($smallY)) {\n $smallY = $id;\n }\n if(is_null($bigY)) {\n $bigY = $id;\n }\n if($smallY > $id) {\n $smallY = $id;\n }\n if($bigY < $id) {\n $bigY = $id;\n }\n }\n }\n\n // Print drawing\n for($y = $smallY; $y <= $bigY; $y++) {\n for($x = $smallX; $x <= $bigX; $x++) {\n $char = \" \";\n if(isset($screen[$x][$y])) {\n $tile = $screen[$x][$y];\n switch($tile) {\n case 1:\n $char = \"#\";\n break;\n case 2:\n $char = \"@\";\n break;\n case 3:\n $char = \"_\";\n break;\n case 4:\n $char = \"*\";\n break;\n }\n }\n echo $char;\n }\n echo \"\\n\";\n }\n echo \"\\n\\n\";\n}\n\nclass Computer {\n\n private $data = array();\n private $pointer = 0;\n private $relativeBase = 0;\n private $finished = false;\n\n function __construct($program) {\n $this->data = $program;\n }\n\n // Executes program\n function runProgram($inputs = array()) {\n $outputs = false;\n if(!is_array($inputs)) {\n $inputs = array($inputs);\n }\n while(($command = $this->data[$this->pointer]) != 99) {\n // Parse command:\n $op = substr($command, -2);\n $command = str_pad($command, 5, 0, STR_PAD_LEFT);\n switch($op) {\n\n // Addition and multiplication\n case \"01\":\n case \"02\":\n $op1 = $this->getValue($command, 1);\n $op2 = $this->getValue($command, 2);\n if($op == 01) {\n $res = $op1 + $op2;\n } else {\n $res = $op1 * $op2;\n }\n $this->setValue($command, 3, $res);\n $this->pointer += 4;\n break;\n // Input value\n case \"03\":\n if(!count($inputs)) {\n return $outputs;\n }\n $input = array_shift($inputs);\n $this->setValue($command, 1, $input);\n $this->pointer += 2;\n break;\n // Output value\n case \"04\":\n $mode1 = substr($command, -3)[0];\n $outputs[] = $this->getValue($command, 1);\n $this->pointer += 2;\n break;\n // Jump if true and jump if false\n case \"05\":\n case \"06\":\n $op1 = $this->getValue($command, 1);\n $op2 = $this->getValue($command, 2);\n if(($op == \"05\" && $op1 != 0) || ($op == \"06\" && $op1 == 0)) {\n $this->pointer = $op2;\n } else {\n $this->pointer +=3;\n }\n break;\n // Less than and equals\n case \"07\":\n case \"08\":\n $op1 = $this->getValue($command, 1);\n $op2 = $this->getValue($command, 2);\n if(($op == \"07\" && $op1 < $op2) || ($op == \"08\" && $op1 == $op2)) {\n $res = 1;\n } else {\n $res = 0;\n }\n $this->setValue($command, 3, $res);\n $this->pointer += 4;\n break;\n // Adjust relative base\n case \"09\":\n $op1 = $this->getValue($command, 1);\n $this->relativeBase += $op1;\n $this->pointer += 2;\n break;\n }\n }\n $this->finished = true;\n return $outputs;\n }\n\n function getValue($command, $param) {\n $mode = substr($command, -($param + 2))[0];\n $addr = $this->data[$this->pointer + $param];\n if($mode == 1) {\n return $addr;\n } elseif($mode == 2) {\n $addr = $addr + $this->relativeBase;\n }\n // Initialize memory\n if(!isset($this->data[$addr])) {\n $this->data[$addr] = 0;\n }\n return $this->data[$addr];\n }\n\n function setValue($command, $param, $value) {\n $mode = substr($command, -($param + 2))[0];\n $addr = $this->data[$this->pointer + $param];\n if($mode == 1 || $mode == 0) {\n $this->data[$addr] = $value;\n } elseif($mode == 2) {\n $this->data[$addr + $this->relativeBase] = $value;\n }\n }\n\n function isFinished() {\n return $this->finished;\n }\n}\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914152,"cells":{"blob_id":{"kind":"string","value":"f2f9c72ae514b27a23380a13ff1573154b323ea5"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"holiday/Validator"},"path":{"kind":"string","value":"/Validator.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3175,"string":"3,175"},"score":{"kind":"number","value":3.34375,"string":"3.34375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"rules = $rules;\r\n $this->data = $data;\r\n\r\n // Initialize the bootstrapper\r\n $bootstrap = new \\Validator\\Bootstrapper(dirname(__FILE__));\r\n $bootstrap->register();\r\n }\r\n\r\n /**\r\n * Getter for the errors\r\n * @return type Array\r\n */\r\n public function getErrors() {\r\n return $this->errors;\r\n }\r\n\r\n /**\r\n * Return true if there are no errors\r\n * @return type Boolean\r\n */\r\n public function isValid() {\r\n return empty($this->errors);\r\n }\r\n\r\n /**\r\n * Parses through each rule\r\n * @return type void\r\n */\r\n public function validate($rules = null) {\r\n\r\n //Rules dictating which fields to validate and strategy to use\r\n if ($rules == null) {\r\n $rules = $this->rules;\r\n }\r\n\r\n //Loop over each field:rule pairs\r\n foreach ($rules as $fieldName => $rule) {\r\n //single rule detected\r\n if (!is_array($rule)) {\r\n //validate the field with specifications in array $rule\r\n $this->_validate($fieldName, $rule);\r\n } else {\r\n //multiple rules detected, recurse\r\n foreach ($rule as $singleRule) {\r\n $multiRule[$fieldName] = $singleRule;\r\n $this->validate($multiRule);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Helper method for validate(). Validates an individual field by loading the correct AbstractValidator \r\n * and passing in the necessart options.\r\n * @param type $fieldName String\r\n * @param type $rule Array\r\n * @return type void\r\n */\r\n private function _validate($fieldName, $rule) {\r\n //single rule\r\n $validator = '\\\\ValidationTypes\\\\' . ucfirst($rule->getValidator()) . 'Validator';\r\n $val = new $validator($this->getData($fieldName), $rule->getOptions());\r\n \r\n \r\n //Validate and log any errors\r\n if (!$val->validate() && !isset($this->errors[$fieldName])) {\r\n $this->errors[$fieldName] = $rule->getMessage();\r\n }\r\n\r\n }\r\n \r\n /**\r\n * Return the data if found, null otherwise\r\n * @param type $fieldName\r\n * @return null \r\n */\r\n private function getData($fieldName) {\r\n if (!isset($this->data[$fieldName])) {\r\n return null;\r\n } else {\r\n $data = $this->data[$fieldName];\r\n if(is_string($data)) {\r\n $data = trim($this->data[$fieldName]);\r\n }\r\n return $data;\r\n }\r\n }\r\n\r\n}\r\n\r\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914153,"cells":{"blob_id":{"kind":"string","value":"79e5337b912b712e6ab7125bff1865b8e14b86a3"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"onenook/helper"},"path":{"kind":"string","value":"/src/string/Sign.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1129,"string":"1,129"},"score":{"kind":"number","value":3.34375,"string":"3.34375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" $v) {\n if ($k != 'sign' && $v != '' && !is_array($v)) {\n $buff .= $k . '=' . $v . '&';\n }\n }\n $buff = trim($buff, '&');\n return $buff;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914154,"cells":{"blob_id":{"kind":"string","value":"ee5dddaf65cb860277505b6ba4042b574bcb2e89"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"robsli/Web-Apps-TESI-Calendar"},"path":{"kind":"string","value":"/dboperation.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":206,"string":"206"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":""},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914155,"cells":{"blob_id":{"kind":"string","value":"2b2e01627f94f73cadbb793c2c9a949f1fdb150b"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"pmatiash/shape-drawer"},"path":{"kind":"string","value":"/app/Trapezoid.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1647,"string":"1,647"},"score":{"kind":"number","value":3.4375,"string":"3.4375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"isCorrectTrapezoid($sideTop, $sideBottom, $height)) {\n throw new \\Exception(\"Trapezoid with these parameters can't be exists\");\n }\n\n $this->sideTop = (int) $sideTop;\n $this->sideBottom = (int) $sideBottom;\n $this->height = (int) $height;\n $this->color = $color;\n }\n\n /**\n * @param $sideTop\n * @param $sideBottom\n * @param $height\n * @return bool\n */\n private function isCorrectTrapezoid($sideTop, $sideBottom, $height) {\n\n if ($sideTop <= 0 ) {\n return false;\n }\n\n if ($sideBottom <= 0) {\n return false;\n }\n\n if ($height <= 0) {\n return false;\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getName()\n {\n return 'Трапеция';\n }\n\n /**\n * @inheritdoc\n */\n public function draw()\n {\n return parent::draw() . sprintf(', верхняя сторона: %s, нижняя сторона: %s, высота: %s', $this->sideTop, $this->sideBottom, $this->height);\n }\n\n /**\n * @inheritdoc\n */\n public function getSquare()\n {\n return ($this->sideTop + $this->sideBottom) / 2 * $this->height;\n }\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914156,"cells":{"blob_id":{"kind":"string","value":"fdd9f6f70ce5ac4c94ed991ca9bb69ddc205093c"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"alexdiasgonsales/organizador"},"path":{"kind":"string","value":"/sistema/model/mysql/SessaoMySqlDAO.class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6396,"string":"6,396"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"table WHERE id_sessao = :id_sessao\";\r\n $stmt = ConnectionFactory::prepare($sql);\r\n $stmt->bindParam(':id_sessao', $id, PDO::PARAM_INT);\r\n $stmt->execute();\r\n return $stmt->fetch();\r\n\t}\r\n \r\n public function querySessaoByAvaliador($id_avaliador) {\r\n $sql =<<bindParam(':id_avaliador', $id_avaliador, PDO::PARAM_INT);\r\n $stmt->execute();\r\n return $stmt->fetchAll();\r\n }\r\n \r\n public function updateConfirmacaoSessao($id_avaliador, $id_sessao, $status_int) {\r\n \r\n $sql =<<bindParam(':id_avaliador', $id_avaliador, PDO::PARAM_INT);\r\n $stmt->bindParam(':id_sessao', $id_sessao, PDO::PARAM_INT);\r\n $stmt->bindParam(':status_int', $status_int, PDO::PARAM_INT);\r\n \r\n return $stmt->execute();\r\n \r\n }\r\n\r\n\t/**\r\n\t * Obtem todos o registros das Tabelas\r\n\t */\r\n \r\n\tpublic function queryAll(){\r\n\t $sql = \"SELECT * FROM $this->table\";\r\n $stmt = ConnectionFactory::prepare($sql);\r\n $stmt->execute();\r\n return $stmt->fetchAll();\t\r\n\t}\r\n\t\r\n\t/**\r\n \t * Exclui um registro da tabela\r\n \t * @parametro sessao chave primária\r\n \t */\r\n \r\n\tpublic function delete($id){\r\n $sql = \"DELETE FROM $this->table WHERE id_sessao = :id_sessao\";\r\n $stmt = ConnectionFactory::prepare($sql);\r\n $stmt->bindParam(':id_sessao', $id, PDO::PARAM_INT);\r\n return $stmt->execute();\r\n\t}\r\n\t\r\n\t/**\r\n \t * Inseri um registro na tabela\r\n \t *\r\n \t * @parametro SessaoMySql sessao\r\n \t */\r\n \r\n\tpublic function insert(Sessao $Sessao){\r\n $sql = \"INSERT INTO $this->table (numero, nome, sala, nome_sala, andar, nome_andar, data, hora_ini, hora_fim, fk_modalidade, status) VALUES ( :numero, :nome, :sala, :nomeSala, :andar, :nomeAndar, :data, :horaIni, :horaFim, :fkModalidade, :status)\";\r\n \r\n \r\n\t $numero = $Sessao->getNumero();\r\n\t $nome = $Sessao->getNome();\r\n\t $sala = $Sessao->getSala();\r\n\t $nomeSala = $Sessao->getNomeSala();\r\n\t $andar = $Sessao->getAndar();\r\n\t $nomeAndar = $Sessao->getNomeAndar();\r\n\t $data = $Sessao->getData();\r\n\t $horaIni = $Sessao->getHoraIni();\r\n\t $horaFim = $Sessao->getHoraFim();\r\n\t $fkModalidade = $Sessao->getFkModalidade();\r\n\t $status = $Sessao->getStatus();\r\n \r\n $stmt = ConnectionFactory::prepare($sql);\r\n \r\n \r\n\t $stmt->bindParam(':numero', $numero);\r\n\t $stmt->bindParam(':nome', $nome);\r\n\t $stmt->bindParam(':sala', $sala);\r\n\t $stmt->bindParam(':nomeSala', $nomeSala);\r\n\t $stmt->bindParam(':andar', $andar);\r\n\t $stmt->bindParam(':nomeAndar', $nomeAndar);\r\n\t $stmt->bindParam(':data', $data);\r\n\t $stmt->bindParam(':horaIni', $horaIni);\r\n\t $stmt->bindParam(':horaFim', $horaFim);\r\n\t $stmt->bindParam(':fkModalidade', $fkModalidade);\r\n\t $stmt->bindParam(':status', $status);\r\n return $stmt->execute(); \r\n\t}\r\n\t\r\n\t/**\r\n \t * atualiza um registro da tabela\r\n \t *\r\n \t * @parametro SessaoMySql sessao\r\n \t */\r\n \r\n\tpublic function update(Sessao $Sessao){\r\n $sql = \"UPDATE $this->table SET numero = :numero, nome = :nome, sala = :sala, nome_sala = :nome_sala, andar = :andar, nome_andar = :nome_andar, data = :data, hora_ini = :hora_ini, hora_fim = :hora_fim, fk_modalidade = :fk_modalidade, status = :status WHERE id_sessao = :id\";\r\n $id = $Sessao->getIdSessao();\r\n \r\n \r\n\t $numero = $Sessao->getNumero();\r\n\t $nome = $Sessao->getNome();\r\n\t $sala = $Sessao->getSala();\r\n\t $nomeSala = $Sessao->getNomeSala();\r\n\t $andar = $Sessao->getAndar();\r\n\t $nomeAndar = $Sessao->getNomeAndar();\r\n\t $data = $Sessao->getData();\r\n\t $horaIni = $Sessao->getHoraIni();\r\n\t $horaFim = $Sessao->getHoraFim();\r\n\t $fkModalidade = $Sessao->getFkModalidade();\r\n\t $status = $Sessao->getStatus();\r\n \r\n $stmt = ConnectionFactory::prepare($sql);\r\n $stmt->bindParam(':id', $id);\r\n \r\n \r\n\t $stmt->bindParam(':numero', $numero);\r\n\t $stmt->bindParam(':nome', $nome);\r\n\t $stmt->bindParam(':sala', $sala);\r\n\t $stmt->bindParam(':nomeSala', $nomeSala);\r\n\t $stmt->bindParam(':andar', $andar);\r\n\t $stmt->bindParam(':nomeAndar', $nomeAndar);\r\n\t $stmt->bindParam(':data', $data);\r\n\t $stmt->bindParam(':horaIni', $horaIni);\r\n\t $stmt->bindParam(':horaFim', $horaFim);\r\n\t $stmt->bindParam(':fkModalidade', $fkModalidade);\r\n\t $stmt->bindParam(':status', $status);\r\n \r\n return $stmt->execute(); \r\n\t}\r\n\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914157,"cells":{"blob_id":{"kind":"string","value":"d3a69d76ef83838df21d374dfc259ed02dae7dc8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"activecollab/authentication"},"path":{"kind":"string","value":"/src/AuthenticationResult/Transport/Transport.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2630,"string":"2,630"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":". All rights reserved.\n */\n\ndeclare(strict_types=1);\n\nnamespace ActiveCollab\\Authentication\\AuthenticationResult\\Transport;\n\nuse ActiveCollab\\Authentication\\Adapter\\AdapterInterface;\nuse LogicException;\nuse Psr\\Http\\Message\\ResponseInterface;\nuse Psr\\Http\\Message\\ServerRequestInterface;\n\nabstract class Transport implements TransportInterface\n{\n private $adapter;\n private $payload;\n\n public function __construct(AdapterInterface $adapter, $payload = null)\n {\n $this->adapter = $adapter;\n $this->payload = $payload;\n }\n\n public function getAdapter(): AdapterInterface\n {\n return $this->adapter;\n }\n\n public function getPayload()\n {\n return $this->payload;\n }\n\n public function setPayload($value): TransportInterface\n {\n $this->payload = $value;\n\n return $this;\n }\n\n public function isEmpty(): bool\n {\n return false;\n }\n\n private $isAppliedToRequest = false;\n private $isAppliedToResponse = false;\n\n public function applyToRequest(ServerRequestInterface $request): ServerRequestInterface\n {\n if ($this->isEmpty()) {\n throw new LogicException('Empty authentication transport cannot be applied');\n }\n\n if ($this->isAppliedToRequest) {\n throw new LogicException('Authentication transport already applied');\n }\n\n $this->isAppliedToRequest = true;\n return $this->getAdapter()->applyToRequest($request, $this);\n }\n\n public function applyToResponse(ResponseInterface $response): ResponseInterface\n {\n if ($this->isEmpty()) {\n throw new LogicException('Empty authentication transport cannot be applied');\n }\n\n if ($this->isAppliedToResponse) {\n throw new LogicException('Authentication transport already applied');\n }\n\n $this->isAppliedToResponse = true;\n return $this->getAdapter()->applyToResponse($response, $this);\n }\n\n public function applyTo(ServerRequestInterface $request, ResponseInterface $response): array\n {\n return [\n $this->applyToRequest($request),\n $this->applyToResponse($response),\n ];\n }\n\n public function isApplied(): bool\n {\n return $this->isAppliedToRequest && $this->isAppliedToResponse;\n }\n\n public function isAppliedToRequest(): bool\n {\n return $this->isAppliedToRequest;\n }\n\n public function isAppliedToResponse(): bool\n {\n return $this->isAppliedToResponse;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914158,"cells":{"blob_id":{"kind":"string","value":"efc1624d2a3359d12ade6f749b993da717fdf766"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"FindMyFriends/api"},"path":{"kind":"string","value":"/App/Domain/Access/PgEntrance.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1075,"string":"1,075"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"origin = $origin;\n\t\t$this->connection = $connection;\n\t}\n\n\t/**\n\t * @param array $credentials\n\t * @throws \\UnexpectedValueException\n\t * @return \\FindMyFriends\\Domain\\Access\\Seeker\n\t */\n\tpublic function enter(array $credentials): Seeker {\n\t\t$seeker = $this->origin->enter($credentials);\n\t\t(new Storage\\NativeQuery($this->connection, 'SELECT globals_set_seeker(?)', [$seeker->id()]))->execute();\n\t\treturn $seeker;\n\t}\n\n\t/**\n\t * @throws \\UnexpectedValueException\n\t * @return \\FindMyFriends\\Domain\\Access\\Seeker\n\t */\n\tpublic function exit(): Seeker {\n\t\t(new Storage\\NativeQuery($this->connection, 'SELECT globals_set_seeker(NULL)'))->execute();\n\t\treturn $this->origin->exit();\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914159,"cells":{"blob_id":{"kind":"string","value":"2dfdc1de9ef3792c6a2b1224c967b7a4142e5330"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"araiy555/6ch"},"path":{"kind":"string","value":"/getleak/image.movie.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5664,"string":"5,664"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\";\n break;\n }\n }\n }\n if ($dougacount >= 1 AND $imagecount >= 1) {\n $error = \"画像か動画のアップロードどちらかを設定してください。\";\n }\n if ($dougacount >= 2) {\n $error = \"動画は1つのみです。\";\n }\n//エラー処理\n if (empty($error)) {\n\n//動画アップロード\n if ($dougacount == 1) {\n $file_nm = $_FILES['files']['name'][0];\n $tmp_ary = explode('.', $file_nm);\n $extension = $tmp_ary[count($tmp_ary) - 1];\n\n if ($extension == 'mp4') {\n\n $size = $_FILES['files']['size'][0];\n //30MB\n $san = '125829120';\n if ($size < $san) {\n //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234');\n $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai',\n 'q1w2e3r4');\n $name = $_FILES['files']['name'][0];\n $type = explode('.', $name);\n $type = end($type);\n $size = $_FILES['files']['size'][0];\n $tmp = $_FILES['files']['tmp_name'][0];\n $random_name = rand();\n\n move_uploaded_file($tmp, 'files/' . $random_name . '.' . $type);\n\n $stmt = $pdo->prepare(\"INSERT INTO douga VALUES('','$name','files/$random_name.$type','')\");\n $stmt->execute();\n\n $douga = $pdo->lastInsertId();\n\n $stmt = $pdo->query(\"select * from douga where id = \" . \"$douga\");\n\n $result = $stmt->fetch();\n ?>\n \">\n \n 0) {\n for ($i = 0; $i < $count; $i++) {\n $size = $_FILES['files']['size'][$i];\n if ($size < 20000) {\n\n $tmp = $_FILES[\"files\"][\"tmp_name\"][$i];\n $fp = fopen($tmp, 'rb');\n $data = bin2hex(fread($fp, $size));\n //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234');\n $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai',\n 'q1w2e3r4');\n\n //$dsn='mysql:host=localhost;dbname=mini_bbs';\n $dsn = 'mysql:host=mysql5027.xserver.jp;dbname=earthwork_sample';\n\n $pdo->exec(\"INSERT INTO `upload`(`type`,`data`) values ('$type',0x$data)\");\n $gazou[] = $pdo->lastInsertId();\n $pdo = null;\n } else {\n $error = \"画像は20KB以内です。\";\n echo $error;\n exit;\n }\n }\n $color = implode(\",\", $gazou);\n\n //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234');\n $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai', 'q1w2e3r4');\n $images = $pdo->query(\"select * from upload where id IN (\" . $color . \")\");\n\n if (!empty($images)):\n foreach ($images as $i => $img):\n if ($i):\n endif;\n\n ?>\n
  • \">\n \">\n \" width=\"10%\" height=\"10%\"\n class=\"img\">\n
  • \n getMessage());\n}\n?>\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914160,"cells":{"blob_id":{"kind":"string","value":"2a1ccb95936a4bc640dbb97473ded42ea0c5ec88"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"fransaez85/clinica_js"},"path":{"kind":"string","value":"/php/consultaTodosMedicos.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1069,"string":"1,069"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"query($query);\n$dimension=$resul->num_rows;\nif ($dimension>0) {\n\t# code...\n\tfor ($i=0; $i < $dimension; $i++) { \t\n\t\t\t$array_fila[] = $resul->fetch_assoc();\n\t\t\t$objmedico =$array_fila[$i];\n\t\t\t\t\t\t\t\t\n\t\t\t$array_medicos[$i] = $objmedico;\n\t\t}\n\n\t\t$obj_JSON = json_encode($array_medicos);\n\t\t\t//alert($obj_JSON);\n\t\techo $obj_JSON;\n\t\t\n\t} else {\n\t\techo \"error\";\n\t}\n\n\n/*include_once(\"conexion.php\");\n\nclass medico {\n\n\t\tpublic $id;\n\t\tpublic $nombre;\n\t\tpublic $id_especialidad;\n\t\tpublic $foto;\n\n\t\tpublic function __construct ($id, $nombre,$id_especialidad, $foto){\n\n\t\t\t$this->id = $id;\n\t\t\t$this->nombre = $nombre;\n\t\t\t$this->id_especialidad = $id_especialidad;\n\t\t\t$this->foto = $foto;\n\t\t}\n\n}\n\n$sql = \"SELECT * FROM medico\";\n$res = $conexion->query($sql);\n$aux = $res->num_rows;\n\nif ($res->num_rows > 0) {\n\twhile ($aux > 0) {\n\n\t\t$datos= $res->fetch_object();\n\t\t$dat[]=$datos;\n\t\t$aux--;\n\n\t}\n\n\t$json=JSON_encode($dat);\n\techo $json;\n\n}else {\n\t\techo \"error\";\n\t}*/\n\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914161,"cells":{"blob_id":{"kind":"string","value":"05237daf21ec12a0afa44941ca316c219e93a909"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"matthewdimatteo/ctrex"},"path":{"kind":"string","value":"/php/content/content-disclosures.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1887,"string":"1,887"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"'.$disclosuresHeader.'
    '; }\n\n// PAGE BODY\necho '
    ';\n\n\t// INTRO\n\tif($disclosuresIntro != NULL) { echo '

    '.parseLinksOld($disclosuresIntro).'

    '; }\n\t\n\t// SOURCES OF INCOME\n\tif(count($disclosuresIncomeItems > 0))\n\t{\n\t\techo '

    ';\n\t\tfor($i = 0; $i <= count($disclosuresIncomeItems); $i++)\n\t\t{\n\t\t\t$incomeItem \t\t= $disclosuresIncomeItems[$i];\n\t\t\t$incomeDescription \t= $disclosuresIncomeDescriptions[$i];\n\t\t\tif($incomeItem != NULL)\n\t\t\t{\n\t\t\t\techo ''.$incomeItem.'';\n\t\t\t\tif($incomeDescription != NULL) { echo parseLinksOld($incomeDescription); }\n\t\t\t\techo '
    ';\n\t\t\t} // end if $incomeItem\n\t\t} // end for\n\t\techo '

    ';\n\t} // end if $disclosuresIncomeItems\n\t\n\t// ADVERTISING AND SPONSORSHIP RELATIONSHIPS\n\tif($disclosuresRelHeader == NULL)\n\t{\n\t\t$disclosuresRelHeader = 'ADVERTISING AND SPONSORSHIP RELATIONSHIPS

    In order to be a sponsor or underwriter (e.g., for research), the business partner must meet the following conditions:';\n\t} // end if !$disclosuresRelHeader\n\tif(count($disclosuresRelItems) > 0)\n\t{\n\t\techo '';\n\t} // end if $disclosuresRelItems\n\t\n\t// CONCLUSION, DATE MODIFIED\n\tif($disclosuresConclusion != NULL) \t\t{ echo '

    '.parseLinksOld($disclosuresConclusion).'

    '; }\n\tif($disclosuresDateModified != NULL) \t{ echo 'Last update: '.$disclosuresDateModified; }\necho '
    '; // /.paragraph left bottom-10\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914162,"cells":{"blob_id":{"kind":"string","value":"51f033530f7c168b50dce06012c036d83587a4c7"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"ck6390/CMS"},"path":{"kind":"string","value":"/application/controllers/Attandance_bioMonth.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8002,"string":"8,002"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"load->model('Attandances_bio','m_bio_att'); \n\n }\n\n public function index() { \n \n $employee = $this->m_bio_att->get_bio_att_emp();//bio data\n // var_dump($employee);\n // die();\n $curr_year = date('Y');\n $curr_month = '08';\n //$curr_month = date('m');\n $curr_day = date('d'); \n foreach ($employee as $emp) {\n //$id_bio = '';\n $sub_str = substr($emp->EmployeeCode, 0, 1);\n $id = substr($emp->EmployeeCode, 1);\n $em_id = $emp->EmployeeCode;\n //var_dump($sub_str);\n //die();\n if($sub_str == '3'){\n \t$type = 'employee';\n \t$result_att = $this->m_bio_att->get_employee_lists($id); \n $condition = array( \n 'month' => $curr_month,\n 'year' => $curr_year,\n //'employee_id' =>'31011'\n 'employee_id' =>@$result_att->employee_id\n ); \n \n \t $data = $condition;\n \t if (!empty($result_att)) { \n \t $attendance = $this->m_bio_att->get_single_data($condition,$type);\n \t }\n \t $bio_att_year = date('Y');\n $bio_att_month = date('m');\n //$bio_att_month = '08';\n \t $bio_att_day = date('d');\n \t $today = date('Y-m-d');\n \t $time = date(\"h:i:s a\");\n \t $no_of_days = cal_days_in_month(CAL_GREGORIAN, $bio_att_month,$bio_att_year);\n \t $attend = array();\n \t for ($i=1; $no_of_days >= $i; $i++) {\n \t \n \t $attend[] = array('day'=>$i,'attendance'=>'','attendance_date'=>'','attendance_time'=>'','out_time'=>'');\n \t \n \t }\n \t if (empty($attendance)) {\n \t $data['employee_id'] = $result_att->employee_id; \n \t $data['status'] = '1';\n \t $data['created_at'] = date('Y-m-d H:i:s');\n \t $data['attendance_data'] = json_encode($attend);\n \t $this->m_bio_att->insert($data,$type); \n \t }else{\n \t \tvar_dump($attendance);\n \t $this->update_atten($em_id,$attendance,$condition,$type);\n \t } \n }\n }\n die(); \n echo \"

    Employee Attendance Updated.

    \";\n }\n\n public function update_atten($em_id,$attendance,$condition,$type)\n { \n //var_dump($em_id);\n\n $result = $this->m_bio_att->get_bio_att($em_id);//bio data \n //$result = $this->m_bio_att->get_bio_att('31011'); \n\t //echo \"
    \";\n      //var_dump($result);  \n      // die();                                  \n      $attendance_data = $attendance->attendance_data;\n      $attendance_data_decode = json_decode($attendance_data);\n      //var_dump($attendance_data_decode);\n      \n      $attend = array();  \n      $today = date('Y-m-d'); \n     /* if($em_id == @$result->UserId)\n      //if($em_id == \"31011\")\n      {     //var_dump($result->LogDate);          \n          $bio_att_day = date('d',strtotime($result->LogDate));\n          $today = date('Y-m-d',strtotime($result->LogDate));\n          $time = date(\"h:i:sa\",strtotime($result->LogDate));\n          $out_time = date(\"h:i:sa\",strtotime($result->LogDate));  \n          \n          $status = \"P\"; //P for present  \n         var_dump($out_time);\n        // die(); \n      }else{\n         $bio_att_day = date('d');\n         $today = date('Y-m-d');\n         $time = \"\"; \n         $status = \"A\"; //P for present\n         \n        \n      } */     \n      //echo \"
    \";\n      //print_r($result);\n      $attend_blank = array();\n      $no_of_days = 31;\n      for ($i=1; $no_of_days >= $i; $i++) {\n          if($i < 10){\n            $j = '0'.$i;\n          }else{\n            $j = $i;\n          }\n          $today = date('Y-08-'.$j);\n            \n            $attend_blank[$today] = array('day'=>$i,'attendance'=>'A','attendance_date'=>$today,'attendance_time'=>'','out_time'=>'');\n        }\n\n\n      $dateArray = array();\n      if(!empty($result)){\n        foreach ($result as $key_res => $res) {\n          $bio_att_day = date('d',strtotime($res->LogDate));\n           //if(empty($res->attendance_time)){\n            $today = date('Y-m-d',strtotime($res->LogDate));\n            $time = date(\"h:i:sa\",strtotime($res->LogDate));\n            $out_time = date(\"h:i:sa\",strtotime($res->LogDate));  \n            $status = \"P\";\n           \n            if(in_array($today, $dateArray)){\n              $tempArray = $attend[$today];\n              $attend[$today] = array('day'=>$tempArray['day'],'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$tempArray['attendance_time'],'out_time'=>$out_time);\n            }else{\n               $attend[$today] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$time,'out_time'=>'');\n            }\n            $dateArray[$key_res]= $today;\n       \n      }\n      }\n\n\n      //echo \"
    \";\n      //print_r($attend);\n      //print_r($attend_blank);\n      //$final_array = array_merge($attend,$attend_blank);\n      foreach ($attend_blank as $key_blank => $blank) {\n          if(array_key_exists($key_blank, $attend)){\n            $final_array[$key_blank] = $attend[$key_blank];\n          }else{\n            $final_array[$key_blank] = $blank;\n          }\n      }\n      //print_r($final_array);\n      echo $attendance_record = json_encode(array_values($final_array));  \n     die;\n\n\n      //*/var_dump($today);\n      /*foreach ($attendance_data_decode as $att_data) {\n        // var_dump($out_time);\n        // die();\n        if($att_data->day == $bio_att_day){\n      /// for out time  check 'attendance_time' \n            if(empty($att_data->attendance_time)){\n            $attend[] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$time,'out_time'=>'');\n            }else{\n              $attend[] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$att_data->attendance_time,'out_time'=>$out_time);\n            }\n          }else{\n              $attend[] = $att_data;\n          }\n      }\n      \n      $attendance_record = json_encode($attend); */ \n      //var_dump($condition);  \n\n      //$this->m_bio_att->update_attandance($attendance_record,$time,$condition,$type);\n      $em_id = substr($em_id, 1); \n     // $data['attendance_data'] = json_encode($attend);\n      $data['attendance_data'] = $attendance_record;\n      $this->db->where('employee_id',$em_id);\n      $this->db->where('month','08');\n      $this->db->where('year','2019');\n      $this->db->update('employee_attendances',$data);\n      //$this->m_bio_att->update_attandance($data); \n       //die;\n    }\n\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914163,"cells":{"blob_id":{"kind":"string","value":"0b216ed27db043f8f090cbd8e10d276b2660b494"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"StepanKovalenko/trustly-client-php"},"path":{"kind":"string","value":"/Trustly/Data/jsonrpcrequest.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7005,"string":"7,005"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","MIT"],"string":"[\n  \"Apache-2.0\",\n  \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" array());\n\n\t\t\tif(isset($data)) {\n\t\t\t\tif(!is_array($data) && isset($attributes)) {\n\t\t\t\t\tthrow new Trustly_DataException('Data must be array if attributes is provided');\n\t\t\t\t}\n\t\t\t\t$payload['params']['Data'] = $data;\n\t\t\t}\n\n\t\t\tif(isset($attributes)) {\n\t\t\t\tif(!isset($payload['params']['Data'])) {\n\t\t\t\t\t$payload['params']['Data'] = array();\n\t\t\t\t}\n\t\t\t\t$payload['params']['Data']['Attributes'] = $attributes;\n\t\t\t}\n\t\t}\n\n\t\tparent::__construct($method, $payload);\n\n\t\tif(isset($method)) {\n\t\t\t$this->payload['method'] = $method;\n\t\t}\n\n\t\tif(!isset($this->payload['params'])) {\n\t\t\t$this->payload['params'] = array();\n\t\t}\n\n\t\t$this->set('version', '1.1');\n\n\t}\n\n\n\t/**\n\t * Set a value in the params section of the request\n\t *\n\t * @param string $name Name of parameter\n\t *\n\t * @param mixed $value Value of parameter\n\t *\n\t * @return mixed $value\n\t */\n\tpublic function setParam($name, $value) {\n\t\t$this->payload['params'][$name] = Trustly_Data::ensureUTF8($value);\n\t\treturn $value;\n\t}\n\n\n\t/**\n\t * Get the value of a params parameter in the request\n\t *\n\t * @param string $name Name of parameter of which to obtain the value\n\t *\n\t * @return mixed The value\n\t */\n\tpublic function getParam($name) {\n\t\tif(isset($this->payload['params'][$name])) {\n\t\t\treturn $this->payload['params'][$name];\n\t\t}\n\t\treturn NULL;\n\t}\n\n\n\t/**\n\t * Pop the value of a params parameter in the request. I.e. get the value\n\t * and then remove the value from the params.\n\t *\n\t * @param string $name Name of parameter of which to obtain the value\n\t *\n\t * @return mixed The value\n\t */\n\tpublic function popParam($name) {\n\t\t$v = NULL;\n\t\tif(isset($this->payload['params'][$name])) {\n\t\t\t$v = $this->payload['params'][$name];\n\t\t}\n\t\tunset($this->payload['params'][$name]);\n\t\treturn $v;\n\t}\n\n\n\t/**\n\t * Set the UUID value in the outgoing call.\n\t *\n\t * @param string $uuid The UUID\n\t *\n\t * @return string $uuid\n\t */\n\tpublic function setUUID($uuid) {\n\t\t$this->payload['params']['UUID'] = Trustly_Data::ensureUTF8($uuid);\n\t\treturn $uuid;\n\t}\n\n\n\t/**\n\t * Get the UUID value from the outgoing call.\n\t *\n\t * @return string The UUID value\n\t */\n\tpublic function getUUID() {\n\t\tif(isset($this->payload['params']['UUID'])) {\n\t\t\treturn $this->payload['params']['UUID'];\n\t\t}\n\t\treturn NULL;\n\t}\n\n\t/**\n\t * Set the Method value in the outgoing call.\n\t *\n\t * @param string $method The name of the API method this call is for\n\t *\n\t * @return string $method\n\t */\n\tpublic function setMethod($method) {\n\t\treturn $this->set('method', $method);\n\t}\n\n\n\t/**\n\t * Get the Method value from the outgoing call.\n\t *\n\t * @return string The Method value.\n\t */\n\tpublic function getMethod() {\n\t\treturn $this->get('method');\n\t}\n\n\n\t/**\n\t * Set a value in the params->Data part of the payload.\n\t *\n\t * @param string $name The name of the Data parameter to set\n\t *\n\t * @param mixed $value The value of the Data parameter to set\n\t *\n\t * @return mixed $value\n\t */\n\tpublic function setData($name, $value) {\n\t\tif(!isset($this->payload['params']['Data'])) {\n\t\t\t$this->payload['params']['Data'] = array();\n\t\t}\n\t\t$this->payload['params']['Data'][$name] = Trustly_Data::ensureUTF8($value);\n\t\treturn $value;\n\t}\n\n\n\t/**\n\t * Get the value of one parameter in the params->Data section of the\n\t * request. Or the entire Data section if no name is given.\n\t *\n\t * @param string $name Name of the Data param to obtain. Leave as NULL to\n\t *\t\tget the entire structure.\n\t *\n\t * @return mixed The value or the entire Data depending on $name\n\t */\n\tpublic function getData($name=NULL) {\n\t\tif(isset($name)) {\n\t\t\tif(isset($this->payload['params']['Data'][$name])) {\n\t\t\t\treturn $this->payload['params']['Data'][$name];\n\t\t\t}\n\t\t} else {\n\t\t\tif(isset($this->payload['params']['Data'])) {\n\t\t\t\treturn $this->payload['params']['Data'];\n\t\t\t}\n\t\t}\n\t\treturn NULL;\n\t}\n\n\n\t/**\n\t * Set a value in the params->Data->Attributes part of the payload.\n\t *\n\t * @param string $name The name of the Attributes parameter to set\n\t *\n\t * @param mixed $value The value of the Attributes parameter to set\n\t *\n\t * @return mixed $value\n\t */\n\tpublic function setAttribute($name, $value) {\n\t\tif(!isset($this->payload['params']['Data'])) {\n\t\t\t$this->payload['params']['Data'] = array();\n\t\t}\n\n\t\tif(!isset($this->payload['params']['Data']['Attributes'])) {\n\t\t\t$this->payload['params']['Data']['Attributes'] = array();\n\t\t}\n\t\t$this->payload['params']['Data']['Attributes'][$name] = Trustly_Data::ensureUTF8($value);\n\t\treturn $value;\n\t}\n\n\n\t/**\n\t * Get the value of one parameter in the params->Data->Attributes section\n\t * of the request. Or the entire Attributes section if no name is given.\n\t *\n\t * @param string $name Name of the Attributes param to obtain. Leave as NULL to\n\t *\t\tget the entire structure.\n\t *\n\t * @return mixed The value or the entire Attributes depending on $name\n\t */\n\tpublic function getAttribute($name) {\n\t\tif(isset($this->payload['params']['Data']['Attributes'][$name])) {\n\t\t\treturn $this->payload['params']['Data']['Attributes'][$name];\n\t\t}\n\t\treturn NULL;\n\t}\n}\n/* vim: set noet cindent sts=4 ts=4 sw=4: */\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914164,"cells":{"blob_id":{"kind":"string","value":"2838764f80fb96c99eac7279a5716585b7f97fcb"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"igorbunov/checkbox-in-ua-php-sdk"},"path":{"kind":"string","value":"/src/Models/CashRegisters/CashRegistersQueryParams.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":691,"string":"691"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n  \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" 1000) {\n            throw new \\Exception('Limit cant be more then 1000');\n        }\n\n        $this->inUse = $inUse;\n        $this->offset = $offset;\n        $this->limit = $limit;\n    }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914165,"cells":{"blob_id":{"kind":"string","value":"fdda5b5b4e22b9510ee83070887ccc9676e2bb32"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"thulioprado/api-next"},"path":{"kind":"string","value":"/src/Database/Collection.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1488,"string":"1,488"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"name = $name;\n        $this->prefix = $database->prefix();\n\n        /** @var Connection $connection */\n        $connection = $database->connection();\n        $this->connection = $connection;\n    }\n\n    public function name(): string\n    {\n        return $this->prefix.$this->name;\n    }\n\n    public function prefix(): string\n    {\n        return $this->prefix;\n    }\n\n    public function fullName(): string\n    {\n        return $this->connection->getTablePrefix().$this->prefix.$this->name;\n    }\n\n    public function builder(): Builder\n    {\n        return $this->connection->table($this->name());\n    }\n\n    public function drop(): void\n    {\n        $this->connection->getSchemaBuilder()->drop($this->name());\n    }\n\n    public function truncate(): void\n    {\n        $this->connection->table($this->name())->truncate();\n    }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914166,"cells":{"blob_id":{"kind":"string","value":"796efcedbc4ed92b5fc7cce81952ff86e2c0c1c7"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"ZED-Magdy/PHP-DDD-Blog-exapmle"},"path":{"kind":"string","value":"/src/Domain/Blog/Service/DeleteTagServiceInterface.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":359,"string":"359"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"name; \n    $breed_alt_name = $results[0]->alt_names;\n    $breed_image = $results[0]->image->url;\n    $breed_des = $results[0]->description;\n    $breed_temp = $results[0]->temperament;\n    $breed_life_span = $results[0]->life_span;\n    $breed_origin = $results[0]->origin;\n    $breed_weight = $results[0]->weight->imperial;\n    $wiki_page = $results[0]->wikipedia_url;\n?>\n\n\n    \n        \n        \n        \n\n        \n        \n\n        \n        \n        \n        \n        Breeds\n    \n    \n        \n        
    \n \n

    ' . $breed_name . '

    \n

    Alternate Names: ' . $breed_alt_name . '

    \n
    \n

    ' . $breed_des . '

    \n

    This cat breed is from ' . $breed_origin . '

    \n

    Life Span: ' . $breed_life_span . ' years

    \n

    Weight: ' . $breed_weight . 'lb

    \n

    Temperament: ' . $breed_temp . '

    \n Checkout Wikipedia Page!\n
    \n '; \n ?>\n
    \n \n \n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914168,"cells":{"blob_id":{"kind":"string","value":"d762a3aa4e638b71e3fe5b5fbfc4ef4e39b18eea"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"30002731/6210-SCP"},"path":{"kind":"string","value":"/SCP Files/connection.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":479,"string":"479"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"query(\"select * from SCP_Subjects\") or die($connection->error());\r\n \r\n \r\n \r\n?>\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914169,"cells":{"blob_id":{"kind":"string","value":"28e6a389df275333f7d793ac4f4c64bb54260622"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"vkabachenko/yii2-eer"},"path":{"kind":"string","value":"/common/models/Student.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2323,"string":"2,323"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" 100],\n [['email'], 'string', 'max' => 250],\n [['email'], 'email'],\n [['email'], 'unique'],\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function attributeLabels()\n {\n return [\n 'id' => 'ID',\n 'name' => 'Фамилия Имя Отчество',\n 'email' => 'Email',\n ];\n }\n\n /**\n * @return \\yii\\db\\ActiveQuery\n */\n public function getStudentEducations()\n {\n return $this->hasMany(StudentEducation::className(), ['id_student' => 'id']);\n }\n\n /**\n * @return \\yii\\db\\ActiveQuery\n */\n public function getStudentPortfolios()\n {\n return $this->hasMany(StudentPortfolio::className(), ['id_student' => 'id']);\n }\n\n /**\n * @inheritdoc\n */\n public function beforeDelete()\n {\n/*\n * Удаляются все записи портфолио.\n * Поскольку модель Tree не поддерживает удаление корневых элементов,\n * для удаления не используется стандартный метод delete модели, а\n * используется DAO.\n */\n if (parent::beforeDelete()) {\n /*\n * Сначала удаляются все файлы, связанные с портфолио, а затем все записи\n */\n $models = $this->studentPortfolios;\n foreach ($models as $model) {\n $model->deleteFile();\n }\n\n Yii::$app->db->\n createCommand()->\n delete('student_portfolio',['id_student' => $this->id])->\n execute();\n return true;\n }\n else {\n return false;\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914170,"cells":{"blob_id":{"kind":"string","value":"cc5badccabbf19be1208393873734aed98301de5"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"michael158/vidafascinante"},"path":{"kind":"string","value":"/modules/Admin/Entities/User.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2324,"string":"2,324"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"upload($data['image'], null, 'users'): null;\n }\n $data['password'] = bcrypt($data['password']);\n $post = $this->create($data);\n } catch (\\Exception $e) {\n throw $e;\n DB::rollback();\n }\n\n DB::commit();\n\n return $post;\n }\n\n public function editUser($data , $user)\n {\n DB::beginTransaction();\n try {\n if (isset($data['image'])) {\n $mUpload = new Upload();\n $data['image'] = !empty($data['image']) ? $mUpload->upload($data['image'], null, 'users') : null;\n }\n\n if (!empty($data['password'])) {\n $data['password'] = bcrypt($data['password']);\n } else {\n unset($data['password']);\n }\n\n $post = $user->update($data);\n } catch (\\Exception $e) {\n throw $e;\n DB::rollback();\n }\n\n DB::commit();\n\n return $post;\n }\n\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914171,"cells":{"blob_id":{"kind":"string","value":"72e9b344591c4af0f9ecbb3d596a91a086bb3f08"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"i80586/RCache"},"path":{"kind":"string","value":"/tests/FileCacheTest.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2060,"string":"2,060"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n * @date 11 August, 2016\n */\nclass FileCacheTest extends PHPUnit_Framework_TestCase\n{\n /**\n * @var RCache\\Cache \n */\n private $cache;\n \n /**\n * Init test\n */\n public function setUp()\n {\n # create temporary directory for cache\n if ( ! is_dir($directory = __DIR__ . '/cache')) {\n mkdir($directory);\n }\n \n $this->cache = new Cache(new FileCache($directory));\n }\n \n /**\n * Test set and get value\n */\n public function testManually()\n {\n $this->cache->set('test-identifier', 'test-value', 120);\n \n # assert existing cache and equal value\n $this->assertEquals('test-value', $this->cache->get('test-identifier'));\n }\n \n /**\n * Test fragment cache\n */\n public function testFragment()\n {\n # write content to cache\n if ($this->cache->start('test-fragment', 120)) {\n \n echo 'test-fragment-content';\n \n $this->cache->end(); }\n \n # test fragment cache\n if ($this->cache->start('test-fragment', 120)) {\n \n $this->assertTrue(false);\n \n $this->cache->end(); }\n }\n \n /**\n * Test cache expire / duration\n */\n public function testCacheExpire()\n {\n $this->cache->set('test-expire', 'test-value', 2);\n \n # assert existing cache\n $this->assertTrue($this->cache->has('test-expire'));\n \n sleep(3);\n \n # assert for expire cache\n $this->assertFalse($this->cache->has('test-expire'));\n }\n \n /**\n * Test deleting cache\n */\n public function testDelete()\n {\n foreach (['test-identifier', 'test-fragment'] as $identifier) {\n $this->cache->drop($identifier);\n $this->assertFalse($this->cache->has($identifier));\n } \n }\n \n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914172,"cells":{"blob_id":{"kind":"string","value":"68e3ff779db20c9b82f6faa6676467330781eafd"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"theolaye/symfony2"},"path":{"kind":"string","value":"/src/Entity/User.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2312,"string":"2,312"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"id;\n }\n\n public function getNomcomplet(): ?string\n {\n return $this->nomcomplet;\n }\n\n public function setNomcomplet(string $nomcomplet): self\n {\n $this->nomcomplet = $nomcomplet;\n\n return $this;\n }\n\n public function getTelephone(): ?int\n {\n return $this->telephone;\n }\n\n public function setTelephone(int $telephone): self\n {\n $this->telephone = $telephone;\n\n return $this;\n }\n\n public function getEmail(): ?string\n {\n return $this->email;\n }\n\n public function setEmail(string $email): self\n {\n $this->email = $email;\n\n return $this;\n }\n\n public function getAdresse(): ?string\n {\n return $this->adresse;\n }\n\n public function setAdresse(string $adresse): self\n {\n $this->adresse = $adresse;\n\n return $this;\n }\n\n public function getIdprofil(): ?profil\n {\n return $this->idprofil;\n }\n\n public function setIdprofil(?profil $idprofil): self\n {\n $this->idprofil = $idprofil;\n\n return $this;\n }\n\n public function getIdpartenaire(): ?partenaire\n {\n return $this->idpartenaire;\n }\n\n public function setIdpartenaire(?partenaire $idpartenaire): self\n {\n $this->idpartenaire = $idpartenaire;\n\n return $this;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914173,"cells":{"blob_id":{"kind":"string","value":"099d3679399b42c2ad53f082c008e8f4ada21ea7"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"pear/pear-core"},"path":{"kind":"string","value":"/PEAR/Command.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":12395,"string":"12,395"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\n * @author Greg Beaver \n * @copyright 1997-2009 The Authors\n * @license http://opensource.org/licenses/bsd-license.php New BSD License\n * @link http://pear.php.net/package/PEAR\n * @since File available since Release 0.1\n */\n\n/**\n * Needed for error handling\n */\nrequire_once 'PEAR.php';\nrequire_once 'PEAR/Frontend.php';\nrequire_once 'PEAR/XMLParser.php';\n\n/**\n * List of commands and what classes they are implemented in.\n * @var array command => implementing class\n */\n$GLOBALS['_PEAR_Command_commandlist'] = array();\n\n/**\n * List of commands and their descriptions\n * @var array command => description\n */\n$GLOBALS['_PEAR_Command_commanddesc'] = array();\n\n/**\n * List of shortcuts to common commands.\n * @var array shortcut => command\n */\n$GLOBALS['_PEAR_Command_shortcuts'] = array();\n\n/**\n * Array of command objects\n * @var array class => object\n */\n$GLOBALS['_PEAR_Command_objects'] = array();\n\n/**\n * PEAR command class, a simple factory class for administrative\n * commands.\n *\n * How to implement command classes:\n *\n * - The class must be called PEAR_Command_Nnn, installed in the\n * \"PEAR/Common\" subdir, with a method called getCommands() that\n * returns an array of the commands implemented by the class (see\n * PEAR/Command/Install.php for an example).\n *\n * - The class must implement a run() function that is called with three\n * params:\n *\n * (string) command name\n * (array) assoc array with options, freely defined by each\n * command, for example:\n * array('force' => true)\n * (array) list of the other parameters\n *\n * The run() function returns a PEAR_CommandResponse object. Use\n * these methods to get information:\n *\n * int getStatus() Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL)\n * *_PARTIAL means that you need to issue at least\n * one more command to complete the operation\n * (used for example for validation steps).\n *\n * string getMessage() Returns a message for the user. Remember,\n * no HTML or other interface-specific markup.\n *\n * If something unexpected happens, run() returns a PEAR error.\n *\n * - DON'T OUTPUT ANYTHING! Return text for output instead.\n *\n * - DON'T USE HTML! The text you return will be used from both Gtk,\n * web and command-line interfaces, so for now, keep everything to\n * plain text.\n *\n * - DON'T USE EXIT OR DIE! Always use pear errors. From static\n * classes do PEAR::raiseError(), from other classes do\n * $this->raiseError().\n * @category pear\n * @package PEAR\n * @author Stig Bakken \n * @author Greg Beaver \n * @copyright 1997-2009 The Authors\n * @license http://opensource.org/licenses/bsd-license.php New BSD License\n * @version Release: @package_version@\n * @link http://pear.php.net/package/PEAR\n * @since Class available since Release 0.1\n */\nclass PEAR_Command\n{\n // {{{ factory()\n\n /**\n * Get the right object for executing a command.\n *\n * @param string $command The name of the command\n * @param object $config Instance of PEAR_Config object\n *\n * @return object the command object or a PEAR error\n */\n public static function &factory($command, &$config)\n {\n if (empty($GLOBALS['_PEAR_Command_commandlist'])) {\n PEAR_Command::registerCommands();\n }\n if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {\n $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];\n }\n if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {\n $a = PEAR::raiseError(\"unknown command `$command'\");\n return $a;\n }\n $class = $GLOBALS['_PEAR_Command_commandlist'][$command];\n if (!class_exists($class)) {\n require_once $GLOBALS['_PEAR_Command_objects'][$class];\n }\n if (!class_exists($class)) {\n $a = PEAR::raiseError(\"unknown command `$command'\");\n return $a;\n }\n $ui =& PEAR_Command::getFrontendObject();\n $obj = new $class($ui, $config);\n return $obj;\n }\n\n // }}}\n // {{{ & getObject()\n public static function &getObject($command)\n {\n $class = $GLOBALS['_PEAR_Command_commandlist'][$command];\n if (!class_exists($class)) {\n require_once $GLOBALS['_PEAR_Command_objects'][$class];\n }\n if (!class_exists($class)) {\n return PEAR::raiseError(\"unknown command `$command'\");\n }\n $ui =& PEAR_Command::getFrontendObject();\n $config = &PEAR_Config::singleton();\n $obj = new $class($ui, $config);\n return $obj;\n }\n\n // }}}\n // {{{ & getFrontendObject()\n\n /**\n * Get instance of frontend object.\n *\n * @return object|PEAR_Error\n */\n public static function &getFrontendObject()\n {\n $a = &PEAR_Frontend::singleton();\n return $a;\n }\n\n // }}}\n // {{{ & setFrontendClass()\n\n /**\n * Load current frontend class.\n *\n * @param string $uiclass Name of class implementing the frontend\n *\n * @return object the frontend object, or a PEAR error\n */\n public static function &setFrontendClass($uiclass)\n {\n $a = &PEAR_Frontend::setFrontendClass($uiclass);\n return $a;\n }\n\n // }}}\n // {{{ setFrontendType()\n\n /**\n * Set current frontend.\n *\n * @param string $uitype Name of the frontend type (for example \"CLI\")\n *\n * @return object the frontend object, or a PEAR error\n */\n public static function setFrontendType($uitype)\n {\n $uiclass = 'PEAR_Frontend_' . $uitype;\n return PEAR_Command::setFrontendClass($uiclass);\n }\n\n // }}}\n // {{{ registerCommands()\n\n /**\n * Scan through the Command directory looking for classes\n * and see what commands they implement.\n *\n * @param bool (optional) if FALSE (default), the new list of\n * commands should replace the current one. If TRUE,\n * new entries will be merged with old.\n *\n * @param string (optional) where (what directory) to look for\n * classes, defaults to the Command subdirectory of\n * the directory from where this file (__FILE__) is\n * included.\n *\n * @return bool TRUE on success, a PEAR error on failure\n */\n public static function registerCommands($merge = false, $dir = null)\n {\n $parser = new PEAR_XMLParser;\n if ($dir === null) {\n $dir = dirname(__FILE__) . '/Command';\n }\n if (!is_dir($dir)) {\n return PEAR::raiseError(\"registerCommands: opendir($dir) '$dir' does not exist or is not a directory\");\n }\n $dp = @opendir($dir);\n if (empty($dp)) {\n return PEAR::raiseError(\"registerCommands: opendir($dir) failed\");\n }\n if (!$merge) {\n $GLOBALS['_PEAR_Command_commandlist'] = array();\n }\n\n while ($file = readdir($dp)) {\n if ($file[0] == '.' || substr($file, -4) != '.xml') {\n continue;\n }\n\n $f = substr($file, 0, -4);\n $class = \"PEAR_Command_\" . $f;\n // List of commands\n if (empty($GLOBALS['_PEAR_Command_objects'][$class])) {\n $GLOBALS['_PEAR_Command_objects'][$class] = \"$dir/\" . $f . '.php';\n }\n\n $parser->parse(file_get_contents(\"$dir/$file\"));\n $implements = $parser->getData();\n foreach ($implements as $command => $desc) {\n if ($command == 'attribs') {\n continue;\n }\n\n if (isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {\n return PEAR::raiseError('Command \"' . $command . '\" already registered in ' .\n 'class \"' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '\"');\n }\n\n $GLOBALS['_PEAR_Command_commandlist'][$command] = $class;\n $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc['summary'];\n if (isset($desc['shortcut'])) {\n $shortcut = $desc['shortcut'];\n if (isset($GLOBALS['_PEAR_Command_shortcuts'][$shortcut])) {\n return PEAR::raiseError('Command shortcut \"' . $shortcut . '\" already ' .\n 'registered to command \"' . $command . '\" in class \"' .\n $GLOBALS['_PEAR_Command_commandlist'][$command] . '\"');\n }\n $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command;\n }\n\n if (isset($desc['options']) && $desc['options']) {\n foreach ($desc['options'] as $oname => $option) {\n if (isset($option['shortopt']) && strlen($option['shortopt']) > 1) {\n return PEAR::raiseError('Option \"' . $oname . '\" short option \"' .\n $option['shortopt'] . '\" must be ' .\n 'only 1 character in Command \"' . $command . '\" in class \"' .\n $class . '\"');\n }\n }\n }\n }\n }\n\n ksort($GLOBALS['_PEAR_Command_shortcuts']);\n ksort($GLOBALS['_PEAR_Command_commandlist']);\n @closedir($dp);\n return true;\n }\n\n // }}}\n // {{{ getCommands()\n\n /**\n * Get the list of currently supported commands, and what\n * classes implement them.\n *\n * @return array command => implementing class\n */\n public static function getCommands()\n {\n if (empty($GLOBALS['_PEAR_Command_commandlist'])) {\n PEAR_Command::registerCommands();\n }\n return $GLOBALS['_PEAR_Command_commandlist'];\n }\n\n // }}}\n // {{{ getShortcuts()\n\n /**\n * Get the list of command shortcuts.\n *\n * @return array shortcut => command\n */\n public static function getShortcuts()\n {\n if (empty($GLOBALS['_PEAR_Command_shortcuts'])) {\n PEAR_Command::registerCommands();\n }\n return $GLOBALS['_PEAR_Command_shortcuts'];\n }\n\n // }}}\n // {{{ getGetoptArgs()\n\n /**\n * Compiles arguments for getopt.\n *\n * @param string $command command to get optstring for\n * @param string $short_args (reference) short getopt format\n * @param array $long_args (reference) long getopt format\n *\n * @return void\n */\n public static function getGetoptArgs($command, &$short_args, &$long_args)\n {\n if (empty($GLOBALS['_PEAR_Command_commandlist'])) {\n PEAR_Command::registerCommands();\n }\n if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {\n $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];\n }\n if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {\n return null;\n }\n $obj = &PEAR_Command::getObject($command);\n return $obj->getGetoptArgs($command, $short_args, $long_args);\n }\n\n // }}}\n // {{{ getDescription()\n\n /**\n * Get description for a command.\n *\n * @param string $command Name of the command\n *\n * @return string command description\n */\n public static function getDescription($command)\n {\n if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) {\n return null;\n }\n return $GLOBALS['_PEAR_Command_commanddesc'][$command];\n }\n\n // }}}\n // {{{ getHelp()\n\n /**\n * Get help for command.\n *\n * @param string $command Name of the command to return help for\n */\n public static function getHelp($command)\n {\n $cmds = PEAR_Command::getCommands();\n if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {\n $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];\n }\n if (isset($cmds[$command])) {\n $obj = &PEAR_Command::getObject($command);\n return $obj->getHelp($command);\n }\n return false;\n }\n // }}}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914174,"cells":{"blob_id":{"kind":"string","value":"7cd4bfa1eb3937b09d14801840dc3fb9b94611f2"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"toanht15/moni"},"path":{"kind":"string","value":"/apps/classes/brandco/cp/CpInstantWinActionManager.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9745,"string":"9,745"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"cp_actions = $this->getModel(\"CpActions\");\n $this->cp_concrete_actions = $this->getModel(\"CpInstantWinActions\");\n $this->cp_transaction_service = $this->getService('CpTransactionService');\n $this->instant_win_prize_service = $this->getService('InstantWinPrizeService');\n $this->logger = aafwLog4phpLogger::getDefaultLogger();\n }\n\n /**\n * @param $cp_action_id\n * @return mixed\n */\n public function getCpActions($cp_action_id) {\n $cp_action = $this->getCpActionById($cp_action_id);\n if ($cp_action === null) {\n $cp_concrete_action = null;\n } else {\n $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action);\n }\n if($cp_concrete_action == null) {\n $instant_win_prizes = null;\n } else {\n $instant_win_prizes = $this->instant_win_prize_service->getInstantWinPrizesByCpInstantWinActionId($cp_concrete_action->id);\n }\n return array($cp_action, $cp_concrete_action, $instant_win_prizes);\n }\n\n /**\n * @param $cp_action_group_id\n * @param $type\n * @param $status\n * @param $order_no\n * @return array|mixed\n */\n public function createCpActions($cp_action_group_id, $type, $status, $order_no) {\n $cp_action = $this->createCpAction($cp_action_group_id, $type, $status, $order_no);\n $cp_concrete_action = $this->createConcreteAction($cp_action);\n $this->cp_transaction_service->createCpTransaction($cp_action->id);\n $this->instant_win_prize_service->createInitInstantWinPrizes($cp_concrete_action->id);\n return array($cp_action, $cp_concrete_action);\n }\n\n /**\n * @param CpAction $cp_action\n * @return mixed|void\n */\n public function deleteCpActions(CpAction $cp_action) {\n $this->cp_transaction_service->deleteCpTransaction($cp_action->id);\n $this->deleteConcreteAction($cp_action);\n $this->deleteCpAction($cp_action);\n }\n\n /**\n * @param CpAction $cp_action\n * @param $data\n * @return mixed|void\n */\n public function updateCpActions(CpAction $cp_action, $data) {\n $this->updateCpAction($cp_action);\n $cp_concrete_action = $this->updateConcreteAction($cp_action, $data);\n $this->instant_win_prize_service->updateInstantWinPrizes($cp_concrete_action->id, $data);\n }\n\n /**\n * @param CpAction $cp_action\n * @return mixed\n */\n public function getConcreteAction(CpAction $cp_action) {\n return $this->getCpConcreteActionByCpAction($cp_action);\n }\n\n /**\n * @param CpAction $cp_action\n * @return mixed\n */\n public function createConcreteAction(CpAction $cp_action) {\n $cp_concrete_action = $this->cp_concrete_actions->createEmptyObject();\n $cp_concrete_action->cp_action_id = $cp_action->id;\n $cp_concrete_action->title = \"スピードくじ\";\n $cp_concrete_action->text = \"\";\n $cp_concrete_action->time_value = 1;\n $cp_concrete_action->time_measurement = CpInstantWinActions::TIME_MEASUREMENT_DAY;\n $cp_concrete_action->logic_type = CpInstantWinActions::LOGIC_TYPE_RATE;\n $cp_concrete_action->once_flg = InstantWinPrizes::ONCE_FLG_ON;\n $this->cp_concrete_actions->save($cp_concrete_action);\n return $cp_concrete_action;\n }\n\n /**\n * @param CpAction $cp_action\n * @param $data\n * @return mixed|void\n */\n public function updateConcreteAction(CpAction $cp_action, $data) {\n $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action);\n $cp_concrete_action->title = $data['title'];\n $cp_concrete_action->text = $data['text'];\n $cp_concrete_action->html_content = Markdown::defaultTransform($data['text']);\n $cp_concrete_action->time_value = $data['time_value'];\n $cp_concrete_action->time_measurement = $data['time_measurement'];\n $cp_concrete_action->once_flg = $data['once_flg'];\n $cp_concrete_action->logic_type = $data['logic_type'];\n $this->cp_concrete_actions->save($cp_concrete_action);\n return $cp_concrete_action;\n }\n\n /**\n * @param CpAction $cp_action\n * @return mixed|void\n */\n public function deleteConcreteAction(CpAction $cp_action) {\n $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action);\n $cp_concrete_action->del_flg = 1;\n $this->cp_concrete_actions->save($cp_concrete_action);\n }\n\n /**\n * @param CpAction $old_cp_action\n * @param $new_cp_action_id\n * @return mixed|void\n */\n public function copyConcreteAction(CpAction $old_cp_action, $new_cp_action_id) {\n $old_concrete_action = $this->getConcreteAction($old_cp_action);\n $new_concrete_action = $this->cp_concrete_actions->createEmptyObject();\n $new_concrete_action->cp_action_id = $new_cp_action_id;\n $new_concrete_action->title = $old_concrete_action->title;\n $new_concrete_action->text = $old_concrete_action->text;\n $new_concrete_action->html_content = $old_concrete_action->html_content;\n $new_concrete_action->time_value = $old_concrete_action->time_value;\n $new_concrete_action->time_measurement = $old_concrete_action->time_measurement;\n $new_concrete_action->once_flg = $old_concrete_action->once_flg;\n $new_concrete_action->logic_type = $old_concrete_action->logic_type;\n $new_cp_instant_win_action = $this->cp_concrete_actions->save($new_concrete_action);\n\n $this->cp_transaction_service->createCpTransaction($new_cp_action_id);\n $this->instant_win_prize_service->copyInstantWinPrizes($new_cp_instant_win_action->id, $old_concrete_action->id);\n }\n\n /**\n * @param CpAction $cp_action\n * @return entity\n */\n private function getCpConcreteActionByCpAction(CpAction $cp_action) {\n return $this->cp_concrete_actions->findOne(array(\"cp_action_id\" => $cp_action->id));\n }\n\n /**\n * @param $cp_action_id\n * @return entity\n */\n public function getCpConcreteActionByCpActionId($cp_action_id) {\n return $this->cp_concrete_actions->findOne(array(\"cp_action_id\" => $cp_action_id));\n }\n\n /**\n * 次回参加までの待機時間を変換する\n * @param $cp_concrete_action\n * @return string\n */\n public function changeValueIntoTime($cp_concrete_action) {\n if ($cp_concrete_action->time_measurement == CpInstantWinActions::TIME_MEASUREMENT_MINUTE) {\n $waiting_time = '+' . $cp_concrete_action->time_value . ' minutes';\n } elseif ($cp_concrete_action->time_measurement == CpInstantWinActions::TIME_MEASUREMENT_HOUR) {\n $waiting_time = '+' . $cp_concrete_action->time_value . ' hours';\n } else {\n $waiting_time = '+' . $cp_concrete_action->time_value . ' days';\n }\n return $waiting_time;\n }\n\n /**\n * @param CpAction $cp_action\n * @return mixed|void\n */\n public function deletePhysicalRelatedCpActionData(CpAction $cp_action, $with_concrete_actions = false) {\n if (!$cp_action || !$cp_action->id) {\n throw new Exception(\"CpInstantWinActionManager#deletePhysicalRelatedCpActionData cp_action_id=\" . $cp_action->id);\n }\n if ($with_concrete_actions) {\n //TODO delete concrete action\n }\n\n //delete instant win action user log\n /** @var InstantWinUserService $instant_win_user_service */\n $instant_win_user_service = $this->getService(\"InstantWinUserService\");\n $instant_win_user_service->deletePhysicalUserLogsByCpActionId($cp_action->id);\n\n // 当選予定時刻か初期化\n $cp_concrete_action = $this->getConcreteAction($cp_action);\n $instant_win_prize = $this->instant_win_prize_service->getInstantWinPrizeByPrizeStatus($cp_concrete_action->id, InstantWinPrizes::PRIZE_STATUS_PASS);\n $this->instant_win_prize_service->resetInstantWinTime($instant_win_prize);\n }\n\n public function deletePhysicalRelatedCpActionDataByCpUser(CpAction $cp_action, CpUser $cp_user) {\n if (!$cp_action || !$cp_user) {\n throw new Exception(\"CpInstantWinActionManager#deletePhysicalRelatedCpActionDataByCpUser cp_action_id=\" . $cp_action->id);\n }\n /** @var InstantWinUserService $instant_win_user_service */\n $instant_win_user_service = $this->getService(\"InstantWinUserService\");\n $instant_win_user_service->deletePhysicalUserLogsByCpActionIdAndCpUserId($cp_action->id, $cp_user->id);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914175,"cells":{"blob_id":{"kind":"string","value":"175d34f6241c51d1532d4c12e74fc164b1bee943"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"nam-duc-tong/ban_hang_hoa_qua_PHP"},"path":{"kind":"string","value":"/admin/product/add.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7054,"string":"7,054"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n\n\n\n \n \n \n Thêm sửa sản phẩm\n\t\n\t\n\n\t\n\t\n\n\t\n\t\n\n\t\n\t\n \n \n \n \n \n\n\n \n
    \n
    \n
    \n

    Thêm/Sửa Sản Phẩm

    \n
    \n
    \n \n
    \n \n \" hidden=\"true\">\n \">\n
    \n
    \n \n \n
    \n \n
    \n \n \">\n
    \n \n
    \n \n \" onchange=\"updateThumbnail()\">\n \"style=\"max-width:200px\" id=\"img_thumbnail\">\n
    \n\n
    \n \n \n
    \n \n \n
    \n
    \n
    \n \n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914176,"cells":{"blob_id":{"kind":"string","value":"47cd3e734204dda7140c70f05d31f04dd11f3a81"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"renanfvcunha/devsbook"},"path":{"kind":"string","value":"/src/controllers/LoginController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4139,"string":"4,139"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"loggedUser = LoginHandler::checkLoggedUser();\n\n if ($this->loggedUser) {\n $this->redirect('');\n }\n\n $this->render('signin');\n }\n\n /**\n * Efetuar Login\n */\n public function SignInAction()\n {\n $data = json_decode(file_get_contents('php://input'));\n\n $email = filter_var($data->email, FILTER_VALIDATE_EMAIL);\n $password = filter_var($data->password, FILTER_SANITIZE_STRING);\n\n // Validando inputs\n if (!$email || !$password) {\n http_response_code(400);\n echo json_encode([\n \"error\" =>\n \"Verifique se preencheu corretamente todos os campos.\",\n ]);\n exit();\n }\n\n // Verificando dados para autenticação\n try {\n $token = LoginHandler::verifyLogin($email, $password);\n if (!$token) {\n http_response_code(401);\n echo json_encode([\n \"error\" => \"E-mail e/ou Senha Incorreto(s).\",\n ]);\n exit();\n }\n\n // Autenticando usuário e atribuindo token\n $_SESSION['token'] = $token;\n } catch (\\Throwable $th) {\n http_response_code(500);\n echo json_encode([\n \"error\" =>\n \"Erro interno do servidor. Tente novamente ou contate o suporte.\",\n ]);\n $this->setErrorLog($th);\n exit();\n }\n }\n\n /**\n * Renderização de tela para\n * cadastro de novo usuário\n */\n public function SignUpRequest()\n {\n $this->loggedUser = LoginHandler::checkLoggedUser();\n\n if ($this->loggedUser) {\n $this->redirect('');\n }\n\n $this->render('signup');\n }\n\n /**\n * Cadastro de novo usuário\n */\n public function SignUpAction()\n {\n $data = json_decode(file_get_contents('php://input'));\n\n $name = filter_var($data->name, FILTER_SANITIZE_FULL_SPECIAL_CHARS);\n $email = filter_var($data->email, FILTER_VALIDATE_EMAIL);\n $password = filter_var($data->password, FILTER_SANITIZE_STRING);\n $birthdate = filter_var($data->birthdate, FILTER_SANITIZE_STRING);\n\n // Verificando campos obrigatórios\n if (!$name || !$email || !$password || !$birthdate) {\n http_response_code(400);\n echo json_encode([\n \"error\" =>\n \"Verifique se preencheu corretamente todos os campos.\",\n ]);\n exit();\n }\n\n // Validando campo birthdate\n $birthdate = ValidatorsHandler::birthdateValidator($birthdate);\n if (!$birthdate) {\n http_response_code(400);\n echo json_encode([\"error\" => \"Data informada é inválida.\"]);\n exit();\n }\n\n try {\n // Verificando duplicidade\n if (User::emailExists($email)) {\n http_response_code(400);\n echo json_encode([\n \"error\" => \"E-mail informado já está cadastrado.\",\n ]);\n exit();\n }\n\n // Cadastrando e autenticando usuário\n $token = User::addUser($name, $email, $password, $birthdate);\n $_SESSION['token'] = $token;\n } catch (\\Throwable $th) {\n http_response_code(500);\n echo json_encode([\n \"error\" =>\n \"Erro interno do servidor. Tente novamente ou contate o suporte.\",\n ]);\n $this->setErrorLog($th);\n exit();\n }\n }\n\n public function SignOut()\n {\n $_SESSION['token'] = '';\n $this->redirect('');\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914177,"cells":{"blob_id":{"kind":"string","value":"d078eed7cea7803640fed404b61e88c41759de3d"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"cenpaul07/test_app_laracast"},"path":{"kind":"string","value":"/app/Http/Controllers/PaymentsController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1049,"string":"1,049"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"user(),new PaymentReceived()); //use this syntax for multiple users\n// request()->user()->notify(new PaymentReceived('5$')); //better and readable syntax for single users\n\n ProductPurchased::dispatch('toy');//or event(new ProductPurchased('toy'));\n\n\n// return redirect(route('payment.create'))\n// ->with('message','User Notified Successfully.');\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914178,"cells":{"blob_id":{"kind":"string","value":"39747dfb2595bb13b4eac616a82a09e9ee9fc32d"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"ThomasWeinert/carica-firmata"},"path":{"kind":"string","value":"/src/Response/SysEx/PinStateResponse.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1453,"string":"1,453"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","MIT"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" Firmata\\Pin::MODE_OUTPUT,\n 0x00 => Firmata\\Pin::MODE_INPUT,\n 0x02 => Firmata\\Pin::MODE_ANALOG,\n 0x03 => Firmata\\Pin::MODE_PWM,\n 0x04 => Firmata\\Pin::MODE_SERVO,\n 0x05 => Firmata\\Pin::MODE_SHIFT,\n 0x06 => Firmata\\Pin::MODE_I2C\n ];\n\n /**\n * @param array $bytes\n */\n public function __construct(array $bytes) {\n parent::__construct(Firmata\\Board::PIN_STATE_RESPONSE, $bytes);\n $length = count($bytes);\n $this->_pin = $bytes[0];\n $this->_mode = $this->_modes[$bytes[1]] ?? FALSE;\n $this->_value = $bytes[2];\n for ($i = 3, $shift = 7; $i < $length; ++$i, $shift *= 2) {\n $this->_value |= ($bytes[$i] << $shift);\n }\n }\n\n /**\n * @param string $name\n * @return int\n */\n public function __get($name) {\n switch ($name) {\n case 'pin' :\n return $this->_pin;\n case 'mode' :\n return $this->_mode;\n case 'value' :\n return $this->_value;\n }\n return parent::__get($name);\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914179,"cells":{"blob_id":{"kind":"string","value":"303a3ad434f7cf18fdab30209304776becb53670"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"alphachoi/duobaohui"},"path":{"kind":"string","value":"/package/search/SearchObject.class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8428,"string":"8,428"},"score":{"kind":"number","value":2.875,"string":"2.875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"searchType = $searchType;\n\t\tif ($searchType == \"cpc\") {\n\t\t\t$this->sphinxClient = parent::_getSecondSphinxClient();\n\t\t}\n\t\telse {\n\t\t\t$this->sphinxClient = parent::_getSphinxClient();\n\t\t} \n\t}\n\n\tpublic function __tostring() {\n\t\t//排序\n\t\tuasort($this->filters, array($this, \"cmp\"));\n\t\tuasort($this->filterRanges, array($this, \"cmp\"));\n\t\tuasort($this->filterFloatRanges, array($this, \"cmp\"));\n\t\t$filtersString = print_r($this->filters, TRUE);\t\n\t\t$filterRangesString = print_r($this->filterRanges, TRUE);\t\n\t\t$filterFloatRangesString = print_r($this->filterFloatRanges, TRUE);\t\n\t\t$keywordsString = print_r($this->keywords, TRUE);\n\t\t$limitString = print_r($this->limit, TRUE);\n\t\t$key = \"filters:{$filtersString}_filterRanges:{$filterRangesString}_filterFloatRanges:{$filterFloatRangesString}_keyWords:{$keywordsString}_limit:{$limitString}\";\n\t\treturn $key;\n\t}\n\n\tpublic function cmp($a, $b) {\n\t\t$bigger = 0;\n\t\tif ($a['attribute'] > $b['attribute']) {\n\t\t\t$bigger = 1;\n\t\t}\t\n\t\telse if ($a['attribute'] === $b['attribute']) {\n\t\t\t$bigger = 0;\n\t\t}\n\t\telse {\n\t\t\t$bigger = -1;\n\t\t}\n\t\treturn $bigger;\n\t}\n\n\t/**\n\t * 调用获取SearchObject\n\t * @author xuanzheng@meilishuo.com\n\t */\n//\tstatic public function getSearchClient() {\n//\t\treturn new SearchObject();\n//\t}\n\n\t/**\n\t * 设置limit\n\t * @author xuanzheng@meilishuo.com\n\t */\n\tpublic function setLimit($offset, $limit, $maxMatches = 12000, $cutoff = 0) {\n\t\tif ($limit <= 0) {\n\t\t\t$limit = 1;\n\t\t}\n\t\t$newLimit = array(\n\t\t\t'offset' => $offset,\n\t\t\t'limit' => $limit,\n\t\t\t'maxMatches' => $maxMatches,\n\t\t\t'cutoff' => $cutoff\n\t\t);\n\t\t$this->limit = $newLimit;\n\t\treturn TRUE;\n\t}\n\n\t/**\n\t * 设置过滤条件,搜索出values中指定的内容\n\t * @author xuanzheng@meilishuo.com\n\t * @param string attribute\n\t * @param array values\n\t * @param bool exclude\n\t */\n\tpublic function setFilter($attribute, $values, $exclude = false) {\n\t\tif (empty($attribute)) {\n\t\t\treturn FALSE;\n\t\t}\n\t\t$filter = array('attribute' => $attribute, 'values' => $values, 'exclude' => $exclude);\n\t\tarray_push($this->filters, $filter);\n\t\treturn TRUE;\t\n\t}\t\n\n\t/**\n\t * 设置过滤条件,搜索出min,max中指定的范围\n\t * @author xuanzheng@meilishuo.com\n\t * @param string attribute\n\t * @param int min \n\t * @param int max \n\t * @param bool exclude\n\t */\n\tpublic function setFilterRange($attribute, $min, $max, $exclude = false) {\n\t\tif (empty($attribute)) {\n\t\t\treturn FALSE;\n\t\t}\n\t\t$filterRange = array('attribute' => $attribute, 'min' => intval($min), 'max' => intval($max), 'exclude' => $exclude);\n\t\tarray_push($this->filterRanges, $filterRange);\n\t\treturn TRUE;\n\t}\n\n\n\t/**\n\t * 设置过滤条件,搜索出min,max中指定的范围\n\t * @author xuanzheng@meilishuo.com\n\t * @param string attribute\n\t * @param float min \n\t * @param float max \n\t * @param bool exclude\n\t */\n\tpublic function setFilterFloatRange($attribute, $min, $max, $exclude = false) {\n\t\tif (empty($attribute)) {\n\t\t\treturn FALSE;\n\t\t}\n\t\t$filterFloatRange = array('attribute' => $attribute, 'min' => (float)$min, 'max' => (float)$max, 'exclude' => $exclude);\n\t\tarray_push($this->filterFloatRanges, $filterFloatRange);\n\t\treturn TRUE;\n\t}\n\n\n\n\t/**\n\t * 设置排序模式,详见文档\n\t * @author xuanzheng@meilishuo.com\n\t * @param NULL define in API\n\t * @param string sortBy\n\t */\n\tpublic function setSortMode($mode, $sortBy) {\n\t\tif (empty($mode)) {\n\t\t\treturn FALSE;\n\t\t}\n\t\t$this->sortMode = $mode;\n\t\t$this->sortBy = $sortBy;\n\t\treturn TRUE;\n\t}\n\n\t/**\n\t * SetMatchMode\n\t *\n\t */\n\tpublic function setMatchMode($matchMode) {\n\t\tif (empty($matchMode)) {\n\t\t\treturn FALSE;\n\t\t}\n\t\t$this->matchMode = $matchMode;\t\n\t\treturn TRUE;\n\t}\n\n\t/**\n\t * 设置所用的搜索索引\n\t * @param string \n\t */\n\tpublic function setIndex($index) {\n\t\tif (empty($index)) {\n\t\t\treturn FALSE;\n\t\t}\n\t\t$this->index = $index;\n\t\treturn TRUE;\n\t}\n\n\tpublic function setMaxQueryTime($maxQueryTime) {\n\t\t$this->maxQueryTime = $maxQueryTime;\n\t\treturn TRUE;\n\t}\n\n\n\tpublic function setUseCache($useCache = TRUE) {\n\t\t$this->useCache = $useCache;\n\t\treturn TRUE;\n\t}\n\n\t/**\n\t * 开始搜索\n\t * @author xuanzheng@meilishuo.com\n\t * @param keywords\n\t */\n\tpublic function search($keywords) {\n\t\t$this->keywords = $keywords;\n\t\t$this->conditionLoad();\n\t\tif ($this->useCache) {\n\t\t\t$result = $this->searchFromCache($this);\t\t\n\t\t\tif (empty($result['matches'])) {\n\t\t\t\t$result = $this->searchFromSphinx($keywords, $this->index);\n\t\t\t\t$this->putSearchResultIntoCache($result);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t$result = $this->searchFromSphinx($keywords, $this->index);\n\t\t}\n\t\t$this->searchResult = $result;\t\n\t\treturn TRUE;\n\t}\n\n\tprivate function searchFromCache($searchObject) {\n\t\t$searchResult = SearchCache::getSearch($this);\t\n\t\treturn $searchResult;\n\t}\n\n\tprivate function putSearchResultIntoCache($searchResult) {\n\t\t$bool = SearchCache::setSearch($this, $searchResult);\n\t\treturn $bool;\n\t}\n\n\tprivate function searchFromSphinx($keywords, $index) {\n\t\tif ($this->searchType == 'cpc') {\n\t\t\t$result = parent::secondQueryViaValidConnection($keywords, $index);\n\t\t}\n\t\telse {\n\t\t\t$result = parent::queryViaValidConnection($keywords, $index);\n\t\t}\n\t\treturn $result;\n\t}\n\n\tpublic function getSearchResult() {\n\t\treturn $this->searchResult;\t\n\t} \n\n\tpublic function conditionLoad() {\n\t\t$this->conditionReset();\n\t\t$this->maxQueryTimeLoad();\n\t\t$this->limitLoad();\n\t\t$this->filtersLoad();\n\t\t$this->filterRangeLoad();\n\t\t$this->filterFloatRangesLoad();\n\t\t$this->sortModeLoad();\n\t\t$this->matchModeLoad();\n\t\treturn TRUE;\n\t}\n\n\tpublic function resetFilters() {\n\t\t$this->sphinxClient->ResetFilters();\t\n\t\t$this->filters = array();\n\t\t$this->filterRanges = array();\n\t\t$this->filterFloatRanges = array();\n\t\treturn TRUE;\n\t}\n\n\t/**\n\t * TODO 加入limit reset\n\t */\n\tprivate function conditionReset() {\n\t\t$this->sphinxClient->ResetFilters();\t\n\t\treturn TRUE;\n\t}\n\n\tprivate function maxQueryTimeLoad() {\n\t\t$this->sphinxClient->SetMaxQueryTime($this->maxQueryTime);\n\t\treturn TRUE;\n\t}\n\n\tprivate function matchModeLoad() {\n\t\t$this->sphinxClient->SetMatchMode($this->matchMode);\n\t\treturn TRUE;\n\t}\n\n\tprivate function sortModeLoad() {\n\t\t$this->sphinxClient->SetSortMode($this->sortMode, $this->sortBy);\n\t\treturn TRUE;\n\t}\n\n\tprivate function limitLoad() {\n\t\tif (empty($this->limit)) {\n\t\t\treturn FALSE; \n\t\t}\n\t\tif(!empty($this->limit) && !isset($this->limit['maxMatches'])) { \n\t\t\t$this->limit['maxMatches'] = self::max; \n\t\t} \n\t\t$this->sphinxClient->SetLimits($this->limit['offset'], $this->limit['limit'], $this->limit['maxMatches'], $this->limit['cutoff']);\n\t\treturn TRUE;\n\t}\n\n\tprivate function filtersLoad() {\n\t\tforeach ($this->filters as $filter) {\n\t\t\t$this->sphinxClient->SetFilter($filter['attribute'], $filter['values'], $filter['exclude']);\t\n\t\t}\n\t\treturn TRUE;\n\t}\n\n\tprivate function filterRangeLoad() {\n\t\tforeach ($this->filterRanges as $filterRange) {\n\t\t\t$this->sphinxClient->SetFilterRange($filterRange['attribute'], $filterRange['min'], $filterRange['max'], $filterRange['exclude']);\n\t\t}\n\t\treturn TRUE;\t\n\t}\n\n\tprivate function filterFloatRangesLoad() {\n\t\tforeach ($this->filterFloatRanges as $filterFloatRange) {\n\t\t\t$this->sphinxClient->SetFilterFloatRange($filterFloatRange['attribute'], $filterFloatRange['min'], $filterFloatRange['max'], $filterFloatRange['exclude']);\t\n\t\t}\n\t\treturn TRUE;\n\t}\n\n\n\tpublic function getSearchString($wordParams) {\n\t\tif (empty($wordParams['word_id']) && empty($wordParams['word_name'])) {\n\t\t\treturn FALSE;\n\t\t}\n\t\t$params = array();\n\t\t$params['word_name'] = $wordName;\n\t\t$params['isuse'] = 1;\n\t\t$wordInfo = AttrWords::getWordInfo($params, \"/*searchGoods-zx*/word_id,word_name\");\n\t\tif (!empty($wordInfo)) {\n\t\t\t$searchKeyArr = AttrWords::getSearchString($wordInfo[0]['word_id'], $wordName);\n\t\t}\n\t\telse{\n\t\t\t$searchKeyArr = array(\"{$wordName}\");\t\n\t\t}\n\t\t$searchString = \"(\" . implode(\")|(\", $searchKeyArr) . \")\";\n\t\t$this->searchString = $searchString;\n\t\treturn $searchString;\n\t}\n\n\tpublic function getIndex() {\n\t\treturn $this->index;\n\t}\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914180,"cells":{"blob_id":{"kind":"string","value":"2ca7813263dcaa8a2153b1fab5cb8140b34671f8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"apuc/guild"},"path":{"kind":"string","value":"/frontend/modules/api/controllers/TaskUserController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1514,"string":"1,514"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" ['get'],\n 'set-task-user' => ['post', 'patch'],\n ];\n }\n\n public function actionSetTaskUser()\n {\n $taskUserModel = new ProjectTaskUser();\n\n $params = Yii::$app->request->post();\n $taskUserModel->attributes = $params;\n\n if(!$taskUserModel->validate()){\n throw new BadRequestHttpException(json_encode($taskUserModel->errors));\n }\n\n $taskUserModel->save();\n\n return $taskUserModel->toArray();\n }\n\n /**\n * @throws NotFoundHttpException\n */\n public function actionGetTaskUsers()\n {\n $task_id = Yii::$app->request->get('task_id');\n if(empty($task_id) or !is_numeric($task_id))\n {\n throw new NotFoundHttpException('Incorrect task ID');\n }\n\n $tasks = $this->findUsers($task_id);\n\n if(empty($tasks)) {\n throw new NotFoundHttpException('The task does not exist or there are no employees for it');\n }\n\n return $tasks;\n }\n\n private function findUsers($project_id): array\n {\n return ProjectTaskUser::find()->where(['task_id' => $project_id])->all();\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914181,"cells":{"blob_id":{"kind":"string","value":"f444ca26f7fba9c771148a778c341f5295a4c87b"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"nxsaloj/miudl"},"path":{"kind":"string","value":"/app/miudl/Carrera/CarreraValidator.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2742,"string":"2,742"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" 'El campo Nombre no debe estar vacío',\n 'Apellidos.required' => 'El campo Apellidos no debe estar vacío',\n 'Ciclos.required' => 'El campo Ciclo no debe estar vacío',\n 'Facultad_id.required' => 'El campo Facultad no debe estar vacío',\n 'Codigo.required' => 'El campo Codigo no debe estar vacío',\n 'Codigo.unique' => 'El codigo especificado ya ha sido utilizado anteriormente',\n );\n\n public function isValid(array $params= array())\n {\n $reglas = array(\n 'Codigo' => 'required|unique:TB_Carrera',\n 'Nombre' => 'required',\n 'Ciclos'=>'required',\n 'Facultad_id' => 'required'\n );\n //\\Log::debug('Puesto P ' . print_r($params['facultad'], true));\n //$facultad = \\App\\Models\\Utils::getVueParam($params,\"facultad\",\"Facultad_id\");\n //\\Log::debug('Puesto ' . $facultad);\n $datos = array(\n 'Codigo' => $params['codigo'],\n 'Nombre' => $params['nombre'],\n 'Ciclos' => $params['ciclos'],\n 'Facultad_id' => isset($params['facultad'])? $params['facultad']:null,\n );\n\n $validator = Validator::make($datos, $reglas, $this->mensajes);\n\n if ($validator->fails()){\n $respuesta['mensaje'] = 'Por favor verifique los datos ingresados';\n $respuesta['errors'] = $validator;\n $respuesta['error'] = true;\n return $respuesta;\n }\n\n return $datos;\n }\n\n public function isValidUpdate(array $params, $id)\n {\n $reglas = array(\n 'Codigo' => 'required|unique:TB_Carrera,Codigo,'.$id.',id',\n 'Nombre' => 'required',\n 'Ciclos'=>'required',\n 'Facultad_id' => 'required'\n );\n //\\Log::debug('Puesto P ' . print_r($params['facultad'], true));\n //$facultad = \\App\\Models\\Utils::getVueParam($params,\"facultad\",\"Facultad_id\");\n //\\Log::debug('Puesto ' . $facultad);\n $datos = array(\n 'Codigo' => $params['codigo'],\n 'Nombre' => $params['nombre'],\n 'Ciclos' => $params['ciclos'],\n 'Facultad_id' => isset($params['facultad'])? $params['facultad']:null,\n );\n\n $validator = Validator::make($datos, $reglas, $this->mensajes);\n\n if ($validator->fails()){\n $respuesta['mensaje'] = 'Por favor verifique los datos ingresados';\n $respuesta['errors'] = $validator;\n $respuesta['error'] = true;\n return $respuesta;\n }\n\n return $datos;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914182,"cells":{"blob_id":{"kind":"string","value":"5420b92db3ec20e8f5eda3e3f3a1b5ddbeeb28dc"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"kanjengsaifu/erp_bnp"},"path":{"kind":"string","value":"/models/StockModel.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":14750,"string":"14,750"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"host, $this->username, $this->password, $this->db_name);\n }\n mysqli_set_charset(static::$db,\"utf8\");\n }\n\n function setTableName($table_name = \"tb_stock\"){\n $this->table_name = $table_name;\n }\n\n function createStockTable(){\n $sql = \"\n CREATE TABLE `\".$this->table_name.\"` ( \n `stock_code` int(11) NOT NULL COMMENT 'รหัสอ้างอิงคลังสินค้า',\n `stock_type` varchar(10) NOT NULL COMMENT 'ประเภท รับ หรือ ออก',\n `product_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงสินค้า',\n `stock_date` date DEFAULT NULL COMMENT 'วันที่ดำเนินการ',\n `in_qty` int(11) NOT NULL COMMENT 'จำนวน (เข้า)',\n `in_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (เข้า)',\n `in_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (เข้า)',\n `out_qty` int(11) NOT NULL COMMENT 'จำนวน (ออก)',\n `out_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (ออก)',\n `out_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (ออก)',\n `stock_qty` int(11) NOT NULL COMMENT 'จำนวน (คงเหลือ)',\n `stock_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (คงเหลือ)',\n `stock_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (คงเหลือ)',\n `delivery_note_supplier_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการยืมเข้า',\n `delivery_note_customer_list_code` varchar(50) DEFAULT NULL COMMENT 'รหัสอ้างอิงรายการยืมออก',\n `invoice_supplier_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการซื้อเข้า',\n `invoice_customer_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการขายออก',\n `stock_move_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการย้ายคลังสินค้า',\n `stock_issue_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการตัดคลังสินค้า',\n `credit_note_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการใบลดหนี้',\n `summit_product_code` varchar(50) NOT NULL COMMENT 'รหัสรายการสินค้ายกยอด',\n `stock_change_product_list_code` varchar(50) NOT NULL COMMENT 'รหัสรายการสินค้าเปลี่ยนชื่อ',\n `addby` varchar(50) NOT NULL COMMENT 'ผู้เพิ่ม',\n `adddate` datetime DEFAULT NULL COMMENT 'เวลาเพิ่ม',\n `updateby` varchar(50) DEFAULT NULL COMMENT 'ผู้แก้ไข',\n `lastupdate` datetime DEFAULT NULL COMMENT 'เวลาแก้ไข'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8; \n \";\n \n if (mysqli_query(static::$db,$sql)) {\n $sql = \"ALTER TABLE `\".$this->table_name.\"` \n ADD PRIMARY KEY (`stock_code`), \n ADD KEY `invoice_code` (`invoice_customer_list_code`,`invoice_supplier_list_code`);\n \";\n if (mysqli_query(static::$db,$sql)) {\n $sql = \"ALTER TABLE `\".$this->table_name.\"` \n MODIFY `stock_code` int(11) NOT NULL AUTO_INCREMENT COMMENT 'รหัสอ้างอิงคลังสินค้า'; \n \";\n if (mysqli_query(static::$db,$sql)) {return true;}\n else {return false;}\n }else {return false;}\n }else {return false;}\n }\n\n function deleteStockTable(){\n $sql = \"DROP TABLE IF EXISTS \".$this->table_name.\" ;\";\n\n if (mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) {\n return true;\n }else {\n return false;\n }\n }\n\n function getStockBy(){\n $sql = \" SELECT * FROM $table_name WHERE 1 \";\n if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) {\n $data = [];\n while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){\n $data[] = $row;\n }\n $result->close();\n return $data;\n }\n }\n\n function getStockLogListByDate($date_start = '', $date_end = '', $stock_group_code = '', $keyword = ''){\n $str = \" AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') \";\n\n $sql_old_in = \"SELECT SUM(in_qty) \n FROM \".$this->table_name.\" \n WHERE \".$this->table_name.\".product_code = tb.product_code \n AND stock_type = 'in' \n AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') < STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s')\";\n\n $sql_old_out = \"SELECT SUM(out_qty) \n FROM \".$this->table_name.\" \n WHERE \".$this->table_name.\".product_code = tb.product_code \n AND stock_type = 'out' \n AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') < STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s')\";\n\n $sql_in = \"SELECT SUM(in_qty) \n FROM \".$this->table_name.\" \n WHERE \".$this->table_name.\".product_code = tb.product_code \n AND stock_type = 'in' \".$str;\n\n $sql_out = \"SELECT SUM(out_qty) \n FROM \".$this->table_name.\" \n WHERE \".$this->table_name.\".product_code = tb.product_code \n AND stock_type = 'out' \".$str;\n\n $sql_borrow_in = \"SELECT SUM(in_qty) \n FROM \".$this->table_name.\" \n WHERE \".$this->table_name.\".product_code = tb.product_code \n AND stock_type = 'borrow_in' \".$str;\n\n $sql_borrow_out = \"SELECT SUM(out_qty) \n FROM \".$this->table_name.\" \n WHERE \".$this->table_name.\".product_code = tb.product_code \n AND stock_type = 'borrow_out' \".$str;\n\n $sql_minimum = \"SELECT SUM(minimum_stock) \n FROM tb_product_customer \n WHERE tb_product_customer.product_code = tb.product_code \n AND product_status = 'Active' \";\n\n $sql_safety = \"SELECT SUM(safety_stock) \n FROM tb_product_customer \n WHERE tb_product_customer.product_code = tb.product_code \n AND product_status = 'Active' \";\n\n $sql = \"SELECT tb.product_code, CONCAT(product_code_first,product_code) as product_code, \n product_name, product_type, product_status ,\n (IFNULL(($sql_old_in),0) - IFNULL(($sql_old_out),0)) as stock_old,\n IFNULL(($sql_in),0) as stock_in,\n IFNULL(($sql_out),0) as stock_out,\n IFNULL(($sql_borrow_in),0) as stock_borrow_in,\n IFNULL(($sql_borrow_out),0) as stock_borrow_out,\n IFNULL(($sql_safety),0) as stock_safety,\n IFNULL(($sql_minimum),0) as stock_minimum \n FROM tb_stock_report \n LEFT JOIN tb_product as tb ON tb_stock_report.product_code = tb.product_code \n WHERE stock_group_code = '$stock_group_code' \n AND (\n CONCAT(product_code_first,product_code) LIKE ('%$keyword%') \n OR product_name LIKE ('%$keyword%') \n ) \n ORDER BY CONCAT(product_code_first,product_code) \n \"; \n\n if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) {\n $data = [];\n while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){\n $data[] = $row;\n }\n $result->close();\n return $data;\n }\n }\n\n function getStockInByDate($date_start = '', $date_end = ''){\n $sql = \"SELECT stock_code, stock_date, \".$this->table_name.\".product_code, CONCAT(product_code_first,product_code) as product_code, \n product_name, product_type, product_status , in_qty , supplier_name_th, supplier_name_en \n FROM \".$this->table_name.\" \n LEFT JOIN tb_product ON \".$this->table_name.\".product_code = tb_product.product_code \n LEFT JOIN tb_invoice_supplier_list ON \".$this->table_name.\".invoice_supplier_list_code = tb_invoice_supplier_list.invoice_supplier_list_code \n LEFT JOIN tb_invoice_supplier ON tb_invoice_supplier_list.invoice_supplier_code = tb_invoice_supplier.invoice_supplier_code \n LEFT JOIN tb_supplier ON tb_invoice_supplier.supplier_code = tb_supplier.supplier_code \n WHERE stock_type = 'in' \n AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') \n AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') \n ORDER BY STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') \n \";\n\n\n if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) {\n $data = [];\n while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){\n $data[] = $row;\n }\n $result->close();\n return $data;\n }\n }\n\n function getStockOutByDate($date_start = '', $date_end = ''){\n $sql = \"SELECT stock_code, stock_date, \".$this->table_name.\".product_code, CONCAT(product_code_first,product_code) as product_code, \n product_name, product_type, product_status , out_qty , customer_name_th, customer_name_en \n FROM \".$this->table_name.\" \n LEFT JOIN tb_product ON \".$this->table_name.\".product_code = tb_product.product_code \n LEFT JOIN tb_invoice_customer_list ON \".$this->table_name.\".invoice_customer_list_code = tb_invoice_customer_list.invoice_customer_list_code \n LEFT JOIN tb_invoice_customer ON tb_invoice_customer_list.invoice_customer_code = tb_invoice_customer.invoice_customer_code \n LEFT JOIN tb_customer ON tb_invoice_customer.customer_code = tb_customer.customer_code \n WHERE stock_type = 'out' \n AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') \n AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') \n ORDER BY STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') \n \";\n\n if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) {\n $data = [];\n while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){\n $data[] = $row;\n }\n $result->close();\n return $data;\n }\n }\n\n function updateStockByCode($code,$data = []){\n $sql = \" UPDATE $table_name SET \n stock_type = '\".$data['stock_type'].\"' , \n product_code = '\".$data['product_code'].\"' , \n stock_date = '\".$data['stock_date'].\"' , \n in_qty = '\".$data['in_qty'].\"' , \n in_cost_avg = '\".$data['in_cost_avg'].\"' , \n in_cost_avg_total = '\".$data['in_cost_avg_total'].\"' , \n out_qty = '\".$data['out_qty'].\"' , \n out_cost_avg = '\".$data['out_cost_avg'].\"' , \n out_cost_avg_total = '\".$data['out_cost_avg_total'].\"' , \n balance_qty = '\".$data['balance_qty'].\"' , \n balance_price = '\".$data['balance_price'].\"' , \n balance_total = '\".$data['balance_total'].\"' , \n delivery_note_supplier_list_code = '\".$data['delivery_note_supplier_list_code'].\"' , \n delivery_note_customer_list_code = '\".$data['delivery_note_customer_list_code'].\"' , \n invoice_supplier_list_code = '\".$data['invoice_supplier_list_code'].\"' , \n invoice_customer_list_code = '\".$data['invoice_customer_list_code'].\"' , \n stock_move_list_code = '\".$data['stock_move_list_code'].\"' , \n regrind_supplier_list_code = '\".$data['regrind_supplier_list_code'].\"' , \n updateby = '\".$data['updateby'].\"', \n lastupdate = NOW() \n WHERE stock_code = '$code'\n \";\n\n if (mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) {\n return true;\n }else {\n return false;\n }\n }\n\n function insertStock($data = []){\n $sql = \" INSERT INTO tb_stock_group (\n stock_type, \n product_code, \n stock_date, \n in_qty, \n in_cost_avg, \n in_cost_avg_total, \n out_qty, \n out_cost_avg, \n out_cost_avg_total, \n balance_qty, \n balance_price, \n balance_total, \n delivery_note_supplier_list_code, \n delivery_note_customer_list_code, \n invoice_supplier_list_code, \n invoice_customer_list_code, \n regrind_supplier_list_code,\n stock_move_list_code, \n addby,\n adddate\n ) VALUES ( \n '\".$data['stock_type'].\"', \n '\".$data['product_code'].\"', \n '\".$data['stock_date'].\"', \n '\".$data['customer_code'].\"', \n '\".$data['supplier_code'].\"', \n '\".$data['in_qty'].\"', \n '\".$data['in_cost_avg'].\"', \n '\".$data['in_cost_avg_total'].\"', \n '\".$data['out_qty'].\"', \n '\".$data['out_cost_avg'].\"', \n '\".$data['out_cost_avg_total'].\"', \n '\".$data['balance_qty'].\"', \n '\".$data['balance_price'].\"', \n '\".$data['balance_total'].\"', \n '\".$data['delivery_note_supplier_list_code'].\"', \n '\".$data['delivery_note_customer_list_code'].\"', \n '\".$data['invoice_supplier_list_code'].\"', \n '\".$data['invoice_customer_list_code'].\"', \n '\".$data['regrind_supplier_list_code'].\"', \n '\".$data['stock_move_list_code'].\"', \n '\".$data['addby'].\"', \n NOW() \n )\";\n\n if(mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)){\n return true;\n }else{\n return false;\n }\n }\n\n function deleteStockByCode($code){\n $sql = \" DELETE FROM $table_name WHERE stock_code = '$code' ;\";\n if(mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)){\n return true;\n }else{\n return false;\n }\n }\n}\n?>\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914183,"cells":{"blob_id":{"kind":"string","value":"71b97e151d285faf37567f6df8084405fce87756"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"zhangjiquan1/phpsourcecode"},"path":{"kind":"string","value":"/web3d/yuncart/include/common/session.class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4321,"string":"4,321"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"session_name = $session_name;\r\n $this->lifetime = $lifetime;\r\n $this->_time = time();\r\n //验证session_id\r\n $tmpsess_id = '';\r\n if ($session_id) {\r\n $tmpsess_id = $session_id;\r\n } else {\r\n $tmpsess_id = cgetcookie($session_name);\r\n }\r\n\r\n if ($tmpsess_id && $this->verify($tmpsess_id)) {\r\n $this->session_id = substr($tmpsess_id, 0, 32);\r\n }\r\n if ($this->session_id) {\r\n\r\n //session_id 存在,加载session\r\n $this->read_session();\r\n } else {\r\n\r\n //session_id 不存在,生成,写入到cookie\r\n $this->session_id = $this->gene_session_id();\r\n $this->init_session();\r\n csetcookie($this->session_name, $this->session_id . $this->gene_salt($this->session_id));\r\n }\r\n //关闭时执行gc\r\n register_shutdown_function(array(&$this, 'gc'));\r\n }\r\n\r\n /**\r\n *\r\n * DB中insert新的session\r\n *\r\n */\r\n private function init_session()\r\n {\r\n DB::getDB()->insert(\"session\", array(\"session_id\" => $this->session_id, \"session_data\" => serialize(array()), 'time' => $this->_time));\r\n }\r\n\r\n /**\r\n *\r\n * 生成session_id\r\n *\r\n */\r\n private function gene_session_id()\r\n {\r\n $id = strval(time());\r\n while (strlen($id) < 32) {\r\n $id .= mt_rand();\r\n }\r\n return md5(uniqid($id, true));\r\n }\r\n\r\n /**\r\n *\r\n * 生成salt,验证\r\n *\r\n */\r\n private function gene_salt($session_id)\r\n {\r\n $ip = getClientIp();\r\n return sprintf(\"%8u\", crc32(SITEPATH . (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : \"\") . $ip . $session_id));\r\n }\r\n\r\n /**\r\n *\r\n * 生成salt,验证\r\n *\r\n */\r\n private function verify($tmpsess_id)\r\n {\r\n return substr($tmpsess_id, 32) == $this->gene_salt(substr($tmpsess_id, 0, 32));\r\n }\r\n\r\n /**\r\n *\r\n * 读出已知session\r\n *\r\n */\r\n private function read_session()\r\n {\r\n\r\n $session = DB::getDB()->selectrow(\"session\", \"*\", \"session_id = '\" . $this->session_id . \"'\");\r\n if (empty($session)) { //session为空,\r\n $this->init_session();\r\n $this->session_md5 = md5('a:0:{}');\r\n $this->session_time = 0;\r\n $GLOBALS['_SESSION'] = array();\r\n } else {\r\n\r\n if (!empty($session['session_data']) && $session['time'] > $this->_time - $this->lifetime) {\r\n $this->session_md5 = md5($session['session_data']);\r\n $this->session_time = $session['time'];\r\n $GLOBALS['_SESSION'] = unserialize($session['session_data']);\r\n } else { //session过期\r\n $this->session_md5 = md5(serialize(array()));\r\n $this->session_time = 0;\r\n $GLOBALS['_SESSION'] = array();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n *\r\n * 更新session\r\n *\r\n */\r\n private function write_session()\r\n {\r\n\r\n $data = serialize(!empty($GLOBALS['_SESSION']) ? $GLOBALS['_SESSION'] : array());\r\n $this->_time = time();\r\n\r\n\r\n //session未变化\r\n if (md5($data) == $this->session_md5 && $this->_time - $this->session_time < 10) {\r\n return true;\r\n }\r\n\r\n $ret = DB::getDB()->update(\"session\", array(\"time\" => $this->_time, \"session_data\" => addslashes($data)), \"session_id='\" . $this->session_id . \"'\", true);\r\n return $ret;\r\n }\r\n\r\n /**\r\n *\r\n * 执行gc\r\n *\r\n */\r\n public function gc()\r\n {\r\n $this->write_session();\r\n if ($this->_time % 2 == 0) {\r\n DB::getDB()->delete(\"session\", \"time<\" . ($this->_time - $this->lifetime));\r\n }\r\n return true;\r\n }\r\n\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914184,"cells":{"blob_id":{"kind":"string","value":"d1c92ef71291db71bb8916a01a27add5639e1a82"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"cyingfan/m3o-php"},"path":{"kind":"string","value":"/src/Model/Routing/RouteOutput.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1739,"string":"1,739"},"score":{"kind":"number","value":2.984375,"string":"2.984375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"distance;\n }\n\n /**\n * @param float $distance\n * @return static\n */\n public function setDistance(float $distance)\n {\n $this->distance = $distance;\n return $this;\n }\n\n public function getDuration(): float\n {\n return $this->duration;\n }\n\n /**\n * @param float $duration\n * @return static\n */\n public function setDuration(float $duration)\n {\n $this->duration = $duration;\n return $this;\n }\n\n /**\n * @return Waypoint[]\n */\n public function getWaypoints(): array\n {\n return $this->waypoints;\n }\n\n /**\n * @param Waypoint[]|array[] $waypoints\n * @return static\n */\n public function setWaypoints(array $waypoints)\n {\n $this->waypoints = $this->castModelArray($waypoints, Waypoint::class);\n return $this;\n }\n\n public static function fromArray(array $array): RouteOutput\n {\n return (new RouteOutput())\n ->setDistance((float) ($array['distance'] ?? 0.0))\n ->setDuration((float) ($array['duration'] ?? 0.0))\n ->setWaypoints($array['waypoints'] ?? []);\n }\n\n public function toArray(): array\n {\n return [\n 'distance' => $this->getDistance(),\n 'duration' => $this->getDuration(),\n 'waypoints' => array_map(fn(Waypoint $w) => $w->toArray(), $this->getWaypoints())\n ];\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914185,"cells":{"blob_id":{"kind":"string","value":"b2b78ec55aff1406eee46b2c68d12ebaaba373a2"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"renilsoni/mvc"},"path":{"kind":"string","value":"/Cybercom/Model/Customer/Address.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":432,"string":"432"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"setTableName('customer_address');\n\t\t$this->setPrimaryKey('addressId');\n\t}\n\n\tpublic function getStatusoptions()\n\t{\n\t\treturn [\n\t\t\tself::STATUS_ENABLED => 'Enable',\n\t\t\tself::STATUS_DISABLED => 'Disable'\n\t\t];\n\t}\n}\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914186,"cells":{"blob_id":{"kind":"string","value":"48912c8a02aa2a3a77c4ad6c30bbc95f20bf5af9"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"leanf19/TP_Final_IPOO"},"path":{"kind":"string","value":"/TPFinal/testTeatroFinal.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":10844,"string":"10,844"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" 4);\n}\n\nfunction menuTeatros()\n{\n $unTeatro = new Teatro();\n $auxTeatros = $unTeatro->listar();\n\n if (count($auxTeatros) != 0) {\n\n foreach ($auxTeatros as $teatro) {\n print $teatro->__toString();\n\n }\n do {\n echo \"\\n***Seleccione el id de uno de estos teatros***\\n\";\n $idteatro = trim(fgets(STDIN));\n $exito = $unTeatro->buscar($idteatro);\n } while (!$exito);\n\n echo \"***Teatro obtenido, seleccione una de las siguientes opciones***\\n\";\n do {\n // $exito = $unTeatro->buscar($idteatro);\n echo \"1.- Mostrar Informacion del teatro\\n\";\n echo \"2.- Modificar datos del teatro(nombre,direccion,funciones)\\n\";\n echo \"3.- Calcular costo total por uso del teatro\\n\";\n echo \"4.- Volver al menu de inicio\\n\";\n $opcion = trim(fgets(STDIN));\n switch ($opcion) {\n case 1:\n print $unTeatro->__toString();\n break;\n case 2:\n modificarDatos($unTeatro);\n break;\n case 3:\n echo \"Costo por el uso de las instalaciones: {$unTeatro->darCosto()}\\n\";\n break;\n case 4:\n break;\n default:\n echo \"Opcion no valida, ingrese una opcion->(1-4)\\n\";\n }\n } while ($opcion <> 4);\n\n } else {\n echo \"***No hay teatros para mostrar***\\n\";\n }\n}\n\nfunction modificarDatos($unTeatro)\n{\n $id = $unTeatro->getIdTeatro();\n $op = -1;\n do {\n\n echo \"***Seleccione una de las siguientes opciones***\\n\";\n echo \"1.- Cambiar datos del teatro(nombre y direccion)\\n\";\n echo \"2.- Agregar una nueva funcion\\n\";\n echo \"3.- Modificar una funcion\\n\";\n echo \"4.- Eliminar una funcion\\n\";\n echo \"5.- Volver al menú anterior\\n\";\n $op = trim(fgets(STDIN));\n switch ($op) {\n case 1:\n modificarTeatro($id);\n break;\n case 2:\n altaFuncion($unTeatro);\n break;\n case 3:\n modificarFuncion($unTeatro);\n break;\n case 4:\n bajaFuncion($unTeatro);\n break;\n default:\n echo \"Ingrese una opción correcta(1-5)\\n\";\n }\n } while ($op <> 5);\n}\n\n//Modifica el nombre y la direccion del teatro con la id pasada por parametro\nfunction modificarTeatro($idTeatro)\n{\n $unTeatro = new Teatro();\n $unTeatro->buscar($idTeatro);\n $nombre=$unTeatro->getNombre();\n $direccion=$unTeatro->getDireccion();\n $exito = false;\n $aux = 0;\n\n echo \"Desea modificar el nombre del teatro? (s/n):\\n\";\n $resp = trim(fgets(STDIN));\n\n if($resp == 's') {\n echo \"Ingrese el nuevo nombre del teatro seleccionado: \\n\";\n $nombre = trim(fgets(STDIN));\n $aux++;\n }\n $resp = \"n\";\n echo \"Desea modificar la direccion del teatro? (s/n):\\n\";\n $resp = trim(fgets(STDIN));\n\n if($resp == 's'){\n echo \"Ingrese la nueva direccion del teatro seleccionado: \\n\";\n $direccion = trim(fgets(STDIN));\n $aux++;\n }\n if($aux != 0){\n $exito =ABM_Teatro::modificarTeatro($idTeatro, $nombre, $direccion);\n\n if($exito){\n echo \"Datos del teatro modificados con exito!!!!\\n\";\n }\n }\n}\n\nfunction altaFuncion($unTeatro)\n{\n\n echo \"Ingrese el nombre de la función a agregar:\\n\";\n $nombreFuncion = strtolower(trim(fgets(STDIN)));\n\n do {\n echo \"Ingrese el tipo de funcion (Cine,Teatro,Musical):\\n\";\n $tipo = strtolower(trim(fgets(STDIN)));\n } while($tipo != \"cine\" && $tipo != \"musical\" && $tipo != \"teatro\");\n do {\n echo \"Ingrese el precio de la funcion:\\n\";\n $precio = trim(fgets(STDIN));\n } while (!is_numeric($precio));\n\n echo \"Ingrese el horario de la funcion en formato 24hrs (HH:MM):\\n\";\n $horaInicio = trim(fgets(STDIN));\n\n do {\n echo \"Ingrese la duracion de la funcion en minutos:\\n\";\n $duracion = trim(fgets(STDIN));\n } while (!is_numeric($duracion));\n\n switch ($tipo) {\n case \"teatro\":\n $exito = ABM_FuncionTeatro::altaFuncionTeatro(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro);\n break;\n case \"cine\":\n echo \"Ingrese el pais de origen:\\n\";\n $pais = trim(fgets(STDIN));\n echo \"Ingrese el genero:\\n\";\n $genero = trim(fgets(STDIN));\n $exito = ABM_FuncionCine::altaFuncionCine(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro, $genero, $pais);\n break;\n case \"musical\":\n echo \"Ingrese el director:\\n\";\n $director = trim(fgets(STDIN));\n echo \"Ingrese la cantidad de personas en escena:\\n\";\n $elenco = trim(fgets(STDIN));\n $exito = ABM_FuncionMusical::altaFuncionMusical(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro, $director, $elenco);\n break;\n }\n if (!$exito) {\n echo \"No es posible agregar la funcion, el horario de la funcion ingresada se solapa con otra funcion\\n\";\n }\n}\n\nfunction modificarFuncion($unTeatro)\n{\n\n $unaFuncion = new Funcion();\n\n\n echo \"Funciones disponibles en este teatro :\\n\";\n $cadenaFunciones = $unTeatro->recorrerFunciones();\n do {\n echo $cadenaFunciones;\n echo \"Ingrese el id de la función a modificar: \\n\";\n $idfuncion = strtolower(trim(fgets(STDIN)));\n $exito= $unaFuncion->buscar($idfuncion);\n } while (!is_numeric($idfuncion) || !$exito);\n\n echo \"Ingrese el nuevo nombre de la función: \\n\";\n $nombreFuncion = trim(fgets(STDIN));\n do {\n\n echo \"Ingrese el nuevo precio de la función: \\n\";\n $precioFuncion = trim(fgets(STDIN));\n } while (!is_numeric($precioFuncion));\n\n echo \"Ingrese la hora de la funcion en formato 24hrs (HH:MM):\\n\";\n $horaInicio = trim(fgets(STDIN));\n\n do {\n echo \"Ingrese la duracion de la funcion en minutos:\\n\";\n $duracion = trim(fgets(STDIN));\n } while (!is_numeric($duracion));\n\n $unaFuncion = $unTeatro->obtenerFunciones($idfuncion);\n $exito = false;\n switch (get_class($unaFuncion)) {\n case \"FuncionCine\":\n echo \"Ingrese el pais de origen de la funcion de cine:\\n\";\n $pais = trim(fgets(STDIN));\n echo \"Ingrese el genero de la funcion de cine:\\n\";\n $genero = trim(fgets(STDIN));\n $exito = ABM_FuncionCine::modificarFuncionCine($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro, $pais, $genero);\n break;\n case \"FuncionMusical\":\n echo \"Ingrese el director:\\n\";\n $director = trim(fgets(STDIN));\n echo \"Ingrese la cantidad de personas en escena:\\n\";\n $elenco = trim(fgets(STDIN));\n $exito = ABM_FuncionMusical::modificarFuncionMusical($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro, $director, $elenco);\n break;\n case \"FuncionTeatro\":\n $exito = ABM_FuncionTeatro::modificarFuncionTeatro($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro);\n }\n if (!$exito) {\n echo \"No se modificó la función porque el horario se solapa con el de otra funcion existente\\n\";\n } else {\n echo \"La funcion se modifico con exito!!!!\";\n }\n}\n\nfunction bajaFuncion($unTeatro)\n{\n $unaFuncion = new Funcion();\n echo \"Funciones disponibles en este teatro :\\n\";\n $funcionesTeatro = $unTeatro->recorrerFunciones();\n $exito = false;\n\n\n echo $funcionesTeatro;\n echo \"Seleccione el id de la función a eliminar:\\n\";\n $idfuncion = trim(fgets(STDIN));\n $unaFuncion=$unTeatro->obtenerFunciones($idfuncion);\n\n switch (get_class($unaFuncion)) {\n case \"FuncionCine\":\n $exito = ABM_FuncionCine::bajaFuncionCine($idfuncion);\n break;\n case \"FuncionMusical\":\n $exito = ABM_FuncionMusical::bajaFuncionMusical($idfuncion);\n break;\n case \"FuncionTeatro\":\n $exito = ABM_FuncionTeatro::bajaFuncionTeatro($idfuncion);\n }\n if($exito){\n echo \"Funcion eliminada con exito!!!\";\n } else {\n echo \"No se ha podido eliminar la funcion elegida\";\n }\n}\n\n\nfunction altaTeatro()\n{\n\n echo \"Ingrese el nombre del teatro:\\n\";\n $nombre = trim(fgets(STDIN));\n echo \"Ingrese la dirección del teatro:\\n\";\n $direccion = trim(fgets(STDIN));\n $exito = ABM_Teatro::altaTeatro($nombre, $direccion);\n if($exito)\n {\n echo \"***Teatro agregado con exito a la base de datos***\\n\";\n } else {\n echo \"***Fallo la carga del teatro a la base de datos***\\n\";\n }\n\n}\n\nfunction bajaTeatro()\n{\n\n mostrarTeatros();\n do {\n $exito = false;\n echo \"Seleccione el id del teatro que desea eliminar \\n\";\n $idteatro = trim(fgets(STDIN));\n $exito = ABM_Teatro::eliminarTeatro($idteatro);\n\n if($exito)\n {\n echo \"Se ha eliminado con exito el teatro de la BD\\n\";\n } else {\n echo \"No se pudo eliminar el teatro seleccionado\";\n }\n } while (!is_numeric($idteatro));\n\n}\n\nfunction mostrarTeatros()\n{\n $teatroTemp = new Teatro();\n $teatros = $teatroTemp->listar();\n\n foreach ($teatros as $teatro)\n print $teatro->__toString();\n echo \"---------------------------\\n\";\n\n}\n\n\n\nfunction main()\n{\n menu();\n}\n\n\nmain();"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914187,"cells":{"blob_id":{"kind":"string","value":"58c651ebc6c3440354274073de3cab20a3bf4cfe"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"lidonghui-ht/poptrip"},"path":{"kind":"string","value":"/Libs/ThirdParty/Ctrip/Hotel/Common/getDate.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2363,"string":"2,363"},"score":{"kind":"number","value":3.296875,"string":"3.296875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"0?date(\"Y\".$linkChar.\"m\".$linkChar.\"d\"):date(\"Y年m月d日\");\r\n\treturn $coutValue;\r\n}\r\n\r\n/**\r\n * 获取年月日形式的日期(参数为空,输出2012年12月23日;输入分隔符,则输出2012-12-23形式)\r\n * cltang 2012年5月11日 携程\r\n * @param $linkChar-分隔符号;\r\n */\r\nfunction getDateYMD_addDay($linkChar,$addDay)\r\n{\r\n\t$coutValue=strlen($linkChar)>0?date(\"Y\".$linkChar.\"m\".$linkChar.\"d\",strtotime(\"$d +$addDay day\")):date(\"Y年m月d日\",strtotime(\"$d +$addDay day\"));\r\n\t\r\n\treturn $coutValue;\r\n}\r\ndate(\"Y-m-d\",strtotime(\"$d +1 day\"));\r\n\r\n/**\r\n * 获取年月日时分秒形式的日期(参数为空,输出2012年12月23日 12:23:50;输入分隔符,则输出2012-12-23 12:23:50形式)\r\n * cltang 2012年5月11日 携程\r\n * @param $linkChar\r\n */\r\nfunction getDateYMDSHM($linkChar)\r\n{\r\n\t\r\n\t$coutValue=strlen($linkChar)>0?date(\"Y\".$linkChar.\"m\".$linkChar.\"d H:i:s\"):date(\"Y年m月d日 H:i:s\");\r\n\treturn $coutValue;\r\n}\r\n/**\r\n * 获取到当前Unix时间戳:分msec sec两个部分,msec是微妙部分,sec是自Unix纪元(1970-1-1 0:00:00)到现在的秒数\r\n */\r\nfunction getMicrotime()\r\n{\r\n\treturn microtime();\r\n}\r\n/**\r\n * \r\n * 将日期转换为秒\r\n * @param $datatime\r\n */\r\nfunction timeToSecond($datatime)\r\n{\r\n return\tstrtotime($datatime);\r\n}\r\n/**\r\n * \r\n * 计算时间的差值:返回{天、小时、分钟、秒}\r\n * @param $begin_time\r\n * @param $end_time\r\n */\r\nfunction timediff($begin_time,$end_time)\r\n{\r\n if($begin_time < $end_time){\r\n $starttime = $begin_time;\r\n $endtime = $end_time;\r\n }\r\n else{\r\n $starttime = $end_time;\r\n $endtime = $begin_time;\r\n }\r\n $timediff = $endtime-$starttime;\r\n //echo $begin_time.$end_time.$timediff;\r\n $days = intval($timediff/86400);\r\n $remain = $timediff%86400;\r\n $hours = intval($remain/3600);\r\n $remain = $remain%3600;\r\n $mins = intval($remain/60);\r\n $secs = $remain%60;\r\n $res = array(\"day\" => $days,\"hour\" => $hours,\"min\" => $mins,\"sec\" => $secs);\r\n return $res;\r\n}\r\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914188,"cells":{"blob_id":{"kind":"string","value":"72957372cfa2e0c22cf0ff14e39ac22178863d07"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"Arkos13/auth-service-symfony"},"path":{"kind":"string","value":"/application/src/Infrastructure/User/Repository/NetworkRepository.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2163,"string":"2,163"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"em = $em;\n }\n\n /**\n * @param string $email\n * @param string $network\n * @return Network|null\n * @throws NonUniqueResultException\n */\n public function findOneByEmailAndNetwork(string $email, string $network): ?Network\n {\n return $this->em->createQueryBuilder()\n ->select(\"networks\")\n ->from(Network::class, \"networks\")\n ->innerJoin(\"networks.user\", \"user\")\n ->andWhere(\"user.email = :email\")->setParameter(\"email\", $email)\n ->andWhere(\"networks.network = :network\")->setParameter(\"network\", $network)\n ->setMaxResults(1)\n ->getQuery()\n ->getOneOrNullResult();\n }\n\n /**\n * @param string $email\n * @param string $accessToken\n * @param string $network\n * @return Network|null\n * @throws NonUniqueResultException\n */\n public function findOneByEmailAndAccessToken(string $email, string $accessToken, string $network): ?Network\n {\n return $this->em->createQueryBuilder()\n ->select(\"networks\")\n ->from(Network::class, \"networks\")\n ->innerJoin(\"networks.user\", \"user\")\n ->andWhere(\"user.email = :email\")->setParameter(\"email\", $email)\n ->andWhere(\"networks.accessToken = :accessToken\")->setParameter(\"accessToken\", $accessToken)\n ->andWhere(\"networks.network = :network\")->setParameter(\"network\", $network)\n ->setMaxResults(1)\n ->getQuery()\n ->getOneOrNullResult();\n }\n\n public function updateAccessToken(Network $network, ?string $accessToken): void\n {\n $network->setAccessToken($accessToken);\n $this->em->persist($network);\n $this->em->flush();\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914189,"cells":{"blob_id":{"kind":"string","value":"520f4f5118d97a03206dc6a8fe29bab51f6b10e3"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"knh/werewolf"},"path":{"kind":"string","value":"/create_game.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1917,"string":"1,917"},"score":{"kind":"number","value":2.984375,"string":"2.984375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\";\n}\n$game_id = mt_rand(100000, 999999); //create a better random game id.\n$query=\"SELECT * FROM werewolf_gameid WHERE game_id=\" . $game_id;\n\n// to make sure the game id is unique\nwhile(true){\n\t$result=$mysqli->query($query);\n\tif($result->num_rows == 0)\n\t\tbreak;\n\t$game_id=rand(100000, 999999);\n\t$query=\"SELECT * FROM werewolf_gameid WHERE game_id = \" . $game_id;\n}\nif($mysqli->query(\"INSERT INTO werewolf_gameid (game_id, player_num_limit)\" .\n\t\"VALUES ('\" . $game_id . \"', '\" . $player_num .\"')\") == true){\n\techo \"
    Create game succeed. Your game id is \" . $game_id .\". Your friend can use this number to join in the game.
    \";\n}else{\n\techo \"
    Create game failed. Please try again later.
    \";\n}\n\n$query=\"INSERT INTO werewolf_detail (game_id, all_roles) VALUES ('\" . $game_id . \"', '\" . $raw_role_string . \"')\";\n\nif($mysqli->query($query)){\n\techo \"Redirecting to game console in 3 seconds. Do not refresh the page.
    \";\n\techo \"\"; // redirecting to control_game.php after creating game.\n}else{\n\techo \"Detail writing failed.
    \";\n}\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914190,"cells":{"blob_id":{"kind":"string","value":"7a53190f49179883fdb49b034066f15c1548e8a1"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"makasim/yadm-benchmark"},"path":{"kind":"string","value":"/src/Entity/OrmOrder.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1175,"string":"1,175"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"id;\n }\n\n /**\n * @param int $id\n */\n public function setId($id)\n {\n $this->id = $id;\n }\n\n /**\n * @return mixed\n */\n public function getNumber()\n {\n return $this->number;\n }\n\n /**\n * @param mixed $number\n */\n public function setNumber($number)\n {\n $this->number = $number;\n }\n\n /**\n * @return OrmPrice\n */\n public function getPrice()\n {\n return $this->price;\n }\n\n /**\n * @param OrmPrice $price\n */\n public function setPrice(OrmPrice $price = null)\n {\n $this->price = $price;\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914191,"cells":{"blob_id":{"kind":"string","value":"9e85ba580f4363fe1b7830365abc96dd83bcf6d8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"michaelvickersuk/laravel-tv-library"},"path":{"kind":"string","value":"/database/migrations/2020_05_06_203601_create_genres_table.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1048,"string":"1,048"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"id();\n $table->string('name');\n $table->timestamps();\n });\n\n DB::table('genres')\n ->insert([\n ['name' => 'Action'],\n ['name' => 'Animation'],\n ['name' => 'Comedy'],\n ['name' => 'Crime'],\n ['name' => 'Documentary'],\n ['name' => 'Drama'],\n ['name' => 'Horror'],\n ['name' => 'Mystery'],\n ['name' => 'Reality'],\n ['name' => 'Science Fiction'],\n ['name' => 'Thriller'],\n ['name' => 'Western'],\n ]);\n }\n\n public function down()\n {\n Schema::dropIfExists('genres');\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914192,"cells":{"blob_id":{"kind":"string","value":"37258cae0c9f72b4856d0d1adaa2843306fc78f9"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"rosko/AlmazService"},"path":{"kind":"string","value":"/php/backup/JsonResponseBuilder.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":481,"string":"481"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"response .= \"Error \" . $errorType . \": \" . $errorMsg;\n }\n \n public function addResource($resource) {\n \n }\n \n public function makeResponse() {\n \n }\n \n public function printResponse() {\n echo $this->response;\n }\n}\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914193,"cells":{"blob_id":{"kind":"string","value":"de54900417e4174abca15868f7b56a9c2cedc232"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"798256478/Design-Pattern"},"path":{"kind":"string","value":"/Strategy.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":965,"string":"965"},"score":{"kind":"number","value":3.6875,"string":"3.6875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"arr['title'] = $title;\n\t\t$this->arr['info'] = $info;\n\t}\n\n\tpublic function getData($objType)\n\t{\n\t\treturn $objType->get($this->arr);\n\t}\n}\n\n/**\n* 返回json类型的数据格式\n*/\nclass Json\n{\n\tpublic function get($data)\n\t{\n\t\treturn json_encode($data);\n\t}\n}\n\n/**\n* 返回xml类型的数据格式\n*/\nclass Xml\n{\n\tpublic function get($data)\n\t{\n\t\t$xml = '';\n\t\t$xml .= '';\n\t\t$xml .= ''.serialize($data).'';\n\t\t$xml .= '';\n\t\treturn $xml;\n\t}\n}\n\n$strategy = new Strategy('cd_1', 'cd_1');\necho $strategy->getData(new Json);\necho $strategy->getData(new Xml);\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914194,"cells":{"blob_id":{"kind":"string","value":"dcb62df97882fb75c7c6daaecb3568b48b0be456"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"lesstif/php-jira-rest-client"},"path":{"kind":"string","value":"/src/ClassSerialize.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1318,"string":"1,318"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" $value) {\n if ($excludeMode === true) {\n if (!in_array($key, $ignoreProperties)) {\n $retAr[$key] = $value;\n }\n } else { // include mode\n if (in_array($key, $ignoreProperties)) {\n $retAr[$key] = $value;\n }\n }\n }\n\n return $retAr;\n }\n\n /**\n * class property to String.\n *\n * @param array $ignoreProperties this properties to be excluded from String.\n * @param bool $excludeMode\n *\n * @return string\n */\n public function toString(array $ignoreProperties = [], bool $excludeMode = true): string\n {\n $ar = $this->toArray($ignoreProperties, $excludeMode);\n\n return json_encode($ar, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914195,"cells":{"blob_id":{"kind":"string","value":"6d0fa897f2975eb6630c0ba6883559ff1d1d387a"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"sdboyer/frozone"},"path":{"kind":"string","value":"/src/Lockable.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1128,"string":"1,128"},"score":{"kind":"number","value":3.203125,"string":"3.203125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"container($container);\n $this->baseResolver = $baseResolver;\n }\n\n /**\n * Resolve `$toResolve` into a callable\n *\n * @param mixed $toResolve\n * @return callable\n */\n public function resolve($toResolve)\n {\n try {\n $resolved = $this->baseResolver->resolve($toResolve);\n return $resolved;\n } catch (\\Exception $e) {\n }\n\n $toResolveArr = explode(':', $toResolve);\n $class = $toResolveArr[0];\n $method = isset($toResolveArr[1]) ? $toResolveArr[1] : null;\n\n $instance = $this->container()->get('registry')->load($class);\n return ($method) ? [$instance, $method] : $instance;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914197,"cells":{"blob_id":{"kind":"string","value":"0187e9344bfe37285930b758eb4d9b0e052d39f1"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"DamienKusters/wbsMonitor"},"path":{"kind":"string","value":"/functions/removeProject.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":287,"string":"287"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\" . mysqli_error($conn);\r\n}\r\nmysqli_close($conn);\r\n?>\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914198,"cells":{"blob_id":{"kind":"string","value":"d805a65f6877fc03a2848a40cc4908fb140a3074"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"DMPR-dev/woocommerce-2plus1"},"path":{"kind":"string","value":"/wc_2plus1action/wc_2plus1action.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2643,"string":"2,643"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"initHooks();\n\t}\n\t/*\n\t\tInits needed hook(s)\n\t*/\n\tprotected function initHooks()\n\t{\n\t\tadd_action('woocommerce_before_calculate_totals',array($this,\"setThirdItemAsFree\"),10,1);\n\t}\n\t/*\n\t\tThis method is attached to 'woocommerce_before_calculate_totals' hook\n\n\t\t@param $cart - an object of current cart that is being processed\n\n\t\t@returns VOID\n\t*/\n\tpublic function setThirdItemAsFree($cart)\n\t{\n\t\t/*\n\t\t\tKeep free items refreshed everytime cart gets updated\n\t\t*/\n\t\t$this->cleanCart($cart);\n\t\tif ($cart->cart_contents_count > 2)\n\t\t{\n\t\t\t/*\n\t\t\t\tDetect the cheapest product on cart\n\t\t\t*/\n\t\t\t$cheapest_product_id = Getters::getCheapestProduct($cart,array(\"return\" => \"ID\"));\n\n\t\t\tif($cheapest_product_id === FALSE || intval($cheapest_product_id) < 0) return;\n\t\t\t/*\n\t\t\t\tMake one of the cheapest items free \n\n\t\t\t\t@returns the original item quantity decreased on 1\n\t\t\t*/\n\t\t\t$this->addFreeItem($cart);\n\t\t}\n\t}\n\t/*\n\t\tPrevents recursion because adding a new item to cart will cause hook call\n\n\t\t@param $cart - an object of cart\n\n\t\t@returns VOID\n\t*/\n\tprotected function addFreeItem($cart)\n\t{\n\t\tremove_action('woocommerce_before_calculate_totals',array($this,\"setThirdItemAsFree\"));\n\t\tFunctions::addAsUniqueFreeProductToCart($cart,Getters::getCheapestProduct($cart,array(\"return\" => \"object\")),\"0.00\");\n\t\tadd_action('woocommerce_before_calculate_totals',array($this,\"setThirdItemAsFree\"),10,1);\n\t}\n\t/*\n\t\tPrevents recursion because removing an item from cart will cause hook call\n\n\t\t@param $cart - an object of cart\n\n\t\t@returns VOID\n\t*/\n\tprotected function cleanCart($cart)\n\t{\n\t\tremove_action('woocommerce_before_calculate_totals',array($this,\"setThirdItemAsFree\"));\n\t\tFunctions::removeFreeItemsFromCart($cart);\n\t\tadd_action('woocommerce_before_calculate_totals',array($this,\"setThirdItemAsFree\"),10,1);\n\t}\n}\n\nnew Action();\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914199,"cells":{"blob_id":{"kind":"string","value":"b92975b84e42d13c5c6157470b829629195587ee"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"kerolesgeorge/php-products"},"path":{"kind":"string","value":"/product.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1621,"string":"1,621"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"readByID($product_id);\n}\n\n?>\n\n\n\n\n \n \n \n PHP Products Home Page\n \n \n \n\n\n
    \n\n
    \n\n
    \n
    \n\n \n \" class=\"card-img-top\" alt=\"Product Image\">\n
    \n
    \n
    Price:
    \n
    \n
    \n \n \n
    \n \n
    \n \n\n
    \n \n
    \n
    \n\n \n \n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":99141,"numItemsPerPage":100,"numTotalItems":9914478,"offset":9914100,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODMyMzA0NSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9waHAiLCJleHAiOjE3NTgzMjY2NDUsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.ss8pwPm3mN9iVcBIrz1ZOYbG4kgvruS6hJDiu16fJi0iRYHGAO3fGnBLdCnYlYwdDVndmW5TSmks4L0JeCY4DQ","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    blob_id
    stringlengths
    40
    40
    language
    stringclasses
    1 value
    repo_name
    stringlengths
    5
    116
    path
    stringlengths
    2
    241
    src_encoding
    stringclasses
    31 values
    length_bytes
    int64
    14
    3.6M
    score
    float64
    2.52
    5.13
    int_score
    int64
    3
    5
    detected_licenses
    listlengths
    0
    41
    license_type
    stringclasses
    2 values
    text
    stringlengths
    14
    3.57M
    download_success
    bool
    1 class
    7934343d96f97967578f1c0664ac0756880c03fb
    PHP
    PratikumWebDasar4101/tamimodul6-irfanfazri16
    /db2/register.php
    UTF-8
    1,877
    2.859375
    3
    []
    no_license
    <?php require_once("config.php"); if(isset($_POST['register'])){ $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); $password = password_hash($_POST["password"], PASSWORD_DEFAULT); $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); $sql = "INSERT INTO users (name, username, email, password) VALUES (:name, :username, :email, :password)"; $stmt = $db->prepare($sql); $params = array( ":name" => $name, ":username" => $username, ":password" => $password, ":email" => $email ); $saved = $stmt->execute($params); if($saved) header("Location: login.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> </head> <body > <form action="" method="POST"> <table> <tr><td><h1>Silahkan daftarkan diri anda</td></tr> <tr><td>Nama Lengkap <td><input type="text" name="name" placeholder="Nama kamu" /> <tr><td>Username <td><input type="text" name="username" placeholder="Username" /> <tr><td>Email <td><input type="email" name="email" placeholder="Alamat Email" /> <tr><td>Password <td><input type="password" name="password" placeholder="Password" /> <tr><td><input type="submit" name="register" value="Daftar" /> </form> </body> </html>
    true
    d1133eb02f7bafdce4f8d1a87d06ac2f270507fa
    PHP
    ytteroy/airtel.airshop
    /application/modules/cwservers/models/cwservers_model.php
    UTF-8
    4,386
    2.609375
    3
    []
    no_license
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Cwservers_model extends CI_Model { /** * Main variables */ public $table_structure = array(); public $sql_services_table = NULL; /** * Class constructor */ public function __construct() { parent::__construct(); // Loading database from config $this->load->database($this->config->item($this->module->active_module), FALSE, TRUE); // Load table structure $this->table_structure = $this->config->item($this->module->active_module.'_table_structure'); // Private actions initialization $this->individual_init(); } public function individual_init() { // Get name of services table $this->sql_services_table = $this->config->item('cwservers_sql_table'); } private function get_expired_servers($table_name) { $current_time = time(); $q = $this->db->where('expires <', $current_time) ->where('expires !=', 0) ->get($table_name); if($q->num_rows() > 0) { return $q->result(); } } public function clear_expired($table_name) { // Get all expired serverss $expired_servers = $this->get_expired_servers($table_name); // If there is at least one expired server if(count($expired_servers) > 0) { // Lets work with each expired server foreach($expired_servers as $server) { // Load SSH lib $settings = $this->module->services[$server->module]['ssh']; // Load ssh lib $this->load->library('core/ssh', $settings); // Do SSH command $this->ssh->execute('screen -X -S '.$server->module.'-'.$server->port.' kill'); // Set array with empty values $data = array( 'name' => '', 'server_rcon' => '', 'server_password' => '', 'expires' => 0, ); // Update server data $this->occupy_server($server->id, $server->module, $data); } } } public function get_available_servers($module) { $q = $this->db->where('expires', 0) ->where('module', $module) ->get($this->sql_services_table); if($q->num_rows() > 0) { return $q->result(); } } /** * Function gets occupied servers by internal active module * @return type */ public function get_occupied_servers() { $q = $this->db->where('expires >', 0) ->where('module', $this->module->active_service) ->get($this->sql_services_table); if($q->num_rows() > 0) { return $q->result(); } } /** * Function gets occupied servers by specified external service * @param type $service * @return type */ public function get_occupied_servers_external($service = 'hlds') { $q = $this->db->where('expires >', 0) ->where('module', $service) ->get($this->sql_services_table); if($q->num_rows() > 0) { return $q->result(); } } /** * Updates server row with new information. Function can be used also for clearing row. * @param type $server_id * @param type $module * @param type $data */ public function occupy_server($server_id, $module, $data = array()) { $this->db->where('id', $server_id) ->where('module', $module) ->update($this->sql_services_table, $data); } public function get_server($server_id) { $q = $this->db->where('id', $server_id) ->get($this->sql_services_table); if($q->num_rows() > 0) { return $q->row(); } } }
    true
    5167ae1bf1169e578e379c92bdb9ccd368504ca8
    PHP
    nwebcode/framework
    /src/Nweb/Framework/Application/Service/Locator.php
    UTF-8
    1,321
    2.546875
    3
    []
    no_license
    <?php /** * Nweb Framework * * @category NwebFramework * @package Application * @subpackage Service * @author Krzysztof Kardasz <[email protected]> * @copyright Copyright (c) 2013 Krzysztof Kardasz * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public * @version 0.1-dev * @link https://github.com/nwebcode/framework * @link http://framework.nweb.pl */ namespace Nweb\Framework\Application\Service; /** * Service Locator * * @category NwebFramework * @package Application * @subpackage Service * @author Krzysztof Kardasz <[email protected]> * @copyright Copyright (c) 2013 Krzysztof Kardasz * @version 0.1-dev */ class Locator { /** * @var array */ protected $services = array(); /** * @param string $name * @return bool */ public function has ($name) { return isset($this->services[$name]); } /** * @param string $name * @return object */ public function get ($name) { if (!isset($this->params[$name])) { $params = $this->params[$name]; } return $this->services[$name]; } /** * @param string $name * @param object $serviceObj */ public function set ($name, $serviceObj) { $this->services[$name] = $serviceObj; } }
    true
    c64bc66afa4af038a33afb8dd43ced6cff735d39
    PHP
    Raza448/thoughtbase
    /application/view_latest/vendor_only/allres_comment.php
    UTF-8
    912
    2.53125
    3
    []
    no_license
    <?php $sql ='select client_answes.id as kid,client_answes.comment,client_answes.client_id,client_answes.survey_id,client_answes.question_id, users.age,users.gender,users.zipcode from client_answes left join users on client_answes.client_id = users.id where client_answes.survey_id='.$survey.' and client_answes.question_id='.$question; $data_img = $this->db->query($sql)->result_array(); ?> <?php if(count($data_img ) > 0 ){ foreach($data_img as $row => $val ){ ?> <div> <?php echo $val['comment']; ?> <h6><i class="fa fa-star"></i>Age:<?php echo $val['age']; ?> <i class="fa fa-star"></i>Gender:<?php echo $val['gender']; ?> <i class="fa fa-star"></i>Zip:<?php echo $val['zipcode']; ?> </h6> </div> <br /> <?php }}else{ ?> <div> No Comments yet <h6 style="display:none;"><i class="fa fa-star"></i>Age:~ <i class="fa fa-star"></i>Gender:~ <i class="fa fa-star"></i>Zip:~ </h6> </div> <br /> <?php } ?>
    true
    94aa2264fb2d4fbcf81c4eaed146b2016763f17b
    PHP
    id0612/openapi-sdk-php
    /src/Cms/V20180308/GetMonitoringTemplate.php
    UTF-8
    1,435
    2.65625
    3
    [ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
    permissive
    <?php namespace AlibabaCloud\Cms\V20180308; use AlibabaCloud\Client\Request\RpcRequest; /** * Request of GetMonitoringTemplate * * @method string getName() * @method string getId() */ class GetMonitoringTemplate extends RpcRequest { /** * @var string */ public $product = 'Cms'; /** * @var string */ public $version = '2018-03-08'; /** * @var string */ public $action = 'GetMonitoringTemplate'; /** * @var string */ public $method = 'POST'; /** * @deprecated deprecated since version 2.0, Use withName() instead. * * @param string $name * * @return $this */ public function setName($name) { return $this->withName($name); } /** * @param string $name * * @return $this */ public function withName($name) { $this->data['Name'] = $name; $this->options['query']['Name'] = $name; return $this; } /** * @deprecated deprecated since version 2.0, Use withId() instead. * * @param string $id * * @return $this */ public function setId($id) { return $this->withId($id); } /** * @param string $id * * @return $this */ public function withId($id) { $this->data['Id'] = $id; $this->options['query']['Id'] = $id; return $this; } }
    true
    4fc011f0184c787bbdac7410df64c1e396470eb7
    PHP
    kernvalley/needs-api
    /roles/index.php
    UTF-8
    679
    2.59375
    3
    [ "MIT" ]
    permissive
    <?php namespace Roles; use \shgysk8zer0\PHPAPI\{PDO, API, Headers, HTTPException}; use \shgysk8zer0\PHPAPI\Abstracts\{HTTPStatusCodes as HTTP}; use \shgysk8zer0\{Role}; require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'autoloader.php'; try { $api = new API('*'); $api->on('GET', function(API $req): void { if ($roles = Role::fetchAll(PDO::load())) { Headers::contentType('application/json'); echo json_encode($roles); } else { throw new HTTPException('Error fetching roles', HTTP::INTERNAL_SERVER_ERROR); } }); $api(); } catch (HTTPException $e) { Headers::status($e->getCode()); Headers::contentType('application/json'); echo json_encode($e); }
    true
    1ea0afcddce9ffde9274b324d172296f4a719f62
    PHP
    DeDoOozZz/brighterycms
    /source/brightery/core/Style.php
    UTF-8
    2,113
    2.703125
    3
    []
    no_license
    <?php /** * Management application styles and interfaces * @package Brightery CMS * @version 1.0 * @property object $instance Codeigniter instance * @property string $interface User Interface name * @property string $styleName Style name * @property string $styleAssets Style assets path * @property string $stylePath Style path * @property string $styleUri Style URI * @property string $styleDirection Style Direction * @author Muhammad El-Saeed <[email protected]> * */ class Style { private $instance; private $interface; private $styleName; private $styleAssets; private $styleUri; private $styleDirection; public $stylePath; public function __construct() { Log::set('Initialize Style class'); $this->instance = & Brightery::SuperInstance(); $this->initialize(); } private function initialize() { $this->interface = $this->instance->Twig->interface; $this->styleName = $this->instance->Twig->styleName; $this->styleDirection = $this->instance->language->getLanguageDirection(); $this->stylePath = ROOT . '/styles/' . $this->interface . '/' . $this->styleName; $this->styleUri = BASE_URL . 'styles/' . $this->interface . '/' . $this->styleName; if (!is_dir($this->stylePath)) Brightery::error_message($this->stylePath . " is missed."); $this->parsing(); $this->createStyleConstants(); } private function parsing() { $style_ini = $this->stylePath . '/style.ini'; if (!file_exists($style_ini)) Brightery::error_message($style_ini . " is missed."); $this->styleAssets = parse_ini_file($style_ini, true); } private function createStyleConstants() { $settings = $this->styleAssets[$this->styleDirection]; define('STYLE_IMAGES', $this->styleUri . '/assets/' . $settings['images']); define('STYLE_JS', $this->styleUri . '/assets/' . $settings['js']); define('STYLE_CSS', $this->styleUri . '/assets/' . $settings['css']); define('MODULE_URL', BASE_URL . 'source/app/modules/'); } }
    true
    506a18bd0dd3aa08eac41a157877680f69cfaa83
    PHP
    didembilgihan/Bookmark-Management-System
    /register.php
    UTF-8
    679
    2.734375
    3
    [ "MIT" ]
    permissive
    <?php if ( $_SERVER["REQUEST_METHOD"] == "POST") { // var_dump($_POST) ; require "db.php" ; extract($_POST) ; try { // Validate email, name and password $sql = "insert into user ( name, email, password) values (?,?,?)" ; $stmt = $db->prepare($sql); $hash_password = password_hash($password, PASSWORD_DEFAULT) ; $stmt->execute([$name, $email, $hash_password]); addMessage("Registered"); header("Location: ?page=loginForm") ; exit ; } catch(PDOException $ex) { addMessage("Insert Failed!") ; header("Location: ?page=registerForm"); exit; } }
    true
    24fac03e9a4d620c1c8575f84ec56252fc424fc1
    PHP
    jwmcpeak/TutsPlus-PHP-Design-Patterns
    /chain-of-responsibility.php
    UTF-8
    1,907
    3.5625
    4
    []
    no_license
    <?php // chain of handlers // request abstract class LogType { const Information = 0; const Debug = 1; const Error = 2; } abstract class AbstractLog { protected $level; private $nextLogger = null; public function setNext(AbstractLog $logger) { $this->nextLogger = $logger; } public function log(int $level, string $message) { if ($this->level <= $level) { $this->write("$message\n"); } if ($this->nextLogger != null) { $this->nextLogger->log($level, $message); } } protected abstract function write(string $message); } class ConsoleLog extends AbstractLog { public function __construct(int $logLevel) { $this->level = $logLevel; } protected function write(string $message) { echo "CONSOLE: $message"; } } class FileLog extends AbstractLog { public function __construct(int $logLevel) { $this->level = $logLevel; } protected function write(string $message) { echo "FILE: $message"; } } class EventLog extends AbstractLog { public function __construct(int $logLevel) { $this->level = $logLevel; } protected function write(string $message) { echo "EVENT: $message"; } } class AppLog { private $logChain; public function __construct() { $console = new ConsoleLog(LogType::Information); $debug = new FileLog(LogType::Debug); $error = new EventLog(LogType::Error); $console->setNext($debug); $debug->setNext($error); $this->logChain = $console; } public function log(int $level, string $message) { $this->logChain->log($level, $message); } } $app = new AppLog(); $app->log(LogType::Information, "This is information."); $app->log(LogType::Debug, "This is debug."); $app->log(LogType::Error, "This is error.");
    true
    cc0de231c8619e429820f088d5833fd27b91758c
    PHP
    gungungggun/workspace
    /collatz-problem/php.php
    UTF-8
    391
    3.65625
    4
    []
    no_license
    <?php $t = microtime(true); $count = 0; for ($i = 2; $i <= 10000; $i++) { $x = $i; while ($x != 1) { if ($x % 2 == 0) { $x = a($x); } else { $x = b($x); } $count++; } } echo '処理時間' . (microtime(true) - $t); echo "\n"; echo 'count:' . $count; function a ($n) { return $n / 2; } function b ($n) { return $n * 3 + 1; }
    true
    92803af814f4d592e219db466a90c528d1ae06af
    PHP
    aliliin/thinkPhp51
    /extend/ObjArray.php
    UTF-8
    905
    3.453125
    3
    [ "Apache-2.0" ]
    permissive
    <?php // ArrayAccess(数组式访问)接口 // 提供像访问数组一样访问对象的能力的接口。 class ObjArray implements \ArrayAccess { private $container = ['title' => 'Aliliin']; // 设置一个偏移位置的值 public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } // 检查一个偏移位置是否存在 public function offsetExists($offset) { return isset($this->container[$offset]); } // 复位一个偏移位置的值 public function offsetUnset($offset) { unset($this->container[$offset]); } // 获取一个偏移位置的值 public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } }
    true
    542288972f173c2f99f6a4ea0a15c1cf85f82e56
    PHP
    crow1796/rev-cms
    /RevCMS/src/Http/Controllers/PagesController.php
    UTF-8
    2,220
    2.703125
    3
    [ "MIT" ]
    permissive
    <?php namespace RevCMS\Http\Controllers; use Illuminate\Http\Request; use RevCMS\Http\Controllers\RevBaseController; use RevCMS\Modules\Cms\Wrapper\Page; class PagesController extends RevBaseController { public function index(){ $this->menuOrder = 2; return $this->makeView('revcms.pages.index', 'Pages'); } /** * Create new page. * @param Request $request * @return mixed */ public function store(Request $request){ $this->checkAjaxRequest($request); $page = $this->rev ->cms() ->createPage($request->all()); if(!$page instanceof Page) { // If page is not equal to false/null, then return all errors with a failed status, else return failed return $page ? $page->errors()->all() + ['status' => false] : [0 => 'Something went wrong. Please make sure that the permalink is unique.','status' => false]; } $response = ['status' => true]; return $response; } public function create(){ $this->menuOrder = 2; return $this->makeView('revcms.pages.create', 'New Page'); } public function edit($id){ dd($id); } /** * Retreive all pages. * @param Request $request * @return array */ public function allPages(Request $request){ $this->checkAjaxRequest($request); return $this->rev ->cms() ->getPageArray(); } /** * Populate controllers and layouts fields. * @param Request $request * @return array */ public function populateFields(Request $request){ $fieldValues = [ 'controllers' => $this->rev->mvc()->allControllers(), 'layouts' => $this->rev->cms()->getActiveThemesLayouts(), ]; return $fieldValues; } /** * Generate slug and action name based on page's title. * @param Request $request * @return array */ public function generateFields(Request $request){ $this->checkAjaxRequest($request); return $this->rev ->cms() ->generateFieldsFor($request->page_title); } }
    true
    a8967ab776debe04d03cc200d88f94469ecb16c6
    PHP
    mobilejazz-contrib/yii2-api
    /app/frontend/models/PasswordResetRequestForm.php
    UTF-8
    1,520
    2.609375
    3
    [ "BSD-3-Clause", "MIT" ]
    permissive
    <?php namespace frontend\models; use common\models\User; use yii\base\Model; /** * Password reset request form */ class PasswordResetRequestForm extends Model { public $email; /** * @inheritdoc */ public function rules () { return [ ['email', 'filter', 'filter' => 'trim'], ['email', 'required'], ['email', 'email'], ['email', 'exist', 'targetClass' => '\common\models\User', 'filter' => ['status' => User::STATUS_ACTIVE], 'message' => 'There is no user with such email.' ], ]; } /** * Sends an email with a link, for resetting the password. * * @return boolean whether the email was send */ public function sendEmail () { /* @var $user User */ $user = User::findOne ([ 'status' => User::STATUS_ACTIVE, 'email' => $this->email, ]); if ($user) { if (!User::isPasswordResetTokenValid ($user->password_reset_token)) { $user->generatePasswordResetToken (); } if ($user->save ()) { $data = [ 'name' => $user->name, 'url' => \Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password','token'=>$user->password_reset_token]) ]; return \Yii::$app->mailer ->compose ('recover-password-'.\Yii::$app->language, $data) ->setGlobalMergeVars ($data) ->setTo ($this->email) ->setSubject (\Yii::t('app','Password reset request')) ->enableAsync () ->send (); } } return false; } }
    true
    6e3ebe6c5d9ea851939dcca52c43e0ade43ce04d
    PHP
    cddsky2014/121
    /php20160504/array_keys.php
    UTF-8
    228
    2.828125
    3
    []
    no_license
    <?php $arr1 = array(1,2,3,"name"=>"lucy","age"=>23,"addr"=>"USA"); print_r($arr1); print_r(array_keys($arr1)); function uarray_keys($a){ $arr = array(); foreach($a as $k=>$v){ $arr[]=$k; } return $arr; } ?>
    true
    5a3e69b98671dc9a55dc4728743fdf5efb07e72f
    PHP
    medV3dkO/bootcamp
    /admin/login.php
    UTF-8
    4,199
    2.53125
    3
    []
    no_license
    <?php if ($_POST['login']!='' && $_POST['pass']!=''){//проверяем что поля не пустые if (strlen($_POST['login'])<=30 && strlen ($_POST['pass'])<= 30){//проверяем чтоб логин и пароль был меньше 30 символов $login = htmlspecialchars($_POST['login']);//убираем спецсимволы $pass = htmlspecialchars($_POST['pass']);//убираем спецсимволы $login = mysql_real_escape_string($login);//еще одна экранизация $pass = mysql_real_escape_string($pass);//еще одна экранизация } } if ($_POST['login']=='' || $_POST['password']=='') echo '<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Авторизация | BOOTCAMP</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mini.css/3.0.1/mini-default.css"> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-3"></div> <div class="col-sm-6"> <br> <form id="form" method="post" action="login"> <fieldset> <legend>Авторизуйтесь</legend> <div class="row"> <div class="col-sm-12 col-md-6"> <label for="user">Логин</label> <input type="text" id="login" name="login" placeholder="Имя пользователя"> </div> <div class="col-sm-12 col-md-6"> <label for="password">Пароль</label> <input type="password" id="password" name="password" placeholder="Пароль"> </div> </div> <div class="row"> <mark id="error" class="inline-block secondary hidden" style="margin: 10px 0 10px 8px;">Текст ошибки</mark> </div> <div class="row"> <input type="submit" id="button" value="Войти"> </div> </fieldset> </form> </div> <div class="col-sm-3"></div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </body> </html>'; else{ //вот так данные можно отправлять без проверки вовсе, ни чего очень плохого случиться не должно. //PDO все заэкранирует и превратит в текст. //Можно разве что проверять длинну текста и какие то специфическиие данные $sql = "SELECT * FROM admin_users WHERE login=:login AND password=:pass";//Формируем запрос без данных $result = $pdo->prepare($sql); $result->bindvalue(':login', $_POST['login']); //Заполняем данные $result->bindvalue(':pass', md5($_POST['password'])); //Заполняем данные. Пароли хранить в открытом виде, дело такое. Поэтому двойной md5) $result->execute( ); //Выполняем запросы $result = $result->fetchAll(); //переводим обьект ПДО в массив данных, для удобной работы if (count($result)>0) {//Если база вернула 1 значение, значит и логин и пароль совпали. отлично echo 'Ура! Мы авторизировались! Перенаправляем в панель...'; $_SESSION['user'] = $result[0];//сохраняем обьект пользователя в сессии header("refresh: 3; url=https://medv3dko.xyz/admin/"); }else echo '<meta charset="UTF-8"><mark id="error" class="inline-block secondary hidden" style="margin: 10px 0 10px 8px;">Логин или пароль не верный или пользователь не существует.</mark> <a href="https://medv3dko.xyz/admin/">Попробовать ещё раз</a>'; } ?>
    true
    02acd4cbae8054282c69b34610987f6f6d578348
    PHP
    amsify42/php-domfinder
    /tests/TestXML.php
    UTF-8
    531
    2.78125
    3
    [ "MIT" ]
    permissive
    <?php namespace Amsify42\Tests; use Amsify42\DOMFinder\DOMFinder; class TestXML { private $domFinder; function __construct() { $this->domFinder = new DOMFinder(getSample('books.xml')); } public function process() { $books = $this->domFinder->getElements('book'); if($books->length) { foreach($books as $book) { echo $this->domFinder->getHtml($book); } } echo "\n\n"; $book = $this->domFinder->find('book')->byId('bk101')->first(); if($book) { echo $this->domFinder->getHtml($book); } } }
    true
    c826aef2b0721c6bd99c9f626c20cefb41d94848
    PHP
    chris-peng-1244/otc-cms
    /app/Services/Repositories/Customer/CustomerRepository.php
    UTF-8
    1,017
    2.8125
    3
    []
    no_license
    <?php namespace OtcCms\Services\Repositories\Customer; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Database\Eloquent\Collection; use OtcCms\Models\Customer; class CustomerRepository implements CustomerRepositoryInterface { /** * @param string $customerName * @param array $columns * @return Collection */ public function searchByName($customerName, $columns = ['*']) { return Customer::where('nickname', 'like', "%$customerName%") ->get(); } /** * @param int $limit * @return Paginator */ public function paginate($limit) { return Customer::paginate($limit); } /** * @param string $query * @return Collection */ public function searchByNameOrId($query) { if (is_numeric($query)) { $customer = Customer::find((int) $query); return $customer ? collect($customer) : collect([]); } return $this->searchByName($query); } }
    true
    f3304a721fa0d0a3a94a8fbe60a86450aa257624
    PHP
    kuljitsingh94/HTMLParse
    /studyGuideGen.php
    UTF-8
    3,527
    3.328125
    3
    []
    no_license
    <?php #give the script the URL to scrape $URLbegin= "https://cs.csubak.edu/~clei/teaching/files/S19_3500/hw"; $URLend = "s.html"; #function that returns an array populated with everything #in between the parameters tag_open and tag_close function tag_contents($string, $tag_open, $tag_close){ foreach (explode($tag_open, $string) as $key => $value) { if(strpos($value, $tag_close) !== FALSE){ $result[] = trim(substr($value, 0, strpos($value, $tag_close))); } } return $result; } $output = fopen('./output.txt','w'); for($hwNum = 1; $hwNum <= 5; $hwNum++) { if($hwNum < 10) $URL = $URLbegin."0".$hwNum.$URLend; else $URL = $URLbegin.$hwNum.$URLend; #download HTML from URL and save as a string $file = file_get_contents($URL); #get the number of questions from the num_quests variable #in the HTML/JavaScript $NUM_QUESTIONS = tag_contents($file, "num_quests =",";"); #save as an integer since tag_contents returns strings #also look at subscript 1 since subscript 0 is garbage $NUM_QUESTIONS = trim($NUM_QUESTIONS[1])+0; #remove all head tag info, leaving just the body #which is all we want $body = substr($file,strpos($file, "<pre class=verbatim>")); #get all comparison expressions since this is where #the answers are located $parsed= tag_contents($body, 'if (', ')'); $questions= tag_contents($body, '<pre class=verbatim>', '</pre>'); array_unshift($questions, "placeholder"); //var_dump($questions); $answers = array(); $i = 0; #all string parsing below requires knowledge of the #structure of the #downloaded HTML and requires pattern recognition #traverse array full of comparison expressions foreach($parsed as $key){ #break the comparison expressions into separate #variables, delimited by && $ifStatment = explode("&&",$key); #this checks if the if statement we grabbed #pertains to answers or something else if(!strpos($key,"hwkform")) { continue; } #if previous if statement fails, we have an #answer if statement $i++; #traverse each comparison expression foreach($ifStatment as $value){ #remove whitespace $value = trim($value); #! tells us its a wrong answer, so #if the ! is not there, meaning its a #right answer if($value[0]!='!'){ #grab the value of right answers,0123 $answer = tag_contents($value, '[',']'); #output formatting, convert 0123 -> ABCD #by ascii value usage if(isset($answers[$i])) $answers[$i].=','.chr($answer[0]+65); else $answers[$i]=chr($answer[0]+65); } } } #error checking, if NUM_QUESTIONS != i then we #got an extra if statement comparison expression if($i!=$NUM_QUESTIONS) { echo "\n\n\tERROR PARSING HTML! DOUBLE CHECK ANSWERS!!\n\n\n"; } echo "\tGenerating Study Guide Output File for $hwNum\n"; #output questions and answers //var_dump($answers); #write to output file for($i = 1; $i<=$NUM_QUESTIONS ; $i++) { fwrite($output, $questions[$i]."<split>".$answers[$i].'<endofquestion>'); } foreach($answers as $question => $ans) { //usleep(0250000); echo "Question $question\t: $ans\n"; } } ?>
    true
    0ea15d126f06d7a3274cdd342b8f1c98a70630c8
    PHP
    jeyroik/extas-q-crawlers-jira
    /src/components/quality/crawlers/jira/JiraIssueChangelogItem.php
    UTF-8
    762
    2.734375
    3
    [ "MIT" ]
    permissive
    <?php namespace extas\components\quality\crawlers\jira; use extas\components\Item; use extas\interfaces\quality\crawlers\jira\IJiraIssueChangelogItem; /** * Class JiraIssueChangelogItem * * @package extas\components\quality\crawlers\jira * @author [email protected] */ class JiraIssueChangelogItem extends Item implements IJiraIssueChangelogItem { /** * @param bool $asTimestamp * * @return false|int|string */ public function getCreated(bool $asTimestamp) { $created = $this->config[static::FIELD__CREATED] ?? ''; return $asTimestamp ? strtotime($created) : $created; } /** * @return string */ protected function getSubjectForExtension(): string { return static::SUBJECT; } }
    true
    1a150ec40f4d58b1d254c01c7345271e475296e9
    PHP
    LaunaKay/codingdojoserver
    /WishList/application/models/M_Wish.php
    UTF-8
    666
    2.625
    3
    [ "MIT" ]
    permissive
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class M_Wish extends CI_Model { public function __construct() { parent::__construct(); } public function addwish($wish) { $id = $this->session->userdata('id'); $wish = array ( 'item' => $wish['item'], 'user_id' => $id['id'] ); $this->db->insert('wishes', $wish); } public function removewish($wishID) { $this->db->where('id', $wishID); $this->db->delete('wishes'); $this->db->where('item_id', $wishID); $this->db->delete('wishlists'); } }
    true
    5ad38c6f4a2be085bef4680975cea39668b6d4b3
    PHP
    lazyman00/ajsas
    /pages/Front_end/allarticle/send_email_1.php
    UTF-8
    4,324
    2.578125
    3
    []
    no_license
    <?php include('../../../connect/connect.php'); ?> <?php require("../../../phpmailer/PHPMailerAutoload.php");?> <?php header('Content-Type: text/html; charset=utf-8'); $sql_article = sprintf("SELECT * FROM `article` left join type_article on article.type_article_id = type_article.type_article_id WHERE `article_id` = %s",GetSQLValueString($_POST['article_id'], 'int')); $query_article = $conn->query($sql_article); $row_article = $query_article->fetch_assoc(); for($i=0; $i<count($_POST['user_id']); $i++){ if($_POST['user_id'][$i]!=""){ $sql = sprintf("SELECT user.name_en, user.surname_en, pre.pre_en_short FROM `user` left join pre on user.pre_id = pre.pre_id WHERE `user`.`user_id` = %s ",GetSQLValueString($_POST['user_id'][$i], 'text')); $query = $conn->query($sql); $row = $query->fetch_assoc(); // echo "<pre>"; // print_r($_POST); // echo "</pre>"; // exit(); $mail = new PHPMailer; $mail->CharSet = "utf-8"; $mail->isSMTP(); // $mail->Debugoutput = 'html'; $mail->Host = 'smtp.gmail.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $gmail_username = "[email protected]"; // gmail ที่ใช้ส่ง $gmail_password = "SunandMoon00"; // รหัสผ่าน gmail // ตั้งค่าอนุญาตการใช้งานได้ที่นี่ https://myaccount.google.com/lesssecureapps?pli=1 $sender = "Article Review Request [AJSAS]"; // ชื่อผู้ส่ง $email_sender = "[email protected]"; // เมล์ผู้ส่ง $email_receiver = $_POST["email"][$i]; // เมล์ผู้รับ *** // $email_receiver = "[email protected]"; $subject = "จดหมายเทียบเชิญผู้ทรงคุณวุฒิ"; // หัวข้อเมล์ $mail->Username = $gmail_username; $mail->Password = $gmail_password; $mail->setFrom($email_sender, $sender); $mail->addAddress($email_receiver); $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); $mail->Subject = $subject; // $mail->SMTPDebug = 1; $email_content = "<!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <title>Document</title> </head> <body> <p><b>Dear ".$row['pre_en_short']." ".$row['name_en']." ".$row['surname_en']."</b></p> <p style='text-indent: 50px;' >I believe that you would serve as an excellent reviewer of the manuscript, ".$row_article['article_name_en']." </p> <p>which has been submitted to Academic Journal of Science and Applied Science. The submission's abstract is</p> <p>inserted below, and I hope that you will consider undertaking this important task for us.</p> <p style='text-indent: 50px;'>Please log into the journal web site by ".$row_article['date_article']." to indicate whether you will undertake the</p> <p>review or not, as well as to access the submission and to record your review and recommendation. After this job</p> <p>is done, you will receive a THB 1,000 cash prize.</p> <p style='text-indent: 50px;'>The review itself is due ".$row_article['date_article'].".</p> <p style='text-indent: 50px;'>Submission URL: <a href='http://localhost/ajsas/rechack_email.php?u=".$_POST['user_id'][$i]."&e=".$row_article['article_name_en']."&t=".$row_article['article_name_th']."&i=".$row_article['article_id']."&sm=".$_POST['id_sendMail']."'>>> ระบบวารสารวิชาการวิทยาศาสตร์และวิทยาศาสตร์ประยุกต์ <<</a></p> <br/> <p>Assoc. Prof. Dr. Issara Inchan </p> <p>Faculty of Science and Technology, Uttaradit Rajabhat University.</p> <p>[email protected] </p> <br/> <p>".$row_article['article_name_en']." </p> <p>".$row_article['abstract_en']."</p> <p>................. </p> </body> </html>"; // ถ้ามี email ผู้รับ if($email_receiver){ $mail->msgHTML($email_content); if ($mail->send()) { $sql = sprintf("INSERT INTO `tb_sendmail`(`id_sendMail`, `user_id`, `article_id`) VALUES (%s,%s,%s)", GetSQLValueString($_POST['id_sendMail'],'text'), GetSQLValueString($_POST['user_id'][$i],'text'), GetSQLValueString($row_article['article_id'],'text')); $query = $conn->query($sql); } } $mail->smtpClose(); } } // echo "ระบบได้ส่งข้อความไปเรียบร้อย"; ?>
    true
    dd89c7c961bdf80d129c570cdcd9b8654e59cc31
    PHP
    crebiz76/phptest
    /ch19/quiz_result.php
    UTF-8
    2,004
    3.140625
    3
    []
    no_license
    <?php $ans = array($_REQUEST['ex1'], $_REQUEST['ex2'], $_REQUEST['ex3']); require_once('MyDB.php'); $pdo = db_connect(); ?> <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>퀴즈 응시 결과</title> </head> <body> <h2>퀴즈 응시 결과</h2> <?php try{ $sql = "select * from quiz"; $stmh = $pdo->query($sql); $count = $stmh->rowCount(); } catch (PDOException $Exception){ print "오류 :".$Exception->getMessage(); } $i = 0; $score = 0; while($row=$stmh->fetch(PDO::FETCH_ASSOC)){ if($ans[$i] == $row['dap']) { $score++; $correct[$i] = 'O'; } else { $correct[$i] = 'X'; } $i++; } $result = ''; switch($score) { case 0: case 1: $result = '미흡'; break; case 2: $result = '보통'; break; case 3: $result = '우수'; break; } ?> <p>판정: <?=$result?></p> <table border="1"> <tr> <td width="100" align="center">순번</td> <td width="100" align="center">선택</td> <td width="100" align="center">정답</td> <td width="100" align="center">결과</td> </tr> <?php try{ $sql = "select * from quiz"; $stmh = $pdo->query($sql); $count = $stmh->rowCount(); } catch (PDOException $Exception){ print "오류 :".$Exception->getMessage(); } $j = 0; while($row=$stmh->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <td width="100" align="center"><?=$row['id']?></td> <td width="100" align="center"><?=$ans[$j]?></td> <td width="100" align="center"><?=$row['dap']?></td> <td width="100" align="center"><?=$correct[$j]?></td> </tr> <?php $j++; } ?> </table> </body> </html>
    true
    175bc2a392f215181f29fe73a3201dc91e41b1e4
    PHP
    boukeversteegh/DecoratorModule
    /test/src/Fixtures/Library/lendableTrait.php
    UTF-8
    246
    2.640625
    3
    []
    no_license
    <?php namespace Fixtures\Library; trait lendableTrait { protected $lending_user; public function lendTo(\Fixtures\Entity\User $user) { $this->lending_user = $user; } public function getLendingTo() { return $this->lending_user; } }
    true
    92600040e18121fbbe05ee90c35734a72af4e6c2
    PHP
    walterra/J4p5Bundle
    /j4p5/parse/easy_parser.php
    UTF-8
    841
    2.53125
    3
    []
    no_license
    <?php namespace Walterra\J4p5Bundle\j4p5\parse; use \Walterra\J4p5Bundle\j4p5\parse\parser; use \Walterra\J4p5Bundle\j4p5\jsly; class easy_parser extends parser { function __construct($pda, $strategy = null) { parent::__construct($pda); $this->call = $this->action; //array(); $this->strategy = ($strategy ? $strategy : new default_parser_strategy()); /* foreach($this->action as $k => $body) { $this->call[$k] = create_function( '$tokens', preg_replace('/{(\d+)}/', '$tokens[\\1]', $body)); } */ } function reduce($action, $tokens) { $call = $this->call[$action]; return jsly::$call($tokens); } function parse($symbol, $lex, $strategy = null) { return parent::parse($symbol, $lex, $this->strategy); } } ?>
    true
    053035df4f0eb6ebbf8b2f9204d0cf2bdfd3653b
    PHP
    HouraiSyuto/php_practice
    /part2/chapter5/reference_array.php
    UTF-8
    342
    3.65625
    4
    []
    no_license
    <?php function array_pass($array){ $array[0] *= 2; $array[1] *= 2; } function array_pass_ref(&$array){ $array[0] *= 2; $array[1] *= 2; } $a = 10; $b = 20; $array = array($a, $b); array_pass_ref($array); echo $a, PHP_EOL; echo $b, PHP_EOL; $array = array($a, &$b); array_pass($array); echo $a, PHP_EOL; echo $b, PHP_EOL;
    true
    1bb4215e1ae1605c17f0d163193ac2f293ae40c5
    PHP
    DeschampsManon/Facebook_app
    /task.php
    UTF-8
    4,908
    2.59375
    3
    []
    no_license
    <?php require __DIR__.'/loaders/dependencies.php'; require __DIR__.'/loaders/classLoader.php'; require __DIR__.'/loaders/bdd.php'; require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php'; // On stock la variable fb (api facebook) dans une variable statique MyController::$fb = new Facebook\Facebook([ 'app_id' => '325674481145757', 'app_secret' => '', 'default_graph_version' => 'v2.8', ]); MyController::$fb->setDefaultAccessToken('325674481145757|'); // On demande une instance sur la class ApiController qui permet de lancer une requette à l'API Facebook $api = ApiController::getInstance(); function array_sort($array, $on, $order=SORT_DESC) { $new_array = array(); $sortable_array = array(); if (count($array) > 0) { foreach ($array as $k => $v) { if (is_array($v)) { foreach ($v as $k2 => $v2) { if ($k2 == $on) { $sortable_array[$k] = $v2; } } } else { $sortable_array[$k] = $v; } } switch ($order) { case SORT_ASC: asort($sortable_array); break; case SORT_DESC: arsort($sortable_array); break; } foreach ($sortable_array as $k => $v) { $new_array[$k] = $array[$k]; } } return $new_array; } // On regarde si un concours est terminé $request = MyController::$bdd->query('SELECT id_concours, end_date FROM concours WHERE status = 1'); $result = $request->fetch(PDO::FETCH_ASSOC); if(!empty($result['id_concours'])) { $concours = $result['id_concours']; $today = date('U'); $end = date('U', strtotime($result['end_date'])); if($result['end_date'] <= $today) { // On stoppe le concours s'il est terminé $request = MyController::$bdd->exec('UPDATE concours SET status = 0 WHERE status = 1'); $request = MyController::$bdd->exec('UPDATE users SET participation = 0'); /* GET LIKES */ $resultats = array(); $count = 0; $request = MyController::$bdd->query('SELECT * FROM photos WHERE id_concours = '. $concours); $result = $request->fetchAll(PDO::FETCH_ASSOC); foreach ($result as $photo) { $likes = $api->getRequest($photo['link_like']); $countLikes = (isset($likes['share'])) ? $likes['share']['share_count'] : 0; $request = MyController::$bdd->query('SELECT first_name, name FROM users WHERE id_user = '. $photo['id_user']); $result = $request->fetch(PDO::FETCH_ASSOC); $resultats[$count]['user'] = $result['first_name'] . ' ' . $result['name']; $resultats[$count]['link_photo'] = $photo['link_photo']; $resultats[$count]['likes'] = $countLikes; $count++; } $resultats = array_sort($resultats, 'likes'); $data = array( 'message' => 'Découvrez ci-dessous la photo du gagnant du concours pardon maman !', 'link' => $resultats[0]['link_photo'] ); // On récupère les id de tous les utilisateurs $request = MyController::$bdd->query('SELECT id_user FROM users'); $result = $request->fetchAll(PDO::FETCH_ASSOC); foreach($result as $id) { $api->postRequest('/'.$id['id_user'].'/feed', $data); } // Send mail to admin $accounts = $api->getRequest('/app/roles', '325674481145757|2_coNBtFEJH6uQenqtAHJCLBcaY'); foreach ($accounts['data'] as $key => $account) { if($account['role'] == 'administrators') { $administrators[] = $account['user']; } } foreach ($administrators as $id) { $email = $api->getRequest('/'.$id.'?fields=email', '325674481145757|2_coNBtFEJH6uQenqtAHJCLBcaY'); $emails[] = $email['email']; } $body = ""; $body .= "<table border='1'>"; $body .= "<tr>"; $body .= "<th>User</th>"; $body .= "<th>link photo</th>"; $body .= "<th>likes</th>"; $body .= "</tr>"; foreach ($resultats as $resultat) { $body .= "<tr>"; $body .= "<td>".$resultat['user']."</td>"; $body .= "<td>".$resultat['link_photo']."</td>"; $body .= "<td>".$resultat['likes']."</td>"; $body .= "</tr>"; } $body .= "</table>"; foreach($emails as $email) { $mail = new PHPMailer; $mail->isHTML(true); $mail->setFrom('[email protected]', 'Concours Photo Pardon Maman'); $mail->addAddress($email); $mail->addReplyTo('[email protected]', 'Information'); $mail->Subject = 'Résultats du concours'; $mail->Body = $body; $mail->send(); } } }
    true
    7676e84c098398d2e87756aabc10b5c82ee4077f
    PHP
    nmusco/assuresign-sdk-php-v2
    /src/StructType/PingResult.php
    UTF-8
    1,265
    2.703125
    3
    []
    no_license
    <?php namespace Nmusco\AssureSign\v2\StructType; use \WsdlToPhp\PackageBase\AbstractStructBase; /** * This class stands for PingResult StructType * @subpackage Structs */ class PingResult extends AbstractStructBase { /** * The Success * Meta information extracted from the WSDL * - use: required * @var bool */ public $Success; /** * Constructor method for PingResult * @uses PingResult::setSuccess() * @param bool $success */ public function __construct($success = null) { $this ->setSuccess($success); } /** * Get Success value * @return bool */ public function getSuccess() { return $this->Success; } /** * Set Success value * @param bool $success * @return \Nmusco\AssureSign\v2\StructType\PingResult */ public function setSuccess($success = null) { // validation for constraint: boolean if (!is_null($success) && !is_bool($success)) { throw new \InvalidArgumentException(sprintf('Invalid value %s, please provide a bool, %s given', var_export($success, true), gettype($success)), __LINE__); } $this->Success = $success; return $this; } }
    true
    c0372bf6d73553f6f6227fe1bd7dcd8672049bd8
    PHP
    taufik-ashari/slightly-big-Flip
    /disburse/getById.php
    UTF-8
    1,259
    2.78125
    3
    []
    no_license
    <?php // required headers header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: access"); header("Access-Control-Allow-Methods: GET"); header("Access-Control-Allow-Credentials: true"); header('Content-Type: application/json'); // include database and object files include_once '../config/database.php'; include_once '../object/disburse.php'; // get database connection $database = new Database(); $db = $database->getConnection(); // prepare product object $disburse = new Disburse($db); // set ID property of record to read $disburse->id = isset($_GET['id']) ? $_GET['id'] : die(); // read the details of product to be edited $disburse->readOne(); if($disburse->id!=null){ // create array $disburses_arr = array( "id" => $disburse->id, "time_served" => $disburse->time_served, "receipt" => $disburse->receipt, "status" => $disburse->status ); // set response code - 200 OK http_response_code(200); // make it json format echo json_encode($disburses_arr); } else{ // set response code - 404 Not found http_response_code(404); // tell the user product does not exist echo json_encode(array("message" => "Disburse does not exist.")); } ?>
    true
    a3c53217dc2801449e58a72aab1e6d9ff4272f68
    PHP
    jamesjoel/tss_12_30
    /ravi/ci/application/views/admin/view_users.php
    UTF-8
    1,067
    2.53125
    3
    []
    no_license
    <div class="container mt-4 pt-3"> <div class="row"> <div class="col-md-10 offset-md-1"> <h2 class="text-center">View All User</h2> <table class="table table-dark table-hover table-bordered"> <tr> <th>S.No.</th> <th>Full Name</th> <th>Username</th> <th>Contact</th> <th>Status</th> <th>Change</th> </tr> <?php $n=1; foreach($result->result_array() as $data) { if($data['status']==1) $a = "Enable"; else $a = "Disable"; ?> <tr> <td><?php echo $n; ?></td> <td><?php echo $data['full_name']; ?></td> <td><?php echo $data['username']; ?></td> <td><?php echo $data['contact']; ?></td> <td><?php echo $a; ?></td> <td><a href="<?php echo site_url('admin/change_status/'.$data['id'].'/'.$data['status']) ?>" class="btn btn-sm btn-info">Change</a></td> </tr> <?php $n++; } ?> </table> </div> </div> </div>
    true
    511c2f3a8e3ce616bc2fa8763ba767747f310b92
    PHP
    ghuysmans/php-u2flib-server
    /examples/pdo/login.php
    UTF-8
    1,546
    2.71875
    3
    [ "BSD-3-Clause", "BSD-2-Clause" ]
    permissive
    <?php require_once('U2F_Login.php'); class L extends U2F_Login { protected function getUserId() { if (isset($_SESSION['user_id'])) return $_SESSION['user_id']; else return 0; } protected function plaintextLogin($username, $password) { $sel = $this->pdo->prepare('SELECT user_id FROM user WHERE user=?'); $sel->execute(array($username)); //FIXME $password return $sel->fetchColumn(0); } protected function login($user_id) { $_SESSION['user_id'] = $user_id; } } $pdo = new PDO('mysql:dbname=u2f', 'test', 'bonjour'); $login = new L($pdo); if (isset($_GET['force'])) { $_SESSION['user_id'] = $_GET['force']; header('Location: login.php'); } $login->route(); ?> <!DOCTYPE html> <html> <head> <title>PHP U2F example</title> <script src="../assets/u2f-api.js"></script> <script src="ajax.js"></script> <script src="login.js"></script> </head> <body> <pre> <?=print_r($_SESSION)?> </pre> <form onsubmit="return login(this)"> <p><label>User name: <input name="username" required></label></p> <!-- FIXME required --> <p><label>Password: <input name="password" type="password"></label></p> <p> <label>Register <input value="register" name="action" type="radio" required> <input name="comment" placeholder="device name"> <label>Authenticate: <input value="authenticate" name="action" type="radio"></p> <p><button type="submit">Submit!</button></p> </form> </body> </html>
    true
    66f48156e0cbdf7529838ce463fc6295fde2af12
    PHP
    HeleneBoivin/PHP_5_Les_tableaux
    /exercice1/index.php
    UTF-8
    537
    3.40625
    3
    []
    no_license
    <!DOCTYPE HTML> <html> <head> <title>Exercice1</title> <h3>PHP - Partie 5 - Exercice 1</h3> </head> <body> <p>Créer un tableau months et l'initialiser avec les mois de l'année<p> <?php // $months = array ('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'décembre'); $months = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'décembre']; // les crochets remplace "array" print_r($months); ?> </body> </html>
    true
    eba7dc0a8bd0a64a96bfc25112b8c15b634e7f43
    PHP
    salvoab/laravel-comics
    /database/seeds/AuthorSeeder.php
    UTF-8
    459
    2.859375
    3
    [ "MIT" ]
    permissive
    <?php use App\Author; use Illuminate\Database\Seeder; use Faker\Generator as Faker; class AuthorSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run(Faker $faker) { for ($i=0; $i < 10; $i++) { $author = new Author(); $author->name = $faker->firstName(); $author->lastname = $faker->lastName; $author->save(); } } }
    true
    c3941a123fc242017610c46abdec247cf902d342
    PHP
    loveorigami/shop_prototype
    /tests/widgets/AdminCreateSubcategoryWidgetTests.php
    UTF-8
    7,983
    2.671875
    3
    []
    no_license
    <?php namespace app\tests\widgets; use PHPUnit\Framework\TestCase; use app\widgets\AdminCreateSubcategoryWidget; use app\forms\AbstractBaseForm; /** * Тестирует класс AdminCreateSubcategoryWidget */ class AdminCreateSubcategoryWidgetTests extends TestCase { private $widget; public function setUp() { $this->widget = new AdminCreateSubcategoryWidget(); } /** * Тестирует свойства AdminCreateSubcategoryWidget */ public function testProperties() { $reflection = new \ReflectionClass(AdminCreateSubcategoryWidget::class); $this->assertTrue($reflection->hasProperty('form')); $this->assertTrue($reflection->hasProperty('categories')); $this->assertTrue($reflection->hasProperty('header')); $this->assertTrue($reflection->hasProperty('template')); } /** * Тестирует метод AdminCreateSubcategoryWidget::setForm */ public function testSetForm() { $form = new class() extends AbstractBaseForm {}; $this->widget->setForm($form); $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $result = $reflection->getValue($this->widget); $this->assertInstanceOf(AbstractBaseForm::class, $result); } /** * Тестирует метод AdminCreateSubcategoryWidget::setCategories */ public function testSetCategories() { $categories = [new class() {}]; $this->widget->setCategories($categories); $reflection = new \ReflectionProperty($this->widget, 'categories'); $reflection->setAccessible(true); $result = $reflection->getValue($this->widget); $this->assertInternalType('array', $result); } /** * Тестирует метод AdminCreateSubcategoryWidget::setHeader */ public function testSetHeader() { $header = 'Header'; $this->widget->setHeader($header); $reflection = new \ReflectionProperty($this->widget, 'header'); $reflection->setAccessible(true); $result = $reflection->getValue($this->widget); $this->assertInternalType('string', $result); } /** * Тестирует метод AdminCreateSubcategoryWidget::setTemplate */ public function testSetTemplate() { $template = 'Template'; $this->widget->setTemplate($template); $reflection = new \ReflectionProperty($this->widget, 'template'); $reflection->setAccessible(true); $result = $reflection->getValue($this->widget); $this->assertInternalType('string', $result); } /** * Тестирует метод AdminCreateSubcategoryWidget::run * если пуст AdminCreateSubcategoryWidget::form * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: form */ public function testRunEmptyForm() { $result = $this->widget->run(); } /** * Тестирует метод AdminCreateSubcategoryWidget::run * если пуст AdminCreateSubcategoryWidget::categories * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: categories */ public function testRunEmptyCategories() { $form = new class() extends AbstractBaseForm {}; $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $form); $result = $this->widget->run(); } /** * Тестирует метод AdminCreateSubcategoryWidget::run * если пуст AdminCreateSubcategoryWidget::header * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: header */ public function testRunEmptyHeader() { $mock = new class() {}; $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $mock); $reflection = new \ReflectionProperty($this->widget, 'categories'); $reflection->setAccessible(true); $reflection->setValue($this->widget, [$mock]); $result = $this->widget->run(); } /** * Тестирует метод AdminCreateSubcategoryWidget::run * если пуст AdminCreateSubcategoryWidget::template * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: template */ public function testRunEmptyTemplate() { $mock = new class() {}; $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $mock); $reflection = new \ReflectionProperty($this->widget, 'categories'); $reflection->setAccessible(true); $reflection->setValue($this->widget, [$mock]); $reflection = new \ReflectionProperty($this->widget, 'header'); $reflection->setAccessible(true); $reflection->setValue($this->widget, 'Header'); $result = $this->widget->run(); } /** * Тестирует метод AdminCreateSubcategoryWidget::run */ public function testRun() { $form = new class() extends AbstractBaseForm { public $name; public $seocode; public $id_category; public $active; }; $categories = [ new class() { public $id = 1; public $name = 'One'; }, new class() { public $id = 2; public $name = 'Two'; }, ]; $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $form); $reflection = new \ReflectionProperty($this->widget, 'categories'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $categories); $reflection = new \ReflectionProperty($this->widget, 'header'); $reflection->setAccessible(true); $reflection->setValue($this->widget, 'Header'); $reflection = new \ReflectionProperty($this->widget, 'template'); $reflection->setAccessible(true); $reflection->setValue($this->widget, 'admin-create-subcategory.twig'); $result = $this->widget->run(); $this->assertRegExp('#<p><strong>Header</strong></p>#', $result); $this->assertRegExp('#<form id="subcategory-create-form" action="..+" method="POST">#', $result); $this->assertRegExp('#<input type="text" id=".+" class="form-control" name=".+\[name\]">#', $result); $this->assertRegExp('#<select id=".+" class="form-control" name=".+\[id_category\]" data-disabled>#', $result); $this->assertRegExp('#<option value="0">------------------------</option>#', $result); $this->assertRegExp('#<option value="1">One</option>#', $result); $this->assertRegExp('#<option value="2">Two</option>#', $result); $this->assertRegExp('#<input type="text" id=".+" class="form-control" name=".+\[seocode\]">#', $result); $this->assertRegExp('#<label><input type="checkbox" id=".+" name=".+\[active\]" value="1"> Active</label>#', $result); $this->assertRegExp('#<input type="submit" value="Создать">#', $result); } }
    true
    e2e53775768928bcf9bde6fa7b7e4efcc8b8450e
    PHP
    puterakahfi/MessageBus
    /src/Handler/Map/MessageHandlerMap.php
    UTF-8
    372
    2.546875
    3
    [ "MIT" ]
    permissive
    <?php namespace SimpleBus\Message\Handler\Map; use SimpleBus\Message\Handler\Map\Exception\NoHandlerForMessageName; use SimpleBus\Message\Handler\MessageHandler; interface MessageHandlerMap { /** * @param string $messageName * @throws NoHandlerForMessageName * @return MessageHandler */ public function handlerByMessageName($messageName); }
    true
    20623fd0931c9d27b0922946fc65488cf2eeee5d
    PHP
    itsrsy/SocietasPro
    /tests/phpunit/Objects/SubscriberTest.php
    UTF-8
    600
    2.71875
    3
    []
    no_license
    <?php /** * Test the subscriber object * * @author Chris Worfolk <[email protected]> * @package UnitTests * @subpackage Objects */ class SubscriberTest extends PHPUnit_Framework_TestCase { protected $object; protected function setUp () { require_once("../../application/admin/objects/Subscriber.php"); $this->object = new Subscriber(); } public function testSetEmailAddress () { $this->assertTrue($this->object->setEmailAddress("[email protected]")); $this->assertFalse($this->object->setEmailAddress("not-a-valid-email-address!")); $this->assertSame($this->object->subscriberEmail, "[email protected]"); } }
    true
    8458be938b47bd94a6f91ac19e678f990f2f7493
    PHP
    5baddi/lifemoz-coding-challenge
    /app/Http/Resources/RoomResource.php
    UTF-8
    752
    2.53125
    3
    []
    no_license
    <?php namespace App\Http\Resources; use Carbon\Carbon; use Illuminate\Http\Resources\Json\JsonResource; class RoomResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'uuid' => $this->uuid, 'name' => $this->name, 'user' => $this->user ?? null, 'updated_at' => Carbon::parse($this->updated_at)->format('H:i d/m/Y'), 'created_at' => Carbon::parse($this->created_at)->format('H:i d/m/Y'), ]; } }
    true
    01679d3ad5b3b0c9469e0d0ad55d64fd34eebcf7
    PHP
    ryanhellyer/auto-xml-backup
    /inc/class-auto-xml-backup-admin-notice.php
    UTF-8
    730
    2.6875
    3
    []
    no_license
    <?php /** * Adds an admin notice, alerting the admin that the email address field is blank. */ class Auto_XML_Backup_Admin_Notice extends Auto_XML_Backup_Abstract { /** * Fire the constructor up :) */ public function __construct() { add_action( 'admin_notices', array( $this, 'message' ) ); } /** * Output the message. */ public function message() { // Bail out if email addresses already stored if ( '' != get_option( self::SLUG ) ) { return; } echo ' <div class="notice notice-warning"> <p>' . sprintf( __( 'Email addresses need to be added to the <a href="%s">Auto XML Backup settings page</a>.', 'auto-xml-backup' ), esc_url( $this->get_settings_url() ) ) . '</p> </div>'; } }
    true
    238be97af2f39ad6ad6242aa292efa5a1b7c6d56
    PHP
    JohnHasmie/restaurant
    /classes/Stripe.class.php
    UTF-8
    1,572
    2.640625
    3
    []
    no_license
    <?php class Stripe { protected $stripToken; public function __construct($data) { $this->stripToken = $data['stripeToken']; \Stripe\Stripe::setApiKey('sk_test_51Ie6PpL8uWnAKjvMZ6aZwNXtiuxGyhOlUV8CXKT2JDdflqKXKyfDc96SqAzrwh92xdULc8lCX5lOMh8DSaM2vRzl00W5fOmfHN'); } public function processPayment($orders) { $order = $orders[0]; $stripToken = $this->stripToken; \Stripe\Charge::create ([ "amount" => round($order->grand_total)*100, "currency" => 'USD', "source" => $stripToken, "description" => "Test payment from click and collect." ]); $orderClass = new Order; $orderClass->payOrder($order->order_number, 'Stripe-'.$order->order_number); // $checkout_session = \Stripe\Checkout\Session::create([ // 'payment_method_types' => ['card'], // 'line_items' => [[ // 'price_data' => [ // 'currency' => 'USD', // 'unit_amount' => round($order->grand_total)*100, // 'product_data' => [ // 'name' => $order->name, // // 'images' => [Config::PRODUCT_IMAGE], // ], // ], // 'quantity' => 1, // ]], // 'mode' => 'payment', // 'client_reference_id' => $order->id, // 'success_url' => BASE_URL.'/callback/stripe.cb.php?success=true', // 'cancel_url' => BASE_URL.'/callback/stripe.cb.php?success=false', // ]); // return $checkout_session; } }
    true
    a4674ae8bbb11c939aa79caf146362b96f5c693d
    PHP
    shuvro-zz/Symfony-3-ERPMedical
    /src/BackendBundle/Entity/TypeGender.php
    UTF-8
    2,417
    2.859375
    3
    [ "MIT" ]
    permissive
    <?php /* Namespace **************************************************************************************************/ namespace BackendBundle\Entity; /* Añadimos el VALIDADOR **************************************************************************************/ /* * Definimos el sistema de validación de los datos en las entidades dentro de "app\config\config.yml" * y la gestionamos en "src\AppBundle\Resources\config\validation.yml", * cada entidad deberá llamar a "use Symfony\Component\Validator\Constraints as Assert;" * VER src\BackendBundle\Entity\User.php */ use Symfony\Component\Validator\Constraints as Assert; /**************************************************************************************************************/ /* * Un ArrayCollection es una implementación de colección que se ajusta a la matriz PHP normal. */ use Doctrine\Common\Collections\ArrayCollection; /* * También deberá incluir "use Doctrine\ORM\Mapping as ORM;"" como ORM; instrucción, que importa el * prefijo de anotaciones ORM. */ use Doctrine\ORM\Mapping as ORM; /**************************************************************************************************************/ class TypeGender { /* Un ArrayCollection es una implementación de colección que se ajusta a la matriz PHP normal. */ private $genderArray; public function __construct() { $this->genderArray = new ArrayCollection(); } /* Id de la Tabla *********************************************************************************************/ private $id; public function getId() { return $this->id; } /**************************************************************************************************************/ /* gender *****************************************************************************************************/ private $type; public function setType($type = null) { $this->type = $type; return $this; } public function getType() { return $this->type; } /**************************************************************************************************************/ /* * la función __toString(){ return $this->gender; } permite * listar los campos cuando referenciemos la tabla */ public function __toString(){ return (string)$this->type; } /**************************************************************************************************************/ }
    true
    0b33d04a0409e60306cbc57dc3ff29e1cbecc133
    PHP
    shiroro666/Vaccination_System
    /index.php
    UTF-8
    2,460
    2.765625
    3
    []
    no_license
    <!DOCTYPE html> <html> <title>Patient Index Page</title> <?php include ("connectdb.php"); if(!isset($_SESSION["user_id"])) { echo "You are currently not logged in. <br /><br >\n"; echo 'Click <a href="login.php">login</a> to login or <a href="register.php">register</a> if you don\'t have an account yet.<br /><br />'; echo 'Click <a href="signup.php">Signup</a> to login if you are a provider.'; echo "\n"; } else { $username = htmlspecialchars($_SESSION["username"]); $user_id = htmlspecialchars($_SESSION["user_id"]); //echo "4"; if ($stmt = $mysqli->prepare("select patientId, name, ssn, birthday, address, phone, email from patient where patientId=?")){ //echo("1"); $stmt->bind_param("s", $user_id); $stmt->execute(); $stmt->bind_result($pid, $name, $ssn, $birthday, $address, $phone, $email); if ($stmt->fetch()){ echo "Welcome $username. You are logged in to the system.<br /><br />\n"; echo "Your Information:<br />"; echo "UserID:".$pid."<br />"; echo "Name:".$name."<br />"; echo "SSN:".$ssn."<br />"; echo "Birthday:".$birthday."<br />"; echo "Address:".$address."<br />"; echo "Phone:".$phone."<br />"; echo "E-Mail:".$email."<br /><br />"; echo 'To view the your appointment offers, <a href="view.php">click here</a>, '; echo "<br /><br />"; echo 'Update information: <a href="update_info.php">click here</a>, '; echo "<br /><br />"; echo 'View or add preferences: <a href="preference.php">click here</a>, '; echo "<br /><br />"; echo 'Log out: <a href="logout.php">click here</a>.'; echo "\n"; } $stmt->close(); } if ($stmt = $mysqli->prepare("select providertype, name, phone, address from provider where providerId=?")){ //echo("2"); $stmt->bind_param("s", $user_id); $stmt->execute(); $stmt->bind_result($pt, $name, $phone, $address); if ($stmt->fetch()){ echo "Welcome $username. You are logged in to the system.<br /><br />\n"; echo "Your Information:<br />"; echo "Provider Type:".$pt."<br />"; echo "Name:".$name."<br />"; echo "Address:".$address."<br />"; echo "Phone:".$phone."<br /><br />"; echo "To view or add appointment <a href=\"appointment.php\">here</a>."; echo "<br /><br />"; echo 'Log out: <a href="logout.php">click here</a>.'; echo "\n"; } $stmt->close(); } } ?> </html>
    true
    6f9fc1a1c7e0ec206a848408924c01cc32ad5374
    PHP
    KrisoprasEpikuros/unbk
    /application/libraries/JalurState/JalurState.php
    UTF-8
    962
    2.90625
    3
    []
    no_license
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Description of JalurState * @property CI_Controller $ci * @property StateManager $stateManager * @property JenisSiswaState $jenisSiswaState * * @author m.rap */ abstract class JalurState { protected $ci; protected $stateManager; private $jenisSiswaState; protected $name; public function __construct(&$ci, &$stateManager) { $this->ci =& $ci; $this->stateManager =& $stateManager; } public function &getName() { return $this->name; } public function __get($name) { if ($this->$name == null) { switch ($name) { case 'jenisSiswaState': $this->jenisSiswaState =& $this->stateManager->getJenisSiswaState(); break; } } return $this->$name; } public abstract function validasi(); }
    true
    58bf076ad98b71b8e346dfd194630f9a7fb3ec66
    PHP
    juanda/curso_php7_ejercicios
    /ejercicio3/find.php
    UTF-8
    625
    2.578125
    3
    []
    no_license
    <?php require __DIR__ . '/libs/autoloader.php'; require __DIR__ . '/readline.php'; use Acme\TopSecret\AES256Crypter; use Acme\KeyStorage\KeyFileStorage; use Acme\KeyStorage\KeyRegister; if($argc != 2){ echo "Uso: $argv[0] nombre_registro". PHP_EOL; exit; } $nombreRegistro = $argv[1]; $keyfile = "keyfile"; $key = _readline('key: '); $crypter = new AES256Crypter($key); $keyStorage = new KeyFileStorage($crypter, $keyfile); $item = $keyStorage->find($nombreRegistro); if(is_null($item)){ echo "No hay ningún registro con ese nombre"; echo PHP_EOL; } print_r($item);
    true
    060996196d76d763aa438cb253cb743ae79faa4c
    PHP
    brunocaramelo/estudos
    /php/zendframework-modulo-1/estoque/skeleton-application/module/Estoque/src/View/Helper/PaginationHelper.php
    UTF-8
    711
    2.65625
    3
    []
    no_license
    <?php namespace Estoque\View\Helper; use Zend\View\Helper\AbstractHelper; class PaginationHelper extends AbstractHelper{ public function __invoke( $itens , $qtdPagina , $url ){ $this->url = $url; $this->totalItens = $itens->count(); $this->qtdPagina = $qtdPagina; return $this; } public function render(){ $count = 0; $totalPaginas = ceil( $this->totalItens / $this->qtdPagina ); $html = "<ul class='nav nav-pills'>"; while( $count < $totalPaginas ){ $count++; $html.= "<li><a href='{$this->url}/{$count}' >{$count}</a></li>"; } $html.="</ul>"; return $html; } }
    true
    9beaf237f0e7a9706aaf9dec1d58e2b61d188319
    PHP
    danielkiesshau/WebPractice
    /PHP/update.php
    UTF-8
    1,462
    2.6875
    3
    []
    no_license
    <?php require_once("Sql.php"); $sql = new Sql(); //This will result in a query of active drivers to pass to the JS to update the UI $rs = $sql->select("SELECT nome FROM MOTORISTAS WHERE sstatus = :STATUS",array(":STATUS"=>1)); $data = json_encode($rs); $tipo = $_GET['tipo']; setcookie("tabela","1", time() + (400), "/"); ?> <script src="../lib/jquery-1.11.1.js"></script> <script type=text/javascript> //Get the data stored in dadosPHP $(document).ready(function(){ var dadosJson = $("#dadosPHP").html(); //Converting data to JSON var objJson = JSON.parse(dadosJson); //Store localStorage.setItem('obj', JSON.stringify(objJson)); var tipo = $("#tipo").html(); //Redirecting to passageiro.html if(tipo == 'passageiro'){ window.location.href="https://whispering-eyrie-32116.herokuapp.com/Paginas/HTML/passageiro.html?update=1"; }else if(tipo == 'corrida'){ window.location.href="https://whispering-eyrie-32116.herokuapp.com/Paginas/HTML/corrida.html?update=1"; }else{ window.location.href="https://whispering-eyrie-32116.herokuapp.com/index.html"; } }); </script> <!DOCTYPE html> <html> <meta charset='UTF-8'> <head></head> <body> <div id="dadosPHP" style="display:none;"><?php echo $data;?></div> <div id="tipo" style="display:none;"><?php echo $tipo;?></div> </body> </html>
    true
    ba68d0b1e36147bc60f7aef3497a3be4b8c88e73
    PHP
    stephenjohndev/renewmember-them-little
    /public/_system/php/api/customer/getAgeCounts.php
    UTF-8
    1,866
    2.9375
    3
    []
    no_license
    <?php # Set database parameters require_once $_SERVER['DOCUMENT_ROOT'].'/_system/php/connection/db_connection.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/_system/php/functions/checkAdminToken.php'; try { # Connect to Database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); # Perform SQL Query // $stmt = $conn->prepare("SELECT DATE(account_created) as date, COUNT(account_id) as count FROM accounts WHERE account_created BETWEEN $start_date AND $end_date GROUP BY date"); $stmt = $conn->prepare( "SELECT CASE WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) < 18 THEN 'Below 18' WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 18 AND 30 THEN '18-30' WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 31 AND 45 THEN '31-45' WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 46 AND 60 THEN '46-60' ELSE 'Over 60' END AS age_range, COUNT(account_id) as count FROM accounts GROUP BY age_range" ); $stmt->execute(); # Fetch Result $age_ranges = array(); $counts = array(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { array_push($age_ranges, $row['age_range']); array_push($counts, $row['count']); } $result = array( 'age_ranges' => $age_ranges, 'counts' => $counts ); # Print Result in JSON Format echo json_encode((object)[ 'success' => true, 'data' => $result ],JSON_NUMERIC_CHECK); } catch(PDOException $e) { echo json_encode((object)[ 'success' => false, 'message' => "Connection failed: " . $e->getMessage() ]); } ?>
    true
    1acb58be632664fa589152ec5cc990dd5a3f91cb
    PHP
    stoyantodorovbg/PHP-Web-Development-Basics
    /PHP Associate Arrays and Functions - Lab/1 asociativeArrays/1-characterCount.php
    UTF-8
    561
    3.328125
    3
    [ "MIT" ]
    permissive
    <?php $word = fgets(STDIN); $word = strtolower($word); $countLetters = []; for ($i = 0; $i < strlen($word); $i++) { if (isset($countLetters[$word[$i]])) { $countLetters[$word[$i]]++; } else { $countLetters[$word[$i]] = 1; } } $result = '['; $counter = 0; foreach ($countLetters as $key => $value) { $counter++; $result .= '"'; $result .= $key; $result .= '" => "'; $result .= $value; if ($counter === count($countLetters)) { } else { $result .= '", '; } } $result .= ']'; echo($result);
    true
    e6e4fc27278c55d2ac057e9d68109430ce5fde80
    PHP
    PhilippeSimier/Gestion_Inscriptions
    /administration/authentification/auth.php
    UTF-8
    2,852
    2.6875
    3
    []
    no_license
    <?php if(!isset($_POST['md5'])) { header("Location: ../index.php"); exit(); } if(!isset($_POST['login'])) { header("Location: ../index.php"); exit(); } if($_POST['login']==NULL) { header("Location: ../index.php?&erreur=Requiert un identifiant et un mot de passe."); exit(); } require_once('../../definitions.inc.php'); // connexion à la base $bdd = new PDO('mysql:host=' . SERVEUR . ';dbname=' . BASE, UTILISATEUR,PASSE); // utilisation de la méthode quote() // Retourne une chaîne protégée, qui est théoriquement sûre à utiliser dans une requête SQL. $sql = sprintf("SELECT * FROM utilisateur WHERE utilisateur.login=%s", $bdd->quote($_POST['login'])); $stmt = $bdd->query($sql); $utilisateur = $stmt->fetchObject(); // vérification des identifiants login et md5 par rapport à ceux enregistrés dans la base if (!($_POST['login'] == $utilisateur->login && $_POST['md5'] == $utilisateur->passe)){ header("Location: ../index.php?&erreur=Incorrectes! Vérifiez vos identifiant et mot de passe."); exit(); } // A partir de cette ligne l'utilisateur est authentifié // donc nouvelle session session_start(); // écriture des variables de session pour cet utilisateur $_SESSION['last_access'] = time(); $_SESSION['ipaddr'] = $_SERVER['REMOTE_ADDR']; $_SESSION['ID_user'] = $utilisateur->ID_user; $_SESSION['login'] = $utilisateur->login; $_SESSION['identite'] = $utilisateur->identite; $_SESSION['email'] = $utilisateur->email; $_SESSION['droits'] = $utilisateur->droits; $_SESSION['path_fichier_perso'] = $utilisateur->path_fichier_perso; // enregistrement de la date et heure de son passage dans le champ date_connexion de la table utilisateur $ID_user = $utilisateur->ID_user; $sql = "UPDATE `utilisateur` SET `date_connexion` = CURRENT_TIMESTAMP WHERE `utilisateur`.`ID_user` =$ID_user LIMIT 1" ; $stmt = $bdd->query($sql); // Incrémentation du compteur de session $sql = "UPDATE utilisateur SET `nb_session` = `nb_session`+1 WHERE `utilisateur`.`ID_user` =$ID_user LIMIT 1" ; $stmt = $bdd->query($sql); // sélection de la page de menu en fonction des droits accordés switch ($utilisateur->droits) { case 0: // Utilisateur révoqué sans droit header("Location: ../index.php?&erreur=révoqué! "); break; case 1: // Organisateurs de niveau 1 header("Location: ../orga_menu.php"); break; case 2: // Organisateurs de niveau 2 header("Location: ../orga_menu.php"); break; case 3: // Administrateurs de niveau 3 header("Location: ../orga_menu.php"); break; default: header("Location: ../index.php"); } ?>
    true
    abf3c72df1963548b31c942011da660ba2779b93
    PHP
    Mirdrack/prueba
    /classes/Vehicles.php
    UTF-8
    1,123
    3.3125
    3
    []
    no_license
    <?php require_once('Vehicle.php'); /** * This class will manage an array of Vehicles object instances */ class Vehicles { private $sql; private $error; private $vehicles; function __construct() { $this->sql = new SqlEngine(); $this->sql->connect(); $this->vehicles = array(); } public function getAll() { $query = 'SELECT *'; $query .= 'FROM vehicles '; $result = $this->sql->query($query); if($result != 1) { return false; $this->error = $this->sql->geterror(); // This will send an error to up level } else { if($this->sql->getRowsAffected() > 0 ) { while($row = mysql_fetch_array($this->sql->getQueryResult(), MYSQL_BOTH)) { $current = new Vehicle(); $current->setVehicle($row); array_push($this->vehicles, $current); } return true; } else { $this->error = "No vehicles"; return false; } } } public function getVehicles() { $data = array(); foreach ($this->vehicles as $vehicle) { array_push($data, $vehicle->asArray()); } return $data; } public function getError() { return $this->error; } } ?>
    true
    c3dafcdc1cf8cf95f3f50cc73e9b549556d6380c
    PHP
    andreafiori/php-coding-dojo
    /src/algorithms/math/Calculator.php
    UTF-8
    580
    3.859375
    4
    []
    no_license
    <?php namespace algorithms\math; class Calculator { /** * @var int|float */ public $op1; /** * @var int|float */ public $op2; /** * Addition * * @return float|int */ public function add() { return $this->op1 + $this->op2; } /** * Subtraction * * @return float|int */ public function subtract() { return $this->op1 - $this->op2; } /** * Check if number is divisible * * @return bool */ public function isDivisible() { return $this->op1 % $this->op2 == 0; } }
    true
    1b2ef6891fc923b4957d5d139c606bad6ac070c7
    PHP
    845alex845/consultorafisi
    /app/model/Escuela.php
    UTF-8
    414
    2.53125
    3
    []
    no_license
    <?php class Escuela{ $cod_facultad; $nom_facultad; $nom_decano; public function obtenerEscuela($cod_facultad){ $sql="SELECT * from facultad where cod_fac=$id"; $conn=oci_connect("consultora","consultora"); $prepare=oci_parse($conn,$sql); oci_execute($prepare); $scar = oci_fetch_assoc($prepare); return $scar; } } ?>
    true
    7e4927d6a3bf4319af1c1f81c32fe84dfdd37481
    PHP
    puiutucutu/geophp
    /src/functions/createUtmFromLatLng.php
    UTF-8
    339
    2.75
    3
    []
    no_license
    <?php use PHPCoord\LatLng; use PHPCoord\RefEll; use PHPCoord\UTMRef; /** * Uses WGS84 ellipsoid. * * @param float $latitude * @param float $longitude * * @return UTMRef */ function createUtmFromLatLng($latitude, $longitude) { $LatLng = new LatLng($latitude, $longitude, 0, RefEll::wgs84()); return $LatLng->toUTMRef(); }
    true
    65919c02274116037b4969c1fc2b4be4854335a1
    PHP
    mstremante/advent-of-code-2019
    /13/part2.php
    UTF-8
    6,654
    3.203125
    3
    []
    no_license
    <?php // Run with php part2.php [input] // If no input file is specified defaults to input.txt in local directory $file = "input.txt"; if(isset($argv[1])) { $file = $argv[1]; } if(file_exists($file)) { $handle = fopen($file, "r"); $opcodes = explode(",", fread($handle, filesize($file))); fclose($handle); $opcodes[0] = 2; $computer = new Computer($opcodes); $screen = array(); $ballX = $paddleX = $score = 0; while(!$computer->isFinished()) { $input = 0; if($ballX > $paddleX) { $input = 1; } if($ballX < $paddleX) { $input = -1; } $outputs = $computer->runProgram($input); $i = 0; while($i < count($outputs)) { if($outputs[$i] == "-1") { $score = $outputs[$i + 2]; } else { if($outputs[$i + 2] == 4) { $ballX = $outputs[$i]; } if($outputs[$i + 2] == 3) { $paddleX = $outputs[$i]; } $screen[$outputs[$i]][$outputs[$i + 1]] = $outputs[$i + 2]; } $i = $i + 3; } // Optional //printScreen($screen); } echo $score; } function printScreen($screen) { $i = 0; $smallX = $bigX = $smallY = $bigY = null; foreach($screen as $x => $y) { if(is_null($smallX)) { $smallX = $x; } if(is_null($bigX)) { $bigX = $x; } if($smallX > $x) { $smallX = $x; } if($bigX < $x) { $bigX = $x; } foreach($y as $id => $tile) { if(is_null($smallY)) { $smallY = $id; } if(is_null($bigY)) { $bigY = $id; } if($smallY > $id) { $smallY = $id; } if($bigY < $id) { $bigY = $id; } } } // Print drawing for($y = $smallY; $y <= $bigY; $y++) { for($x = $smallX; $x <= $bigX; $x++) { $char = " "; if(isset($screen[$x][$y])) { $tile = $screen[$x][$y]; switch($tile) { case 1: $char = "#"; break; case 2: $char = "@"; break; case 3: $char = "_"; break; case 4: $char = "*"; break; } } echo $char; } echo "\n"; } echo "\n\n"; } class Computer { private $data = array(); private $pointer = 0; private $relativeBase = 0; private $finished = false; function __construct($program) { $this->data = $program; } // Executes program function runProgram($inputs = array()) { $outputs = false; if(!is_array($inputs)) { $inputs = array($inputs); } while(($command = $this->data[$this->pointer]) != 99) { // Parse command: $op = substr($command, -2); $command = str_pad($command, 5, 0, STR_PAD_LEFT); switch($op) { // Addition and multiplication case "01": case "02": $op1 = $this->getValue($command, 1); $op2 = $this->getValue($command, 2); if($op == 01) { $res = $op1 + $op2; } else { $res = $op1 * $op2; } $this->setValue($command, 3, $res); $this->pointer += 4; break; // Input value case "03": if(!count($inputs)) { return $outputs; } $input = array_shift($inputs); $this->setValue($command, 1, $input); $this->pointer += 2; break; // Output value case "04": $mode1 = substr($command, -3)[0]; $outputs[] = $this->getValue($command, 1); $this->pointer += 2; break; // Jump if true and jump if false case "05": case "06": $op1 = $this->getValue($command, 1); $op2 = $this->getValue($command, 2); if(($op == "05" && $op1 != 0) || ($op == "06" && $op1 == 0)) { $this->pointer = $op2; } else { $this->pointer +=3; } break; // Less than and equals case "07": case "08": $op1 = $this->getValue($command, 1); $op2 = $this->getValue($command, 2); if(($op == "07" && $op1 < $op2) || ($op == "08" && $op1 == $op2)) { $res = 1; } else { $res = 0; } $this->setValue($command, 3, $res); $this->pointer += 4; break; // Adjust relative base case "09": $op1 = $this->getValue($command, 1); $this->relativeBase += $op1; $this->pointer += 2; break; } } $this->finished = true; return $outputs; } function getValue($command, $param) { $mode = substr($command, -($param + 2))[0]; $addr = $this->data[$this->pointer + $param]; if($mode == 1) { return $addr; } elseif($mode == 2) { $addr = $addr + $this->relativeBase; } // Initialize memory if(!isset($this->data[$addr])) { $this->data[$addr] = 0; } return $this->data[$addr]; } function setValue($command, $param, $value) { $mode = substr($command, -($param + 2))[0]; $addr = $this->data[$this->pointer + $param]; if($mode == 1 || $mode == 0) { $this->data[$addr] = $value; } elseif($mode == 2) { $this->data[$addr + $this->relativeBase] = $value; } } function isFinished() { return $this->finished; } } ?>
    true
    f2f9c72ae514b27a23380a13ff1573154b323ea5
    PHP
    holiday/Validator
    /Validator.php
    UTF-8
    3,175
    3.34375
    3
    []
    no_license
    <?php namespace Validator; require_once 'Bootstrapper.php'; require_once 'Rule.php'; class Validator { //stores the rules and options private $rules; //stores the data as key:value pairs private $data; //logs errors for each field private $errors = array(); /** * Initializes a new Validator with rules and the data to perform the validation on * @param type $rules Array of fieldnames to rules * @param type $data Array of key value pairs of data */ public function __construct($rules, $data) { $this->rules = $rules; $this->data = $data; // Initialize the bootstrapper $bootstrap = new \Validator\Bootstrapper(dirname(__FILE__)); $bootstrap->register(); } /** * Getter for the errors * @return type Array */ public function getErrors() { return $this->errors; } /** * Return true if there are no errors * @return type Boolean */ public function isValid() { return empty($this->errors); } /** * Parses through each rule * @return type void */ public function validate($rules = null) { //Rules dictating which fields to validate and strategy to use if ($rules == null) { $rules = $this->rules; } //Loop over each field:rule pairs foreach ($rules as $fieldName => $rule) { //single rule detected if (!is_array($rule)) { //validate the field with specifications in array $rule $this->_validate($fieldName, $rule); } else { //multiple rules detected, recurse foreach ($rule as $singleRule) { $multiRule[$fieldName] = $singleRule; $this->validate($multiRule); } } } } /** * Helper method for validate(). Validates an individual field by loading the correct AbstractValidator * and passing in the necessart options. * @param type $fieldName String * @param type $rule Array * @return type void */ private function _validate($fieldName, $rule) { //single rule $validator = '\\ValidationTypes\\' . ucfirst($rule->getValidator()) . 'Validator'; $val = new $validator($this->getData($fieldName), $rule->getOptions()); //Validate and log any errors if (!$val->validate() && !isset($this->errors[$fieldName])) { $this->errors[$fieldName] = $rule->getMessage(); } } /** * Return the data if found, null otherwise * @param type $fieldName * @return null */ private function getData($fieldName) { if (!isset($this->data[$fieldName])) { return null; } else { $data = $this->data[$fieldName]; if(is_string($data)) { $data = trim($this->data[$fieldName]); } return $data; } } } ?>
    true
    79e5337b912b712e6ab7125bff1865b8e14b86a3
    PHP
    onenook/helper
    /src/string/Sign.php
    UTF-8
    1,129
    3.34375
    3
    [ "Apache-2.0" ]
    permissive
    <?php namespace nook\string; class Sign { // ------------------------------ 微信签名 ------------------------------ /** * 生成签名 * @param array $data * @return string */ public static function makeSign(array $data): string { // 签名步骤一:按字典序排序参数 ksort($data); $string = self::toUrlParams($data); // 签名步骤二:在string后加入time $string = $string . '&time=' . time(); // 签名步骤三:sha1加密 $string = sha1($string); // md5() // 签名步骤四:所有字符转为大写 $string = strtoupper($string); return $string; } /** * 格式化参数格式化成url参数 * @param array $data * @return string */ public static function toUrlParams(array $data): string { $buff = ''; foreach ($data as $k => $v) { if ($k != 'sign' && $v != '' && !is_array($v)) { $buff .= $k . '=' . $v . '&'; } } $buff = trim($buff, '&'); return $buff; } }
    true
    ee5dddaf65cb860277505b6ba4042b574bcb2e89
    PHP
    robsli/Web-Apps-TESI-Calendar
    /dboperation.php
    UTF-8
    206
    2.6875
    3
    [ "MIT" ]
    permissive
    <?php function connectToDB($user, $pw, $dbname){ $dbc = @mysqli_connect("localhost", $user, $pw, $dbname) OR die("Could not connect to MySQL on cscilab: ". mysqli_connect_error()); return $dbc; } ?>
    true
    2b2e01627f94f73cadbb793c2c9a949f1fdb150b
    PHP
    pmatiash/shape-drawer
    /app/Trapezoid.php
    UTF-8
    1,647
    3.4375
    3
    []
    no_license
    <?php namespace app; /** * Class Trapezoid Shape * @package app */ class Trapezoid extends Shape { private $sideTop; private $sideBottom; private $height; /** * @param int $sideTop * @param int $sideBottom * @param int $height * @param string $color */ public function __construct($sideTop, $sideBottom, $height, $color) { if (!$this->isCorrectTrapezoid($sideTop, $sideBottom, $height)) { throw new \Exception("Trapezoid with these parameters can't be exists"); } $this->sideTop = (int) $sideTop; $this->sideBottom = (int) $sideBottom; $this->height = (int) $height; $this->color = $color; } /** * @param $sideTop * @param $sideBottom * @param $height * @return bool */ private function isCorrectTrapezoid($sideTop, $sideBottom, $height) { if ($sideTop <= 0 ) { return false; } if ($sideBottom <= 0) { return false; } if ($height <= 0) { return false; } return true; } /** * @inheritdoc */ public function getName() { return 'Трапеция'; } /** * @inheritdoc */ public function draw() { return parent::draw() . sprintf(', верхняя сторона: %s, нижняя сторона: %s, высота: %s', $this->sideTop, $this->sideBottom, $this->height); } /** * @inheritdoc */ public function getSquare() { return ($this->sideTop + $this->sideBottom) / 2 * $this->height; } }
    true
    fdd9f6f70ce5ac4c94ed991ca9bb69ddc205093c
    PHP
    alexdiasgonsales/organizador
    /sistema/model/mysql/SessaoMySqlDAO.class.php
    UTF-8
    6,396
    2.625
    3
    []
    no_license
    <?php /** * Classe de operação da tabela 'sessao'. Banco de Dados Mysql. * Estas classes não contemplam meu projeto final, por estarem obsoletas, estou contruindo * novos templates em Persistent Data Object com definição de prepared statements contra * sql injection, utilize para meio de testes, nunca coloque em produção, servindo * apenas de trampolin para classe de produção * * @autor: Alessander Wasem * @data: 2014-05-21 21:57 */ class SessaoMySqlDAO implements SessaoDAO{ protected $table = 'sessao'; /** * Implementa o dominio chave primária na seleção de único registro * * @parametro String $id primary key * @retorna SessaoMySql */ public function load($id){ $sql = "SELECT * FROM $this->table WHERE id_sessao = :id_sessao"; $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id_sessao', $id, PDO::PARAM_INT); $stmt->execute(); return $stmt->fetch(); } public function querySessaoByAvaliador($id_avaliador) { $sql =<<<SQL select sessao.id_sessao, sessao.numero, sessao.nome, sessao.sala, sessao.nome_sala, sessao.andar, sessao.nome_andar, sessao.data, sessao.hora_ini, sessao.hora_fim, avaliador_sessao.status from sessao inner join avaliador_sessao on sessao.id_sessao = avaliador_sessao.fk_sessao where fk_avaliador = :id_avaliador; SQL; $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id_avaliador', $id_avaliador, PDO::PARAM_INT); $stmt->execute(); return $stmt->fetchAll(); } public function updateConfirmacaoSessao($id_avaliador, $id_sessao, $status_int) { $sql =<<<SQL update avaliador_sessao set status = :status_int where fk_sessao = :id_sessao and fk_avaliador = :id_avaliador SQL; $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id_avaliador', $id_avaliador, PDO::PARAM_INT); $stmt->bindParam(':id_sessao', $id_sessao, PDO::PARAM_INT); $stmt->bindParam(':status_int', $status_int, PDO::PARAM_INT); return $stmt->execute(); } /** * Obtem todos o registros das Tabelas */ public function queryAll(){ $sql = "SELECT * FROM $this->table"; $stmt = ConnectionFactory::prepare($sql); $stmt->execute(); return $stmt->fetchAll(); } /** * Exclui um registro da tabela * @parametro sessao chave primária */ public function delete($id){ $sql = "DELETE FROM $this->table WHERE id_sessao = :id_sessao"; $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id_sessao', $id, PDO::PARAM_INT); return $stmt->execute(); } /** * Inseri um registro na tabela * * @parametro SessaoMySql sessao */ public function insert(Sessao $Sessao){ $sql = "INSERT INTO $this->table (numero, nome, sala, nome_sala, andar, nome_andar, data, hora_ini, hora_fim, fk_modalidade, status) VALUES ( :numero, :nome, :sala, :nomeSala, :andar, :nomeAndar, :data, :horaIni, :horaFim, :fkModalidade, :status)"; $numero = $Sessao->getNumero(); $nome = $Sessao->getNome(); $sala = $Sessao->getSala(); $nomeSala = $Sessao->getNomeSala(); $andar = $Sessao->getAndar(); $nomeAndar = $Sessao->getNomeAndar(); $data = $Sessao->getData(); $horaIni = $Sessao->getHoraIni(); $horaFim = $Sessao->getHoraFim(); $fkModalidade = $Sessao->getFkModalidade(); $status = $Sessao->getStatus(); $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':numero', $numero); $stmt->bindParam(':nome', $nome); $stmt->bindParam(':sala', $sala); $stmt->bindParam(':nomeSala', $nomeSala); $stmt->bindParam(':andar', $andar); $stmt->bindParam(':nomeAndar', $nomeAndar); $stmt->bindParam(':data', $data); $stmt->bindParam(':horaIni', $horaIni); $stmt->bindParam(':horaFim', $horaFim); $stmt->bindParam(':fkModalidade', $fkModalidade); $stmt->bindParam(':status', $status); return $stmt->execute(); } /** * atualiza um registro da tabela * * @parametro SessaoMySql sessao */ public function update(Sessao $Sessao){ $sql = "UPDATE $this->table SET numero = :numero, nome = :nome, sala = :sala, nome_sala = :nome_sala, andar = :andar, nome_andar = :nome_andar, data = :data, hora_ini = :hora_ini, hora_fim = :hora_fim, fk_modalidade = :fk_modalidade, status = :status WHERE id_sessao = :id"; $id = $Sessao->getIdSessao(); $numero = $Sessao->getNumero(); $nome = $Sessao->getNome(); $sala = $Sessao->getSala(); $nomeSala = $Sessao->getNomeSala(); $andar = $Sessao->getAndar(); $nomeAndar = $Sessao->getNomeAndar(); $data = $Sessao->getData(); $horaIni = $Sessao->getHoraIni(); $horaFim = $Sessao->getHoraFim(); $fkModalidade = $Sessao->getFkModalidade(); $status = $Sessao->getStatus(); $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id', $id); $stmt->bindParam(':numero', $numero); $stmt->bindParam(':nome', $nome); $stmt->bindParam(':sala', $sala); $stmt->bindParam(':nomeSala', $nomeSala); $stmt->bindParam(':andar', $andar); $stmt->bindParam(':nomeAndar', $nomeAndar); $stmt->bindParam(':data', $data); $stmt->bindParam(':horaIni', $horaIni); $stmt->bindParam(':horaFim', $horaFim); $stmt->bindParam(':fkModalidade', $fkModalidade); $stmt->bindParam(':status', $status); return $stmt->execute(); } }
    true
    d3a69d76ef83838df21d374dfc259ed02dae7dc8
    PHP
    activecollab/authentication
    /src/AuthenticationResult/Transport/Transport.php
    UTF-8
    2,630
    2.625
    3
    [ "MIT" ]
    permissive
    <?php /* * This file is part of the Active Collab Authentication project. * * (c) A51 doo <[email protected]>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\Authentication\AuthenticationResult\Transport; use ActiveCollab\Authentication\Adapter\AdapterInterface; use LogicException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; abstract class Transport implements TransportInterface { private $adapter; private $payload; public function __construct(AdapterInterface $adapter, $payload = null) { $this->adapter = $adapter; $this->payload = $payload; } public function getAdapter(): AdapterInterface { return $this->adapter; } public function getPayload() { return $this->payload; } public function setPayload($value): TransportInterface { $this->payload = $value; return $this; } public function isEmpty(): bool { return false; } private $isAppliedToRequest = false; private $isAppliedToResponse = false; public function applyToRequest(ServerRequestInterface $request): ServerRequestInterface { if ($this->isEmpty()) { throw new LogicException('Empty authentication transport cannot be applied'); } if ($this->isAppliedToRequest) { throw new LogicException('Authentication transport already applied'); } $this->isAppliedToRequest = true; return $this->getAdapter()->applyToRequest($request, $this); } public function applyToResponse(ResponseInterface $response): ResponseInterface { if ($this->isEmpty()) { throw new LogicException('Empty authentication transport cannot be applied'); } if ($this->isAppliedToResponse) { throw new LogicException('Authentication transport already applied'); } $this->isAppliedToResponse = true; return $this->getAdapter()->applyToResponse($response, $this); } public function applyTo(ServerRequestInterface $request, ResponseInterface $response): array { return [ $this->applyToRequest($request), $this->applyToResponse($response), ]; } public function isApplied(): bool { return $this->isAppliedToRequest && $this->isAppliedToResponse; } public function isAppliedToRequest(): bool { return $this->isAppliedToRequest; } public function isAppliedToResponse(): bool { return $this->isAppliedToResponse; } }
    true
    efc1624d2a3359d12ade6f749b993da717fdf766
    PHP
    FindMyFriends/api
    /App/Domain/Access/PgEntrance.php
    UTF-8
    1,075
    2.75
    3
    []
    no_license
    <?php declare(strict_types = 1); namespace FindMyFriends\Domain\Access; use Klapuch\Storage; /** * Entrance to PG database */ final class PgEntrance implements Entrance { /** @var \Klapuch\Storage\Connection */ private $connection; /** @var \FindMyFriends\Domain\Access\Entrance */ private $origin; public function __construct(Entrance $origin, Storage\Connection $connection) { $this->origin = $origin; $this->connection = $connection; } /** * @param array $credentials * @throws \UnexpectedValueException * @return \FindMyFriends\Domain\Access\Seeker */ public function enter(array $credentials): Seeker { $seeker = $this->origin->enter($credentials); (new Storage\NativeQuery($this->connection, 'SELECT globals_set_seeker(?)', [$seeker->id()]))->execute(); return $seeker; } /** * @throws \UnexpectedValueException * @return \FindMyFriends\Domain\Access\Seeker */ public function exit(): Seeker { (new Storage\NativeQuery($this->connection, 'SELECT globals_set_seeker(NULL)'))->execute(); return $this->origin->exit(); } }
    true
    2dfdc1de9ef3792c6a2b1224c967b7a4142e5330
    PHP
    araiy555/6ch
    /getleak/image.movie.php
    UTF-8
    5,664
    2.671875
    3
    [ "MIT" ]
    permissive
    <?php $count = count($_FILES['files']['tmp_name']); $errmsg = ""; // エラーメッセージ $gazou = []; $imageset = 0; $dougaset = 0; try { for ($i = 0; $i < $count; $i++) { //ファイル名の取得 $file_name = $_FILES["files"]["type"][$i]; //preg_match関数で判別するファイルの拡張子に「jpg」「jpeg」「png」「gif」が含まれているか確認する if ($_FILES["files"]["error"][$i] !== 4) { switch ($file_name) { case 'image/png': $imagecount = $imageset + 1; break; case 'image/jpeg': $imagecount = $imageset + 1; break; case 'image/jpg': $imagecount = $imageset + 1; break; case 'video/mp4': $dougaset = $dougaset + 1; $dougacount = $dougaset; break; default: $error = "$i'.枚目 拡張子は「jpg」「jpeg」「png」「mp4」です。</br>"; break; } } } if ($dougacount >= 1 AND $imagecount >= 1) { $error = "画像か動画のアップロードどちらかを設定してください。"; } if ($dougacount >= 2) { $error = "動画は1つのみです。"; } //エラー処理 if (empty($error)) { //動画アップロード if ($dougacount == 1) { $file_nm = $_FILES['files']['name'][0]; $tmp_ary = explode('.', $file_nm); $extension = $tmp_ary[count($tmp_ary) - 1]; if ($extension == 'mp4') { $size = $_FILES['files']['size'][0]; //30MB $san = '125829120'; if ($size < $san) { //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234'); $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai', 'q1w2e3r4'); $name = $_FILES['files']['name'][0]; $type = explode('.', $name); $type = end($type); $size = $_FILES['files']['size'][0]; $tmp = $_FILES['files']['tmp_name'][0]; $random_name = rand(); move_uploaded_file($tmp, 'files/' . $random_name . '.' . $type); $stmt = $pdo->prepare("INSERT INTO douga VALUES('','$name','files/$random_name.$type','')"); $stmt->execute(); $douga = $pdo->lastInsertId(); $stmt = $pdo->query("select * from douga where id = " . "$douga"); $result = $stmt->fetch(); ?> <input type="hidden" id="result1" name="" value="<?php echo $douga; ?>"> <video src="<?php echo $result['raw_data']; ?>" width="50%" height="50%" poster="thumb.jpg" controls></video> <?php } else { $error = "ファイルサイズが大きすぎます。"; echo $error; exit; } } } //画像アップロード if ($imagecount > 0) { for ($i = 0; $i < $count; $i++) { $size = $_FILES['files']['size'][$i]; if ($size < 20000) { $tmp = $_FILES["files"]["tmp_name"][$i]; $fp = fopen($tmp, 'rb'); $data = bin2hex(fread($fp, $size)); //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234'); $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai', 'q1w2e3r4'); //$dsn='mysql:host=localhost;dbname=mini_bbs'; $dsn = 'mysql:host=mysql5027.xserver.jp;dbname=earthwork_sample'; $pdo->exec("INSERT INTO `upload`(`type`,`data`) values ('$type',0x$data)"); $gazou[] = $pdo->lastInsertId(); $pdo = null; } else { $error = "画像は20KB以内です。"; echo $error; exit; } } $color = implode(",", $gazou); //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234'); $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai', 'q1w2e3r4'); $images = $pdo->query("select * from upload where id IN (" . $color . ")"); if (!empty($images)): foreach ($images as $i => $img): if ($i): endif; ?> <li id="<?php echo $img['id']; ?>"> <input type="hidden" id="result" name="" value="<?php echo $color ?>"> <img src="data:image/jpeg;base64,<?= base64_encode($img['data']) ?>" width="10%" height="10%" class="img"> </li> <?php endforeach; endif; } } else { echo $error; exit; } } catch (PDOException $e) { // 500 Internal Server Errorでテキストとしてエラーメッセージを表示 http_response_code(500); header('Content-Type: text/plain; charset=UTF-8', true, 500); exit($e->getMessage()); } ?>
    true
    2a1ccb95936a4bc640dbb97473ded42ea0c5ec88
    PHP
    fransaez85/clinica_js
    /php/consultaTodosMedicos.php
    UTF-8
    1,069
    2.953125
    3
    []
    no_license
    <?php include_once 'conexion.php'; //consulta todos los registros $query = "SELECT * FROM medico"; $resul = $conexion->query($query); $dimension=$resul->num_rows; if ($dimension>0) { # code... for ($i=0; $i < $dimension; $i++) { $array_fila[] = $resul->fetch_assoc(); $objmedico =$array_fila[$i]; $array_medicos[$i] = $objmedico; } $obj_JSON = json_encode($array_medicos); //alert($obj_JSON); echo $obj_JSON; } else { echo "error"; } /*include_once("conexion.php"); class medico { public $id; public $nombre; public $id_especialidad; public $foto; public function __construct ($id, $nombre,$id_especialidad, $foto){ $this->id = $id; $this->nombre = $nombre; $this->id_especialidad = $id_especialidad; $this->foto = $foto; } } $sql = "SELECT * FROM medico"; $res = $conexion->query($sql); $aux = $res->num_rows; if ($res->num_rows > 0) { while ($aux > 0) { $datos= $res->fetch_object(); $dat[]=$datos; $aux--; } $json=JSON_encode($dat); echo $json; }else { echo "error"; }*/ ?>
    true
    05237daf21ec12a0afa44941ca316c219e93a909
    PHP
    matthewdimatteo/ctrex
    /php/content/content-disclosures.php
    UTF-8
    1,887
    2.515625
    3
    []
    no_license
    <?php /* php/content/content-disclosures.php By Matthew DiMatteo, Children's Technology Review This is the content file for the disclosures page It is included dynamically in the file 'php/document.php' */ // PAGE HEADER if($disclosuresHeader != NULL) { echo '<div class = "page-header">'.$disclosuresHeader.'</div>'; } // PAGE BODY echo '<div class = "paragraph left bottom-10">'; // INTRO if($disclosuresIntro != NULL) { echo '<p>'.parseLinksOld($disclosuresIntro).'</p>'; } // SOURCES OF INCOME if(count($disclosuresIncomeItems > 0)) { echo '<p>'; for($i = 0; $i <= count($disclosuresIncomeItems); $i++) { $incomeItem = $disclosuresIncomeItems[$i]; $incomeDescription = $disclosuresIncomeDescriptions[$i]; if($incomeItem != NULL) { echo '<strong>'.$incomeItem.'</strong>'; if($incomeDescription != NULL) { echo parseLinksOld($incomeDescription); } echo '<br/>'; } // end if $incomeItem } // end for echo '</p>'; } // end if $disclosuresIncomeItems // ADVERTISING AND SPONSORSHIP RELATIONSHIPS if($disclosuresRelHeader == NULL) { $disclosuresRelHeader = 'ADVERTISING AND SPONSORSHIP RELATIONSHIPS<br/></br>In order to be a sponsor or underwriter (e.g., for research), the business partner must meet the following conditions:'; } // end if !$disclosuresRelHeader if(count($disclosuresRelItems) > 0) { echo '<ul>'; for($i = 0; $i <= count($disclosuresRelItems); $i++) { $thisRelItem = $disclosuredRelItems[$i]; if($thisRelItem != NULL) { echo '<li>'.parseLinksOld($thisRelItem).'</li>'; } } // end for echo '</ul>'; } // end if $disclosuresRelItems // CONCLUSION, DATE MODIFIED if($disclosuresConclusion != NULL) { echo '<p>'.parseLinksOld($disclosuresConclusion).'</p>'; } if($disclosuresDateModified != NULL) { echo 'Last update: '.$disclosuresDateModified; } echo '</div>'; // /.paragraph left bottom-10 ?>
    true
    51f033530f7c168b50dce06012c036d83587a4c7
    PHP
    ck6390/CMS
    /application/controllers/Attandance_bioMonth.php
    UTF-8
    8,002
    2.515625
    3
    [ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
    permissive
    <?php defined('BASEPATH') OR exit('No direct script access allowed'); /* * *****************Welcome.php********************************** * @product name : Global School Management System Pro * @type : Class * @class name : Welcome * @description : This is default class of the application. * @author : Codetroopers Team * @url : https://themeforest.net/user/codetroopers * @support : [email protected] * @copyright : Codetroopers Team * ********************************************************** */ class Attandance_bioMonth extends CI_Controller { /* * **************Function index********************************** * @type : Function * @function name : index * @description : this function load login view page * @param : null; * @return : null * ********************************************************** */ function __construct() { parent::__construct(); $this->load->model('Attandances_bio','m_bio_att'); } public function index() { $employee = $this->m_bio_att->get_bio_att_emp();//bio data // var_dump($employee); // die(); $curr_year = date('Y'); $curr_month = '08'; //$curr_month = date('m'); $curr_day = date('d'); foreach ($employee as $emp) { //$id_bio = ''; $sub_str = substr($emp->EmployeeCode, 0, 1); $id = substr($emp->EmployeeCode, 1); $em_id = $emp->EmployeeCode; //var_dump($sub_str); //die(); if($sub_str == '3'){ $type = 'employee'; $result_att = $this->m_bio_att->get_employee_lists($id); $condition = array( 'month' => $curr_month, 'year' => $curr_year, //'employee_id' =>'31011' 'employee_id' =>@$result_att->employee_id ); $data = $condition; if (!empty($result_att)) { $attendance = $this->m_bio_att->get_single_data($condition,$type); } $bio_att_year = date('Y'); $bio_att_month = date('m'); //$bio_att_month = '08'; $bio_att_day = date('d'); $today = date('Y-m-d'); $time = date("h:i:s a"); $no_of_days = cal_days_in_month(CAL_GREGORIAN, $bio_att_month,$bio_att_year); $attend = array(); for ($i=1; $no_of_days >= $i; $i++) { $attend[] = array('day'=>$i,'attendance'=>'','attendance_date'=>'','attendance_time'=>'','out_time'=>''); } if (empty($attendance)) { $data['employee_id'] = $result_att->employee_id; $data['status'] = '1'; $data['created_at'] = date('Y-m-d H:i:s'); $data['attendance_data'] = json_encode($attend); $this->m_bio_att->insert($data,$type); }else{ var_dump($attendance); $this->update_atten($em_id,$attendance,$condition,$type); } } } die(); echo "<h1 style='text-align:center;'>Employee Attendance Updated.</h1>"; } public function update_atten($em_id,$attendance,$condition,$type) { //var_dump($em_id); $result = $this->m_bio_att->get_bio_att($em_id);//bio data //$result = $this->m_bio_att->get_bio_att('31011'); //echo "<pre>"; //var_dump($result); // die(); $attendance_data = $attendance->attendance_data; $attendance_data_decode = json_decode($attendance_data); //var_dump($attendance_data_decode); $attend = array(); $today = date('Y-m-d'); /* if($em_id == @$result->UserId) //if($em_id == "31011") { //var_dump($result->LogDate); $bio_att_day = date('d',strtotime($result->LogDate)); $today = date('Y-m-d',strtotime($result->LogDate)); $time = date("h:i:sa",strtotime($result->LogDate)); $out_time = date("h:i:sa",strtotime($result->LogDate)); $status = "P"; //P for present var_dump($out_time); // die(); }else{ $bio_att_day = date('d'); $today = date('Y-m-d'); $time = ""; $status = "A"; //P for present } */ //echo "<PRe>"; //print_r($result); $attend_blank = array(); $no_of_days = 31; for ($i=1; $no_of_days >= $i; $i++) { if($i < 10){ $j = '0'.$i; }else{ $j = $i; } $today = date('Y-08-'.$j); $attend_blank[$today] = array('day'=>$i,'attendance'=>'A','attendance_date'=>$today,'attendance_time'=>'','out_time'=>''); } $dateArray = array(); if(!empty($result)){ foreach ($result as $key_res => $res) { $bio_att_day = date('d',strtotime($res->LogDate)); //if(empty($res->attendance_time)){ $today = date('Y-m-d',strtotime($res->LogDate)); $time = date("h:i:sa",strtotime($res->LogDate)); $out_time = date("h:i:sa",strtotime($res->LogDate)); $status = "P"; if(in_array($today, $dateArray)){ $tempArray = $attend[$today]; $attend[$today] = array('day'=>$tempArray['day'],'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$tempArray['attendance_time'],'out_time'=>$out_time); }else{ $attend[$today] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$time,'out_time'=>''); } $dateArray[$key_res]= $today; } } //echo "<PRe>"; //print_r($attend); //print_r($attend_blank); //$final_array = array_merge($attend,$attend_blank); foreach ($attend_blank as $key_blank => $blank) { if(array_key_exists($key_blank, $attend)){ $final_array[$key_blank] = $attend[$key_blank]; }else{ $final_array[$key_blank] = $blank; } } //print_r($final_array); echo $attendance_record = json_encode(array_values($final_array)); die; //*/var_dump($today); /*foreach ($attendance_data_decode as $att_data) { // var_dump($out_time); // die(); if($att_data->day == $bio_att_day){ /// for out time check 'attendance_time' if(empty($att_data->attendance_time)){ $attend[] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$time,'out_time'=>''); }else{ $attend[] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$att_data->attendance_time,'out_time'=>$out_time); } }else{ $attend[] = $att_data; } } $attendance_record = json_encode($attend); */ //var_dump($condition); //$this->m_bio_att->update_attandance($attendance_record,$time,$condition,$type); $em_id = substr($em_id, 1); // $data['attendance_data'] = json_encode($attend); $data['attendance_data'] = $attendance_record; $this->db->where('employee_id',$em_id); $this->db->where('month','08'); $this->db->where('year','2019'); $this->db->update('employee_attendances',$data); //$this->m_bio_att->update_attandance($data); //die; } }
    true
    0b216ed27db043f8f090cbd8e10d276b2660b494
    PHP
    StepanKovalenko/trustly-client-php
    /Trustly/Data/jsonrpcrequest.php
    UTF-8
    7,005
    2.8125
    3
    [ "Apache-2.0", "MIT" ]
    permissive
    <?php /** * Trustly_Data_JSONRPCRequest class. * * @license https://opensource.org/licenses/MIT * @copyright Copyright (c) 2014 Trustly Group AB */ /* The MIT License (MIT) * * Copyright (c) 2014 Trustly Group AB * * 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, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Class implementing the structure for data used in the signed API calls */ class Trustly_Data_JSONRPCRequest extends Trustly_Data_Request { /** * Constructor. * * @throws Trustly_DataException If the combination of $data and * $attributes is invalid * * @param string $method Outgoing call API method * * @param mixed $data Outputgoing call Data (if any). This can be either an * array or a simple non-complex value. * * @param mixed $attributes Outgoing call attributes if any. If attributes * is set then $data needs to be an array. */ public function __construct($method=NULL, $data=NULL, $attributes=NULL) { $payload = NULL; if(isset($data) || isset($attributes)) { $payload = array('params' => array()); if(isset($data)) { if(!is_array($data) && isset($attributes)) { throw new Trustly_DataException('Data must be array if attributes is provided'); } $payload['params']['Data'] = $data; } if(isset($attributes)) { if(!isset($payload['params']['Data'])) { $payload['params']['Data'] = array(); } $payload['params']['Data']['Attributes'] = $attributes; } } parent::__construct($method, $payload); if(isset($method)) { $this->payload['method'] = $method; } if(!isset($this->payload['params'])) { $this->payload['params'] = array(); } $this->set('version', '1.1'); } /** * Set a value in the params section of the request * * @param string $name Name of parameter * * @param mixed $value Value of parameter * * @return mixed $value */ public function setParam($name, $value) { $this->payload['params'][$name] = Trustly_Data::ensureUTF8($value); return $value; } /** * Get the value of a params parameter in the request * * @param string $name Name of parameter of which to obtain the value * * @return mixed The value */ public function getParam($name) { if(isset($this->payload['params'][$name])) { return $this->payload['params'][$name]; } return NULL; } /** * Pop the value of a params parameter in the request. I.e. get the value * and then remove the value from the params. * * @param string $name Name of parameter of which to obtain the value * * @return mixed The value */ public function popParam($name) { $v = NULL; if(isset($this->payload['params'][$name])) { $v = $this->payload['params'][$name]; } unset($this->payload['params'][$name]); return $v; } /** * Set the UUID value in the outgoing call. * * @param string $uuid The UUID * * @return string $uuid */ public function setUUID($uuid) { $this->payload['params']['UUID'] = Trustly_Data::ensureUTF8($uuid); return $uuid; } /** * Get the UUID value from the outgoing call. * * @return string The UUID value */ public function getUUID() { if(isset($this->payload['params']['UUID'])) { return $this->payload['params']['UUID']; } return NULL; } /** * Set the Method value in the outgoing call. * * @param string $method The name of the API method this call is for * * @return string $method */ public function setMethod($method) { return $this->set('method', $method); } /** * Get the Method value from the outgoing call. * * @return string The Method value. */ public function getMethod() { return $this->get('method'); } /** * Set a value in the params->Data part of the payload. * * @param string $name The name of the Data parameter to set * * @param mixed $value The value of the Data parameter to set * * @return mixed $value */ public function setData($name, $value) { if(!isset($this->payload['params']['Data'])) { $this->payload['params']['Data'] = array(); } $this->payload['params']['Data'][$name] = Trustly_Data::ensureUTF8($value); return $value; } /** * Get the value of one parameter in the params->Data section of the * request. Or the entire Data section if no name is given. * * @param string $name Name of the Data param to obtain. Leave as NULL to * get the entire structure. * * @return mixed The value or the entire Data depending on $name */ public function getData($name=NULL) { if(isset($name)) { if(isset($this->payload['params']['Data'][$name])) { return $this->payload['params']['Data'][$name]; } } else { if(isset($this->payload['params']['Data'])) { return $this->payload['params']['Data']; } } return NULL; } /** * Set a value in the params->Data->Attributes part of the payload. * * @param string $name The name of the Attributes parameter to set * * @param mixed $value The value of the Attributes parameter to set * * @return mixed $value */ public function setAttribute($name, $value) { if(!isset($this->payload['params']['Data'])) { $this->payload['params']['Data'] = array(); } if(!isset($this->payload['params']['Data']['Attributes'])) { $this->payload['params']['Data']['Attributes'] = array(); } $this->payload['params']['Data']['Attributes'][$name] = Trustly_Data::ensureUTF8($value); return $value; } /** * Get the value of one parameter in the params->Data->Attributes section * of the request. Or the entire Attributes section if no name is given. * * @param string $name Name of the Attributes param to obtain. Leave as NULL to * get the entire structure. * * @return mixed The value or the entire Attributes depending on $name */ public function getAttribute($name) { if(isset($this->payload['params']['Data']['Attributes'][$name])) { return $this->payload['params']['Data']['Attributes'][$name]; } return NULL; } } /* vim: set noet cindent sts=4 ts=4 sw=4: */
    true
    2838764f80fb96c99eac7279a5716585b7f97fcb
    PHP
    igorbunov/checkbox-in-ua-php-sdk
    /src/Models/CashRegisters/CashRegistersQueryParams.php
    UTF-8
    691
    2.75
    3
    [ "MIT" ]
    permissive
    <?php namespace igorbunov\Checkbox\Models\CashRegisters; class CashRegistersQueryParams { /** @var bool|null $inUse */ public $inUse; // null, true, false /** @var int $limit */ public $limit; /** @var int $offset */ public $offset; public function __construct( ?bool $inUse = null, int $limit = 25, int $offset = 0 ) { if ($offset < 0) { throw new \Exception('Offset cant be lower then 0'); } if ($limit > 1000) { throw new \Exception('Limit cant be more then 1000'); } $this->inUse = $inUse; $this->offset = $offset; $this->limit = $limit; } }
    true
    fdda5b5b4e22b9510ee83070887ccc9676e2bb32
    PHP
    thulioprado/api-next
    /src/Database/Collection.php
    UTF-8
    1,488
    2.890625
    3
    []
    no_license
    <?php declare(strict_types=1); namespace Directus\Database; use Directus\Contracts\Database\Collection as CollectionContract; use Directus\Contracts\Database\Database as DatabaseContract; use Illuminate\Database\Connection; use Illuminate\Database\Query\Builder; /** * Directus collection. */ class Collection implements CollectionContract { /** * @var string */ private $name; /** * @var string */ private $prefix; /** * @var Connection */ private $connection; /** * Constructor. */ public function __construct(DatabaseContract $database, string $name) { $this->name = $name; $this->prefix = $database->prefix(); /** @var Connection $connection */ $connection = $database->connection(); $this->connection = $connection; } public function name(): string { return $this->prefix.$this->name; } public function prefix(): string { return $this->prefix; } public function fullName(): string { return $this->connection->getTablePrefix().$this->prefix.$this->name; } public function builder(): Builder { return $this->connection->table($this->name()); } public function drop(): void { $this->connection->getSchemaBuilder()->drop($this->name()); } public function truncate(): void { $this->connection->table($this->name())->truncate(); } }
    true
    796efcedbc4ed92b5fc7cce81952ff86e2c0c1c7
    PHP
    ZED-Magdy/PHP-DDD-Blog-exapmle
    /src/Domain/Blog/Service/DeleteTagServiceInterface.php
    UTF-8
    359
    2.578125
    3
    []
    no_license
    <?php namespace App\Domain\Blog\Service; use App\Domain\Blog\Exception\TagNotFoundException; use App\Domain\Blog\ValueObject\TagId; interface DeleteTagServiceInterface { /** * Undocumented function * * @param TagId $tagId * @return void * @throws TagNotFoundException */ public function execute(TagId $tagId): void; }
    true
    595f53679ef82e20abefd4a77651a81910d4b5ff
    PHP
    NatashaAC/HTTP5203_Final_Project-Natasha_Chambers
    /views/breed_details.php
    UTF-8
    2,291
    2.578125
    3
    []
    no_license
    <?php // Grabbing the cat breed's name and accounting for spaces $url = 'https://api.thecatapi.com/v1/breeds/search?q=' . str_replace(' ', '%20', $_GET["name"]); $results = json_decode(file_get_contents($url)); $breed_name = $results[0]->name; $breed_alt_name = $results[0]->alt_names; $breed_image = $results[0]->image->url; $breed_des = $results[0]->description; $breed_temp = $results[0]->temperament; $breed_life_span = $results[0]->life_span; $breed_origin = $results[0]->origin; $breed_weight = $results[0]->weight->imperial; $wiki_page = $results[0]->wikipedia_url; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device=width, initial-scale=1" /> <meta name="description" content="A website for all cat lovers!"> <!-- Scripts --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script> <!-- Style Sheets --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <link rel="stylesheet" href="../css/main.css"> <title>Breeds</title> </head> <body> <?php require_once "shared/header.php"; ?> <main id="page"> <?php echo '<div class="container-fluid card detailCard"> <h1>' . $breed_name . '</h1> <h2>Alternate Names: ' . $breed_alt_name . '</h2> <div class="card-body"> <p>' . $breed_des . '</p> <p>This cat breed is from ' . $breed_origin . '</p> <p>Life Span: ' . $breed_life_span . ' years</p> <p>Weight: ' . $breed_weight . 'lb</p> <p>Temperament: ' . $breed_temp . '</p> <a class="btn btn-outline-info" href="' . $wiki_page . '">Checkout Wikipedia Page!</a> </div> </div>'; ?> </main> <?php include "shared/footer.php"; ?> </body> </html>
    true
    d762a3aa4e638b71e3fe5b5fbfc4ef4e39b18eea
    PHP
    30002731/6210-SCP
    /SCP Files/connection.php
    UTF-8
    479
    2.578125
    3
    []
    no_license
    <?php //Create Database credential variables $user = "a3000273_user"; $password = "Toiohomai1234"; $db = "a3000273_SCP_Files"; //Create php db connection object $connection = new mysqli("localhost", $user, $password, $db) or die(mysqli_error($connection)); //Get all data from table and save in a variable for use on our page application $result = $connection->query("select * from SCP_Subjects") or die($connection->error()); ?>
    true
    28e6a389df275333f7d793ac4f4c64bb54260622
    PHP
    vkabachenko/yii2-eer
    /common/models/Student.php
    UTF-8
    2,323
    2.6875
    3
    []
    no_license
    <?php namespace common\models; use Yii; /** * This is the model class for table "student". * * @property integer $id * @property string $name * @property string $email * * @property StudentEducation[] $studentEducations * @property StudentPortfolio[] $studentPortfolios */ class Student extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'student'; } /** * @inheritdoc */ public function rules() { return [ [['name','email'], 'required'], [['name'], 'string', 'max' => 100], [['email'], 'string', 'max' => 250], [['email'], 'email'], [['email'], 'unique'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'Фамилия Имя Отчество', 'email' => 'Email', ]; } /** * @return \yii\db\ActiveQuery */ public function getStudentEducations() { return $this->hasMany(StudentEducation::className(), ['id_student' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getStudentPortfolios() { return $this->hasMany(StudentPortfolio::className(), ['id_student' => 'id']); } /** * @inheritdoc */ public function beforeDelete() { /* * Удаляются все записи портфолио. * Поскольку модель Tree не поддерживает удаление корневых элементов, * для удаления не используется стандартный метод delete модели, а * используется DAO. */ if (parent::beforeDelete()) { /* * Сначала удаляются все файлы, связанные с портфолио, а затем все записи */ $models = $this->studentPortfolios; foreach ($models as $model) { $model->deleteFile(); } Yii::$app->db-> createCommand()-> delete('student_portfolio',['id_student' => $this->id])-> execute(); return true; } else { return false; } } }
    true
    cc5badccabbf19be1208393873734aed98301de5
    PHP
    michael158/vidafascinante
    /modules/Admin/Entities/User.php
    UTF-8
    2,324
    2.6875
    3
    [ "MIT" ]
    permissive
    <?php namespace Modules\Admin\Entities; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; use Illuminate\Support\Facades\DB; class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'image', 'description', 'admin','facebook','twitter', 'google_plus', 'instagram', 'youtube' ]; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function newUser($data) { DB::beginTransaction(); try { if (isset($data['image'])) { $mUpload = new Upload(); $data['image'] = !empty($data['image']) ? $mUpload->upload($data['image'], null, 'users'): null; } $data['password'] = bcrypt($data['password']); $post = $this->create($data); } catch (\Exception $e) { throw $e; DB::rollback(); } DB::commit(); return $post; } public function editUser($data , $user) { DB::beginTransaction(); try { if (isset($data['image'])) { $mUpload = new Upload(); $data['image'] = !empty($data['image']) ? $mUpload->upload($data['image'], null, 'users') : null; } if (!empty($data['password'])) { $data['password'] = bcrypt($data['password']); } else { unset($data['password']); } $post = $user->update($data); } catch (\Exception $e) { throw $e; DB::rollback(); } DB::commit(); return $post; } }
    true
    72e9b344591c4af0f9ecbb3d596a91a086bb3f08
    PHP
    i80586/RCache
    /tests/FileCacheTest.php
    UTF-8
    2,060
    2.703125
    3
    []
    no_license
    <?php use RCache\Cache; use RCache\FileCache; /** * FileCacheTest tests class * Test cache for file * * @author Rasim Ashurov <[email protected]> * @date 11 August, 2016 */ class FileCacheTest extends PHPUnit_Framework_TestCase { /** * @var RCache\Cache */ private $cache; /** * Init test */ public function setUp() { # create temporary directory for cache if ( ! is_dir($directory = __DIR__ . '/cache')) { mkdir($directory); } $this->cache = new Cache(new FileCache($directory)); } /** * Test set and get value */ public function testManually() { $this->cache->set('test-identifier', 'test-value', 120); # assert existing cache and equal value $this->assertEquals('test-value', $this->cache->get('test-identifier')); } /** * Test fragment cache */ public function testFragment() { # write content to cache if ($this->cache->start('test-fragment', 120)) { echo 'test-fragment-content'; $this->cache->end(); } # test fragment cache if ($this->cache->start('test-fragment', 120)) { $this->assertTrue(false); $this->cache->end(); } } /** * Test cache expire / duration */ public function testCacheExpire() { $this->cache->set('test-expire', 'test-value', 2); # assert existing cache $this->assertTrue($this->cache->has('test-expire')); sleep(3); # assert for expire cache $this->assertFalse($this->cache->has('test-expire')); } /** * Test deleting cache */ public function testDelete() { foreach (['test-identifier', 'test-fragment'] as $identifier) { $this->cache->drop($identifier); $this->assertFalse($this->cache->has($identifier)); } } }
    true
    68e3ff779db20c9b82f6faa6676467330781eafd
    PHP
    theolaye/symfony2
    /src/Entity/User.php
    UTF-8
    2,312
    2.53125
    3
    []
    no_license
    <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\UserRepository") */ class User { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $nomcomplet; /** * @ORM\Column(type="integer") */ private $telephone; /** * @ORM\Column(type="string", length=255) */ private $email; /** * @ORM\Column(type="string", length=255) */ private $adresse; /** * @ORM\ManyToOne(targetEntity="App\Entity\profil", inversedBy="users") * @ORM\JoinColumn(nullable=false) */ private $idprofil; /** * @ORM\ManyToOne(targetEntity="App\Entity\partenaire", inversedBy="users") * @ORM\JoinColumn(nullable=false) */ private $idpartenaire; public function getId(): ?int { return $this->id; } public function getNomcomplet(): ?string { return $this->nomcomplet; } public function setNomcomplet(string $nomcomplet): self { $this->nomcomplet = $nomcomplet; return $this; } public function getTelephone(): ?int { return $this->telephone; } public function setTelephone(int $telephone): self { $this->telephone = $telephone; return $this; } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): self { $this->email = $email; return $this; } public function getAdresse(): ?string { return $this->adresse; } public function setAdresse(string $adresse): self { $this->adresse = $adresse; return $this; } public function getIdprofil(): ?profil { return $this->idprofil; } public function setIdprofil(?profil $idprofil): self { $this->idprofil = $idprofil; return $this; } public function getIdpartenaire(): ?partenaire { return $this->idpartenaire; } public function setIdpartenaire(?partenaire $idpartenaire): self { $this->idpartenaire = $idpartenaire; return $this; } }
    true
    099d3679399b42c2ad53f082c008e8f4ada21ea7
    PHP
    pear/pear-core
    /PEAR/Command.php
    UTF-8
    12,395
    2.828125
    3
    [ "BSD-2-Clause" ]
    permissive
    <?php /** * PEAR_Command, command pattern class * * PHP versions 4 and 5 * * @category pear * @package PEAR * @author Stig Bakken <[email protected]> * @author Greg Beaver <[email protected]> * @copyright 1997-2009 The Authors * @license http://opensource.org/licenses/bsd-license.php New BSD License * @link http://pear.php.net/package/PEAR * @since File available since Release 0.1 */ /** * Needed for error handling */ require_once 'PEAR.php'; require_once 'PEAR/Frontend.php'; require_once 'PEAR/XMLParser.php'; /** * List of commands and what classes they are implemented in. * @var array command => implementing class */ $GLOBALS['_PEAR_Command_commandlist'] = array(); /** * List of commands and their descriptions * @var array command => description */ $GLOBALS['_PEAR_Command_commanddesc'] = array(); /** * List of shortcuts to common commands. * @var array shortcut => command */ $GLOBALS['_PEAR_Command_shortcuts'] = array(); /** * Array of command objects * @var array class => object */ $GLOBALS['_PEAR_Command_objects'] = array(); /** * PEAR command class, a simple factory class for administrative * commands. * * How to implement command classes: * * - The class must be called PEAR_Command_Nnn, installed in the * "PEAR/Common" subdir, with a method called getCommands() that * returns an array of the commands implemented by the class (see * PEAR/Command/Install.php for an example). * * - The class must implement a run() function that is called with three * params: * * (string) command name * (array) assoc array with options, freely defined by each * command, for example: * array('force' => true) * (array) list of the other parameters * * The run() function returns a PEAR_CommandResponse object. Use * these methods to get information: * * int getStatus() Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL) * *_PARTIAL means that you need to issue at least * one more command to complete the operation * (used for example for validation steps). * * string getMessage() Returns a message for the user. Remember, * no HTML or other interface-specific markup. * * If something unexpected happens, run() returns a PEAR error. * * - DON'T OUTPUT ANYTHING! Return text for output instead. * * - DON'T USE HTML! The text you return will be used from both Gtk, * web and command-line interfaces, so for now, keep everything to * plain text. * * - DON'T USE EXIT OR DIE! Always use pear errors. From static * classes do PEAR::raiseError(), from other classes do * $this->raiseError(). * @category pear * @package PEAR * @author Stig Bakken <[email protected]> * @author Greg Beaver <[email protected]> * @copyright 1997-2009 The Authors * @license http://opensource.org/licenses/bsd-license.php New BSD License * @version Release: @package_version@ * @link http://pear.php.net/package/PEAR * @since Class available since Release 0.1 */ class PEAR_Command { // {{{ factory() /** * Get the right object for executing a command. * * @param string $command The name of the command * @param object $config Instance of PEAR_Config object * * @return object the command object or a PEAR error */ public static function &factory($command, &$config) { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { $a = PEAR::raiseError("unknown command `$command'"); return $a; } $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; if (!class_exists($class)) { require_once $GLOBALS['_PEAR_Command_objects'][$class]; } if (!class_exists($class)) { $a = PEAR::raiseError("unknown command `$command'"); return $a; } $ui =& PEAR_Command::getFrontendObject(); $obj = new $class($ui, $config); return $obj; } // }}} // {{{ & getObject() public static function &getObject($command) { $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; if (!class_exists($class)) { require_once $GLOBALS['_PEAR_Command_objects'][$class]; } if (!class_exists($class)) { return PEAR::raiseError("unknown command `$command'"); } $ui =& PEAR_Command::getFrontendObject(); $config = &PEAR_Config::singleton(); $obj = new $class($ui, $config); return $obj; } // }}} // {{{ & getFrontendObject() /** * Get instance of frontend object. * * @return object|PEAR_Error */ public static function &getFrontendObject() { $a = &PEAR_Frontend::singleton(); return $a; } // }}} // {{{ & setFrontendClass() /** * Load current frontend class. * * @param string $uiclass Name of class implementing the frontend * * @return object the frontend object, or a PEAR error */ public static function &setFrontendClass($uiclass) { $a = &PEAR_Frontend::setFrontendClass($uiclass); return $a; } // }}} // {{{ setFrontendType() /** * Set current frontend. * * @param string $uitype Name of the frontend type (for example "CLI") * * @return object the frontend object, or a PEAR error */ public static function setFrontendType($uitype) { $uiclass = 'PEAR_Frontend_' . $uitype; return PEAR_Command::setFrontendClass($uiclass); } // }}} // {{{ registerCommands() /** * Scan through the Command directory looking for classes * and see what commands they implement. * * @param bool (optional) if FALSE (default), the new list of * commands should replace the current one. If TRUE, * new entries will be merged with old. * * @param string (optional) where (what directory) to look for * classes, defaults to the Command subdirectory of * the directory from where this file (__FILE__) is * included. * * @return bool TRUE on success, a PEAR error on failure */ public static function registerCommands($merge = false, $dir = null) { $parser = new PEAR_XMLParser; if ($dir === null) { $dir = dirname(__FILE__) . '/Command'; } if (!is_dir($dir)) { return PEAR::raiseError("registerCommands: opendir($dir) '$dir' does not exist or is not a directory"); } $dp = @opendir($dir); if (empty($dp)) { return PEAR::raiseError("registerCommands: opendir($dir) failed"); } if (!$merge) { $GLOBALS['_PEAR_Command_commandlist'] = array(); } while ($file = readdir($dp)) { if ($file[0] == '.' || substr($file, -4) != '.xml') { continue; } $f = substr($file, 0, -4); $class = "PEAR_Command_" . $f; // List of commands if (empty($GLOBALS['_PEAR_Command_objects'][$class])) { $GLOBALS['_PEAR_Command_objects'][$class] = "$dir/" . $f . '.php'; } $parser->parse(file_get_contents("$dir/$file")); $implements = $parser->getData(); foreach ($implements as $command => $desc) { if ($command == 'attribs') { continue; } if (isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { return PEAR::raiseError('Command "' . $command . '" already registered in ' . 'class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"'); } $GLOBALS['_PEAR_Command_commandlist'][$command] = $class; $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc['summary']; if (isset($desc['shortcut'])) { $shortcut = $desc['shortcut']; if (isset($GLOBALS['_PEAR_Command_shortcuts'][$shortcut])) { return PEAR::raiseError('Command shortcut "' . $shortcut . '" already ' . 'registered to command "' . $command . '" in class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"'); } $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command; } if (isset($desc['options']) && $desc['options']) { foreach ($desc['options'] as $oname => $option) { if (isset($option['shortopt']) && strlen($option['shortopt']) > 1) { return PEAR::raiseError('Option "' . $oname . '" short option "' . $option['shortopt'] . '" must be ' . 'only 1 character in Command "' . $command . '" in class "' . $class . '"'); } } } } } ksort($GLOBALS['_PEAR_Command_shortcuts']); ksort($GLOBALS['_PEAR_Command_commandlist']); @closedir($dp); return true; } // }}} // {{{ getCommands() /** * Get the list of currently supported commands, and what * classes implement them. * * @return array command => implementing class */ public static function getCommands() { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } return $GLOBALS['_PEAR_Command_commandlist']; } // }}} // {{{ getShortcuts() /** * Get the list of command shortcuts. * * @return array shortcut => command */ public static function getShortcuts() { if (empty($GLOBALS['_PEAR_Command_shortcuts'])) { PEAR_Command::registerCommands(); } return $GLOBALS['_PEAR_Command_shortcuts']; } // }}} // {{{ getGetoptArgs() /** * Compiles arguments for getopt. * * @param string $command command to get optstring for * @param string $short_args (reference) short getopt format * @param array $long_args (reference) long getopt format * * @return void */ public static function getGetoptArgs($command, &$short_args, &$long_args) { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { return null; } $obj = &PEAR_Command::getObject($command); return $obj->getGetoptArgs($command, $short_args, $long_args); } // }}} // {{{ getDescription() /** * Get description for a command. * * @param string $command Name of the command * * @return string command description */ public static function getDescription($command) { if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) { return null; } return $GLOBALS['_PEAR_Command_commanddesc'][$command]; } // }}} // {{{ getHelp() /** * Get help for command. * * @param string $command Name of the command to return help for */ public static function getHelp($command) { $cmds = PEAR_Command::getCommands(); if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (isset($cmds[$command])) { $obj = &PEAR_Command::getObject($command); return $obj->getHelp($command); } return false; } // }}} }
    true
    7cd4bfa1eb3937b09d14801840dc3fb9b94611f2
    PHP
    toanht15/moni
    /apps/classes/brandco/cp/CpInstantWinActionManager.php
    UTF-8
    9,745
    2.5625
    3
    []
    no_license
    <?php AAFW::import('jp.aainc.lib.base.aafwObject'); AAFW::import('jp.aainc.classes.entities.CpAction'); AAFW::import('jp.aainc.classes.services.CpTransactionService'); AAFW::import('jp.aainc.classes.services.instant_win.InstantWinPrizeService'); AAFW::import('jp.aainc.classes.brandco.cp.interface.CpActionManager'); AAFW::import('jp.aainc.classes.brandco.cp.trait.CpActionTrait'); use Michelf\Markdown; /** * Class CpInstantWinActionManager * TODO トランザクション */ class CpInstantWinActionManager extends aafwObject implements CpActionManager { use CpActionTrait; /** @var CpInstantWinActions $cp_concrete_actions */ protected $cp_concrete_actions; /** @var CpTransactionService $cp_transaction_service */ protected $cp_transaction_service; /** @var InstantWinPrizeService $instant_win_prize_service */ protected $instant_win_prize_service; protected $logger; const LOGIC_TYPE_RATE = 1; const LOGIC_TYPE_TIME = 2; function __construct() { parent::__construct(); $this->cp_actions = $this->getModel("CpActions"); $this->cp_concrete_actions = $this->getModel("CpInstantWinActions"); $this->cp_transaction_service = $this->getService('CpTransactionService'); $this->instant_win_prize_service = $this->getService('InstantWinPrizeService'); $this->logger = aafwLog4phpLogger::getDefaultLogger(); } /** * @param $cp_action_id * @return mixed */ public function getCpActions($cp_action_id) { $cp_action = $this->getCpActionById($cp_action_id); if ($cp_action === null) { $cp_concrete_action = null; } else { $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action); } if($cp_concrete_action == null) { $instant_win_prizes = null; } else { $instant_win_prizes = $this->instant_win_prize_service->getInstantWinPrizesByCpInstantWinActionId($cp_concrete_action->id); } return array($cp_action, $cp_concrete_action, $instant_win_prizes); } /** * @param $cp_action_group_id * @param $type * @param $status * @param $order_no * @return array|mixed */ public function createCpActions($cp_action_group_id, $type, $status, $order_no) { $cp_action = $this->createCpAction($cp_action_group_id, $type, $status, $order_no); $cp_concrete_action = $this->createConcreteAction($cp_action); $this->cp_transaction_service->createCpTransaction($cp_action->id); $this->instant_win_prize_service->createInitInstantWinPrizes($cp_concrete_action->id); return array($cp_action, $cp_concrete_action); } /** * @param CpAction $cp_action * @return mixed|void */ public function deleteCpActions(CpAction $cp_action) { $this->cp_transaction_service->deleteCpTransaction($cp_action->id); $this->deleteConcreteAction($cp_action); $this->deleteCpAction($cp_action); } /** * @param CpAction $cp_action * @param $data * @return mixed|void */ public function updateCpActions(CpAction $cp_action, $data) { $this->updateCpAction($cp_action); $cp_concrete_action = $this->updateConcreteAction($cp_action, $data); $this->instant_win_prize_service->updateInstantWinPrizes($cp_concrete_action->id, $data); } /** * @param CpAction $cp_action * @return mixed */ public function getConcreteAction(CpAction $cp_action) { return $this->getCpConcreteActionByCpAction($cp_action); } /** * @param CpAction $cp_action * @return mixed */ public function createConcreteAction(CpAction $cp_action) { $cp_concrete_action = $this->cp_concrete_actions->createEmptyObject(); $cp_concrete_action->cp_action_id = $cp_action->id; $cp_concrete_action->title = "スピードくじ"; $cp_concrete_action->text = ""; $cp_concrete_action->time_value = 1; $cp_concrete_action->time_measurement = CpInstantWinActions::TIME_MEASUREMENT_DAY; $cp_concrete_action->logic_type = CpInstantWinActions::LOGIC_TYPE_RATE; $cp_concrete_action->once_flg = InstantWinPrizes::ONCE_FLG_ON; $this->cp_concrete_actions->save($cp_concrete_action); return $cp_concrete_action; } /** * @param CpAction $cp_action * @param $data * @return mixed|void */ public function updateConcreteAction(CpAction $cp_action, $data) { $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action); $cp_concrete_action->title = $data['title']; $cp_concrete_action->text = $data['text']; $cp_concrete_action->html_content = Markdown::defaultTransform($data['text']); $cp_concrete_action->time_value = $data['time_value']; $cp_concrete_action->time_measurement = $data['time_measurement']; $cp_concrete_action->once_flg = $data['once_flg']; $cp_concrete_action->logic_type = $data['logic_type']; $this->cp_concrete_actions->save($cp_concrete_action); return $cp_concrete_action; } /** * @param CpAction $cp_action * @return mixed|void */ public function deleteConcreteAction(CpAction $cp_action) { $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action); $cp_concrete_action->del_flg = 1; $this->cp_concrete_actions->save($cp_concrete_action); } /** * @param CpAction $old_cp_action * @param $new_cp_action_id * @return mixed|void */ public function copyConcreteAction(CpAction $old_cp_action, $new_cp_action_id) { $old_concrete_action = $this->getConcreteAction($old_cp_action); $new_concrete_action = $this->cp_concrete_actions->createEmptyObject(); $new_concrete_action->cp_action_id = $new_cp_action_id; $new_concrete_action->title = $old_concrete_action->title; $new_concrete_action->text = $old_concrete_action->text; $new_concrete_action->html_content = $old_concrete_action->html_content; $new_concrete_action->time_value = $old_concrete_action->time_value; $new_concrete_action->time_measurement = $old_concrete_action->time_measurement; $new_concrete_action->once_flg = $old_concrete_action->once_flg; $new_concrete_action->logic_type = $old_concrete_action->logic_type; $new_cp_instant_win_action = $this->cp_concrete_actions->save($new_concrete_action); $this->cp_transaction_service->createCpTransaction($new_cp_action_id); $this->instant_win_prize_service->copyInstantWinPrizes($new_cp_instant_win_action->id, $old_concrete_action->id); } /** * @param CpAction $cp_action * @return entity */ private function getCpConcreteActionByCpAction(CpAction $cp_action) { return $this->cp_concrete_actions->findOne(array("cp_action_id" => $cp_action->id)); } /** * @param $cp_action_id * @return entity */ public function getCpConcreteActionByCpActionId($cp_action_id) { return $this->cp_concrete_actions->findOne(array("cp_action_id" => $cp_action_id)); } /** * 次回参加までの待機時間を変換する * @param $cp_concrete_action * @return string */ public function changeValueIntoTime($cp_concrete_action) { if ($cp_concrete_action->time_measurement == CpInstantWinActions::TIME_MEASUREMENT_MINUTE) { $waiting_time = '+' . $cp_concrete_action->time_value . ' minutes'; } elseif ($cp_concrete_action->time_measurement == CpInstantWinActions::TIME_MEASUREMENT_HOUR) { $waiting_time = '+' . $cp_concrete_action->time_value . ' hours'; } else { $waiting_time = '+' . $cp_concrete_action->time_value . ' days'; } return $waiting_time; } /** * @param CpAction $cp_action * @return mixed|void */ public function deletePhysicalRelatedCpActionData(CpAction $cp_action, $with_concrete_actions = false) { if (!$cp_action || !$cp_action->id) { throw new Exception("CpInstantWinActionManager#deletePhysicalRelatedCpActionData cp_action_id=" . $cp_action->id); } if ($with_concrete_actions) { //TODO delete concrete action } //delete instant win action user log /** @var InstantWinUserService $instant_win_user_service */ $instant_win_user_service = $this->getService("InstantWinUserService"); $instant_win_user_service->deletePhysicalUserLogsByCpActionId($cp_action->id); // 当選予定時刻か初期化 $cp_concrete_action = $this->getConcreteAction($cp_action); $instant_win_prize = $this->instant_win_prize_service->getInstantWinPrizeByPrizeStatus($cp_concrete_action->id, InstantWinPrizes::PRIZE_STATUS_PASS); $this->instant_win_prize_service->resetInstantWinTime($instant_win_prize); } public function deletePhysicalRelatedCpActionDataByCpUser(CpAction $cp_action, CpUser $cp_user) { if (!$cp_action || !$cp_user) { throw new Exception("CpInstantWinActionManager#deletePhysicalRelatedCpActionDataByCpUser cp_action_id=" . $cp_action->id); } /** @var InstantWinUserService $instant_win_user_service */ $instant_win_user_service = $this->getService("InstantWinUserService"); $instant_win_user_service->deletePhysicalUserLogsByCpActionIdAndCpUserId($cp_action->id, $cp_user->id); } }
    true
    175d34f6241c51d1532d4c12e74fc164b1bee943
    PHP
    nam-duc-tong/ban_hang_hoa_qua_PHP
    /admin/product/add.php
    UTF-8
    7,054
    2.5625
    3
    []
    no_license
    <?php require_once('../../db/dbhelper.php'); $id = $title = $thumbnail = $content = $id_category = $price =''; if(!empty($_POST)){ if(isset($_POST['title'])){ $title = $_POST['title']; $title = str_replace('"', '\\"', $title); } if(isset($_POST['id'])){ $id = $_POST['id']; // $id = str_replace('"', '\\"', $id); } if(isset($_POST['price'])){ $price = $_POST['price']; $price = str_replace('"', '\\"', $price); } if(isset($_POST['thumbnail'])){ $thumbnail = $_POST['thumbnail']; $thumbnail = str_replace('"', '\\"', $thumbnail); } if(isset($_POST['content'])){ $content = $_POST['content']; $content = str_replace('"', '\\"', $content); } if(isset($_POST['id_category'])){ $id_category = $_POST['id_category']; $id_category = str_replace('"', '\\"', $id_category); } if(!empty($title)){ $created_at = $updated_at =date('Y-m-d H:s:i'); //luu vao database if($id == ''){ $sql = 'insert into product(title,thumbnail,price,content,id_category,created_at,updated_at) values ("'.$title.'","'.$thumbnail.'","'.$price.'","'.$content.'","'.$id_category.'","'.$created_at.'","'.$updated_at.'")'; } else{ $sql = 'update product set title = "'.$title.'",updated_at="'.$updated_at.'",thumbnail="'.$thumbnail.'",price = "'.$price.'",content = "'.$content.'",id_category="'.$id_category.'" where id = '.$id; } execute($sql); header('Location: index.php'); die(); } } if(isset($_GET['id'])){ $id = $_GET['id']; $sql = 'select * from product where id = '.$id; $product = executeSingleResult($sql); if($product != null){ $title = $product['title']; $price = $product['price']; $thumbnail = $product['thumbnail']; $id_category = $product['id_category']; $content = $product['content']; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Thêm sửa sản phẩm</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <!-- summernote --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote.min.js"></script> <style> thead tr td{ font-weight: bold; } </style> </head> <body> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link" href="../category/"> Quản Lý Danh Mục </a> </li> <li class="nav-item"> <a class="nav-link" href="index.php"> Quản Lý Sản Phẩm </a> </li> </ul> <div class="container"> <div class="panel panel-primary"> <div class="panel-heading" style= "font-weight: bold; margin-bottom:10px;"> <h2 class="text-center">Thêm/Sửa Sản Phẩm</h2> </div> <div class="panel-body"> <form method="post"> <div class="form-group"> <label for="name">Tên Sản Phẩm:</label> <input type="text" name="id" value="<?=$id?>" hidden="true"> <input required = "true" type="text" class="form-control" id="title" name="title" value="<?=$title?>"> </div> <div class="form-group"> <label for="price">Chọn Danh Mục:</label> <select class="form-control" name="id_category" id="id_category"> <option>--Lua chon danh muc--</option> <?php $sql = 'select * from category'; $categoryList = executeResult($sql); foreach($categoryList as $item){ if($item['id'] == $id_category){ echo '<option selected value="'.$item['id'].'">'.$item['name'].'</option>'; } else{ echo '<option value="'.$item['id'].'">'.$item['name'].'</option>'; } } ?> </select> </div> <div class="form-group"> <label for="price">Giá Bán:</label> <input required = "true" type="number" class="form-control" id="price" name="price" value="<?=$price?>"> </div> <div class="form-group"> <label for="thumbnail">Thumbnail:</label> <input required = "true" type="text" class="form-control" id="thumbnail" name="thumbnail" value="<?=$thumbnail?>" onchange="updateThumbnail()"> <img src="<?=$thumbnail?>"style="max-width:200px" id="img_thumbnail"> </div> <div class="form-group"> <label for="content">Nội Dung:</label> <textarea class = "form-control" name="content" id="content"rows="5"><?=$price?></textarea> </div> <button class="btn btn-success">Lưu</button> </form> </div> </div> </div> <script type="text/javascript"> function updateThumbnail(){ $('#img_thumbnail').attr('src', $('#thumbnail').val()) } $(function(){ $('#content').summernote({ height: 300, // set editor height minHeight: null, // set minimum height of editor maxHeight: null, // set maximum height of editor // focus: true // set focus to editable area after initializing summernote }); }) </script> </body> </html>
    true
    47cd3e734204dda7140c70f05d31f04dd11f3a81
    PHP
    renanfvcunha/devsbook
    /src/controllers/LoginController.php
    UTF-8
    4,139
    3.015625
    3
    []
    no_license
    <?php namespace src\controllers; use core\Controller; use src\handlers\LoginHandler; use src\handlers\ValidatorsHandler; use src\models\User; /** * Classe que lida com autenticação e * cadastro de usuários */ class LoginController extends Controller { private $loggedUser; /** * Renderização de tela para efetuar login */ public function SignInRequest() { $this->loggedUser = LoginHandler::checkLoggedUser(); if ($this->loggedUser) { $this->redirect(''); } $this->render('signin'); } /** * Efetuar Login */ public function SignInAction() { $data = json_decode(file_get_contents('php://input')); $email = filter_var($data->email, FILTER_VALIDATE_EMAIL); $password = filter_var($data->password, FILTER_SANITIZE_STRING); // Validando inputs if (!$email || !$password) { http_response_code(400); echo json_encode([ "error" => "Verifique se preencheu corretamente todos os campos.", ]); exit(); } // Verificando dados para autenticação try { $token = LoginHandler::verifyLogin($email, $password); if (!$token) { http_response_code(401); echo json_encode([ "error" => "E-mail e/ou Senha Incorreto(s).", ]); exit(); } // Autenticando usuário e atribuindo token $_SESSION['token'] = $token; } catch (\Throwable $th) { http_response_code(500); echo json_encode([ "error" => "Erro interno do servidor. Tente novamente ou contate o suporte.", ]); $this->setErrorLog($th); exit(); } } /** * Renderização de tela para * cadastro de novo usuário */ public function SignUpRequest() { $this->loggedUser = LoginHandler::checkLoggedUser(); if ($this->loggedUser) { $this->redirect(''); } $this->render('signup'); } /** * Cadastro de novo usuário */ public function SignUpAction() { $data = json_decode(file_get_contents('php://input')); $name = filter_var($data->name, FILTER_SANITIZE_FULL_SPECIAL_CHARS); $email = filter_var($data->email, FILTER_VALIDATE_EMAIL); $password = filter_var($data->password, FILTER_SANITIZE_STRING); $birthdate = filter_var($data->birthdate, FILTER_SANITIZE_STRING); // Verificando campos obrigatórios if (!$name || !$email || !$password || !$birthdate) { http_response_code(400); echo json_encode([ "error" => "Verifique se preencheu corretamente todos os campos.", ]); exit(); } // Validando campo birthdate $birthdate = ValidatorsHandler::birthdateValidator($birthdate); if (!$birthdate) { http_response_code(400); echo json_encode(["error" => "Data informada é inválida."]); exit(); } try { // Verificando duplicidade if (User::emailExists($email)) { http_response_code(400); echo json_encode([ "error" => "E-mail informado já está cadastrado.", ]); exit(); } // Cadastrando e autenticando usuário $token = User::addUser($name, $email, $password, $birthdate); $_SESSION['token'] = $token; } catch (\Throwable $th) { http_response_code(500); echo json_encode([ "error" => "Erro interno do servidor. Tente novamente ou contate o suporte.", ]); $this->setErrorLog($th); exit(); } } public function SignOut() { $_SESSION['token'] = ''; $this->redirect(''); } }
    true
    d078eed7cea7803640fed404b61e88c41759de3d
    PHP
    cenpaul07/test_app_laracast
    /app/Http/Controllers/PaymentsController.php
    UTF-8
    1,049
    2.5625
    3
    [ "MIT" ]
    permissive
    <?php namespace App\Http\Controllers; use App\Events\ProductPurchased; use App\Notifications\PaymentReceived; use Illuminate\Support\Facades\Notification; class PaymentsController extends Controller { public function create() { return view('payment.create'); } public function store() { /*TODO: Core Logic : 1. Payment Processing 2. Unlocking Purchase Side Effects: 3. Notifying User 4. Generating rewards 5.Sending Shareable Coupons Example: Event = ProductPurchased , Listeners = Notifying User,Generating rewards, Sending Shareable Coupons */ //Notification::send(request()->user(),new PaymentReceived()); //use this syntax for multiple users // request()->user()->notify(new PaymentReceived('5$')); //better and readable syntax for single users ProductPurchased::dispatch('toy');//or event(new ProductPurchased('toy')); // return redirect(route('payment.create')) // ->with('message','User Notified Successfully.'); } }
    true
    39747dfb2595bb13b4eac616a82a09e9ee9fc32d
    PHP
    ThomasWeinert/carica-firmata
    /src/Response/SysEx/PinStateResponse.php
    UTF-8
    1,453
    2.75
    3
    [ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
    permissive
    <?php namespace Carica\Firmata\Response\SysEx { use Carica\Firmata; /** * @property-read int $pin * @property-read int $mode * @property-read int $value */ class PinStateResponse extends Firmata\Response { /** * @var int */ private $_pin; /** * @var int */ private $_mode; /** * @var int */ private $_value; private $_modes = [ 0x01 => Firmata\Pin::MODE_OUTPUT, 0x00 => Firmata\Pin::MODE_INPUT, 0x02 => Firmata\Pin::MODE_ANALOG, 0x03 => Firmata\Pin::MODE_PWM, 0x04 => Firmata\Pin::MODE_SERVO, 0x05 => Firmata\Pin::MODE_SHIFT, 0x06 => Firmata\Pin::MODE_I2C ]; /** * @param array $bytes */ public function __construct(array $bytes) { parent::__construct(Firmata\Board::PIN_STATE_RESPONSE, $bytes); $length = count($bytes); $this->_pin = $bytes[0]; $this->_mode = $this->_modes[$bytes[1]] ?? FALSE; $this->_value = $bytes[2]; for ($i = 3, $shift = 7; $i < $length; ++$i, $shift *= 2) { $this->_value |= ($bytes[$i] << $shift); } } /** * @param string $name * @return int */ public function __get($name) { switch ($name) { case 'pin' : return $this->_pin; case 'mode' : return $this->_mode; case 'value' : return $this->_value; } return parent::__get($name); } } }
    true
    303a3ad434f7cf18fdab30209304776becb53670
    PHP
    alphachoi/duobaohui
    /package/search/SearchObject.class.php
    UTF-8
    8,428
    2.875
    3
    []
    no_license
    <?php namespace Snake\Package\Search; /** * 对search操作封装的一个文件 * @author [email protected] * @version alpha */ class SearchObject extends Search{ private $sphinxClient = NULL; private $limit = array(); private $filters = array(); private $filterRanges = array(); private $filterFloatRanges = array(); private $sortMode = SPH_SORT_RELEVANCE; private $sortBy = ''; private $index = ''; private $matchMode = SPH_MATCH_ANY; private $searchResult = array(); private $maxQueryTime = 4000; private $searchType = "normal"; private $useCache = FALSE; private $keywords = ''; const max = 12000; const daysFilter = 201; function __construct($searchType = "normal") { parent::__construct(); $this->searchType = $searchType; if ($searchType == "cpc") { $this->sphinxClient = parent::_getSecondSphinxClient(); } else { $this->sphinxClient = parent::_getSphinxClient(); } } public function __tostring() { //排序 uasort($this->filters, array($this, "cmp")); uasort($this->filterRanges, array($this, "cmp")); uasort($this->filterFloatRanges, array($this, "cmp")); $filtersString = print_r($this->filters, TRUE); $filterRangesString = print_r($this->filterRanges, TRUE); $filterFloatRangesString = print_r($this->filterFloatRanges, TRUE); $keywordsString = print_r($this->keywords, TRUE); $limitString = print_r($this->limit, TRUE); $key = "filters:{$filtersString}_filterRanges:{$filterRangesString}_filterFloatRanges:{$filterFloatRangesString}_keyWords:{$keywordsString}_limit:{$limitString}"; return $key; } public function cmp($a, $b) { $bigger = 0; if ($a['attribute'] > $b['attribute']) { $bigger = 1; } else if ($a['attribute'] === $b['attribute']) { $bigger = 0; } else { $bigger = -1; } return $bigger; } /** * 调用获取SearchObject * @author [email protected] */ // static public function getSearchClient() { // return new SearchObject(); // } /** * 设置limit * @author [email protected] */ public function setLimit($offset, $limit, $maxMatches = 12000, $cutoff = 0) { if ($limit <= 0) { $limit = 1; } $newLimit = array( 'offset' => $offset, 'limit' => $limit, 'maxMatches' => $maxMatches, 'cutoff' => $cutoff ); $this->limit = $newLimit; return TRUE; } /** * 设置过滤条件,搜索出values中指定的内容 * @author [email protected] * @param string attribute * @param array values * @param bool exclude */ public function setFilter($attribute, $values, $exclude = false) { if (empty($attribute)) { return FALSE; } $filter = array('attribute' => $attribute, 'values' => $values, 'exclude' => $exclude); array_push($this->filters, $filter); return TRUE; } /** * 设置过滤条件,搜索出min,max中指定的范围 * @author [email protected] * @param string attribute * @param int min * @param int max * @param bool exclude */ public function setFilterRange($attribute, $min, $max, $exclude = false) { if (empty($attribute)) { return FALSE; } $filterRange = array('attribute' => $attribute, 'min' => intval($min), 'max' => intval($max), 'exclude' => $exclude); array_push($this->filterRanges, $filterRange); return TRUE; } /** * 设置过滤条件,搜索出min,max中指定的范围 * @author [email protected] * @param string attribute * @param float min * @param float max * @param bool exclude */ public function setFilterFloatRange($attribute, $min, $max, $exclude = false) { if (empty($attribute)) { return FALSE; } $filterFloatRange = array('attribute' => $attribute, 'min' => (float)$min, 'max' => (float)$max, 'exclude' => $exclude); array_push($this->filterFloatRanges, $filterFloatRange); return TRUE; } /** * 设置排序模式,详见文档 * @author [email protected] * @param NULL define in API * @param string sortBy */ public function setSortMode($mode, $sortBy) { if (empty($mode)) { return FALSE; } $this->sortMode = $mode; $this->sortBy = $sortBy; return TRUE; } /** * SetMatchMode * */ public function setMatchMode($matchMode) { if (empty($matchMode)) { return FALSE; } $this->matchMode = $matchMode; return TRUE; } /** * 设置所用的搜索索引 * @param string */ public function setIndex($index) { if (empty($index)) { return FALSE; } $this->index = $index; return TRUE; } public function setMaxQueryTime($maxQueryTime) { $this->maxQueryTime = $maxQueryTime; return TRUE; } public function setUseCache($useCache = TRUE) { $this->useCache = $useCache; return TRUE; } /** * 开始搜索 * @author [email protected] * @param keywords */ public function search($keywords) { $this->keywords = $keywords; $this->conditionLoad(); if ($this->useCache) { $result = $this->searchFromCache($this); if (empty($result['matches'])) { $result = $this->searchFromSphinx($keywords, $this->index); $this->putSearchResultIntoCache($result); } } else { $result = $this->searchFromSphinx($keywords, $this->index); } $this->searchResult = $result; return TRUE; } private function searchFromCache($searchObject) { $searchResult = SearchCache::getSearch($this); return $searchResult; } private function putSearchResultIntoCache($searchResult) { $bool = SearchCache::setSearch($this, $searchResult); return $bool; } private function searchFromSphinx($keywords, $index) { if ($this->searchType == 'cpc') { $result = parent::secondQueryViaValidConnection($keywords, $index); } else { $result = parent::queryViaValidConnection($keywords, $index); } return $result; } public function getSearchResult() { return $this->searchResult; } public function conditionLoad() { $this->conditionReset(); $this->maxQueryTimeLoad(); $this->limitLoad(); $this->filtersLoad(); $this->filterRangeLoad(); $this->filterFloatRangesLoad(); $this->sortModeLoad(); $this->matchModeLoad(); return TRUE; } public function resetFilters() { $this->sphinxClient->ResetFilters(); $this->filters = array(); $this->filterRanges = array(); $this->filterFloatRanges = array(); return TRUE; } /** * TODO 加入limit reset */ private function conditionReset() { $this->sphinxClient->ResetFilters(); return TRUE; } private function maxQueryTimeLoad() { $this->sphinxClient->SetMaxQueryTime($this->maxQueryTime); return TRUE; } private function matchModeLoad() { $this->sphinxClient->SetMatchMode($this->matchMode); return TRUE; } private function sortModeLoad() { $this->sphinxClient->SetSortMode($this->sortMode, $this->sortBy); return TRUE; } private function limitLoad() { if (empty($this->limit)) { return FALSE; } if(!empty($this->limit) && !isset($this->limit['maxMatches'])) { $this->limit['maxMatches'] = self::max; } $this->sphinxClient->SetLimits($this->limit['offset'], $this->limit['limit'], $this->limit['maxMatches'], $this->limit['cutoff']); return TRUE; } private function filtersLoad() { foreach ($this->filters as $filter) { $this->sphinxClient->SetFilter($filter['attribute'], $filter['values'], $filter['exclude']); } return TRUE; } private function filterRangeLoad() { foreach ($this->filterRanges as $filterRange) { $this->sphinxClient->SetFilterRange($filterRange['attribute'], $filterRange['min'], $filterRange['max'], $filterRange['exclude']); } return TRUE; } private function filterFloatRangesLoad() { foreach ($this->filterFloatRanges as $filterFloatRange) { $this->sphinxClient->SetFilterFloatRange($filterFloatRange['attribute'], $filterFloatRange['min'], $filterFloatRange['max'], $filterFloatRange['exclude']); } return TRUE; } public function getSearchString($wordParams) { if (empty($wordParams['word_id']) && empty($wordParams['word_name'])) { return FALSE; } $params = array(); $params['word_name'] = $wordName; $params['isuse'] = 1; $wordInfo = AttrWords::getWordInfo($params, "/*searchGoods-zx*/word_id,word_name"); if (!empty($wordInfo)) { $searchKeyArr = AttrWords::getSearchString($wordInfo[0]['word_id'], $wordName); } else{ $searchKeyArr = array("{$wordName}"); } $searchString = "(" . implode(")|(", $searchKeyArr) . ")"; $this->searchString = $searchString; return $searchString; } public function getIndex() { return $this->index; } }
    true
    2ca7813263dcaa8a2153b1fab5cb8140b34671f8
    PHP
    apuc/guild
    /frontend/modules/api/controllers/TaskUserController.php
    UTF-8
    1,514
    2.546875
    3
    [ "BSD-3-Clause" ]
    permissive
    <?php namespace frontend\modules\api\controllers; use common\models\ProjectTaskUser; use Yii; use yii\filters\auth\HttpBearerAuth; use yii\rest\Controller; use yii\web\BadRequestHttpException; use yii\web\NotFoundHttpException; class TaskUserController extends ApiController { public function verbs(): array { return [ 'get-task-users' => ['get'], 'set-task-user' => ['post', 'patch'], ]; } public function actionSetTaskUser() { $taskUserModel = new ProjectTaskUser(); $params = Yii::$app->request->post(); $taskUserModel->attributes = $params; if(!$taskUserModel->validate()){ throw new BadRequestHttpException(json_encode($taskUserModel->errors)); } $taskUserModel->save(); return $taskUserModel->toArray(); } /** * @throws NotFoundHttpException */ public function actionGetTaskUsers() { $task_id = Yii::$app->request->get('task_id'); if(empty($task_id) or !is_numeric($task_id)) { throw new NotFoundHttpException('Incorrect task ID'); } $tasks = $this->findUsers($task_id); if(empty($tasks)) { throw new NotFoundHttpException('The task does not exist or there are no employees for it'); } return $tasks; } private function findUsers($project_id): array { return ProjectTaskUser::find()->where(['task_id' => $project_id])->all(); } }
    true
    f444ca26f7fba9c771148a778c341f5295a4c87b
    PHP
    nxsaloj/miudl
    /app/miudl/Carrera/CarreraValidator.php
    UTF-8
    2,742
    2.65625
    3
    [ "MIT" ]
    permissive
    <?php namespace miudl\Carrera; use Validator; class CarreraValidator implements CarreraValidatorInterface { protected $mensajes = array( 'Nombre.required' => 'El campo Nombre no debe estar vacío', 'Apellidos.required' => 'El campo Apellidos no debe estar vacío', 'Ciclos.required' => 'El campo Ciclo no debe estar vacío', 'Facultad_id.required' => 'El campo Facultad no debe estar vacío', 'Codigo.required' => 'El campo Codigo no debe estar vacío', 'Codigo.unique' => 'El codigo especificado ya ha sido utilizado anteriormente', ); public function isValid(array $params= array()) { $reglas = array( 'Codigo' => 'required|unique:TB_Carrera', 'Nombre' => 'required', 'Ciclos'=>'required', 'Facultad_id' => 'required' ); //\Log::debug('Puesto P ' . print_r($params['facultad'], true)); //$facultad = \App\Models\Utils::getVueParam($params,"facultad","Facultad_id"); //\Log::debug('Puesto ' . $facultad); $datos = array( 'Codigo' => $params['codigo'], 'Nombre' => $params['nombre'], 'Ciclos' => $params['ciclos'], 'Facultad_id' => isset($params['facultad'])? $params['facultad']:null, ); $validator = Validator::make($datos, $reglas, $this->mensajes); if ($validator->fails()){ $respuesta['mensaje'] = 'Por favor verifique los datos ingresados'; $respuesta['errors'] = $validator; $respuesta['error'] = true; return $respuesta; } return $datos; } public function isValidUpdate(array $params, $id) { $reglas = array( 'Codigo' => 'required|unique:TB_Carrera,Codigo,'.$id.',id', 'Nombre' => 'required', 'Ciclos'=>'required', 'Facultad_id' => 'required' ); //\Log::debug('Puesto P ' . print_r($params['facultad'], true)); //$facultad = \App\Models\Utils::getVueParam($params,"facultad","Facultad_id"); //\Log::debug('Puesto ' . $facultad); $datos = array( 'Codigo' => $params['codigo'], 'Nombre' => $params['nombre'], 'Ciclos' => $params['ciclos'], 'Facultad_id' => isset($params['facultad'])? $params['facultad']:null, ); $validator = Validator::make($datos, $reglas, $this->mensajes); if ($validator->fails()){ $respuesta['mensaje'] = 'Por favor verifique los datos ingresados'; $respuesta['errors'] = $validator; $respuesta['error'] = true; return $respuesta; } return $datos; } }
    true
    5420b92db3ec20e8f5eda3e3f3a1b5ddbeeb28dc
    PHP
    kanjengsaifu/erp_bnp
    /models/StockModel.php
    UTF-8
    14,750
    2.6875
    3
    []
    no_license
    <?php require_once("BaseModel.php"); class StockModel extends BaseModel{ private $table_name = ""; function __construct(){ if(!static::$db){ static::$db = mysqli_connect($this->host, $this->username, $this->password, $this->db_name); } mysqli_set_charset(static::$db,"utf8"); } function setTableName($table_name = "tb_stock"){ $this->table_name = $table_name; } function createStockTable(){ $sql = " CREATE TABLE `".$this->table_name."` ( `stock_code` int(11) NOT NULL COMMENT 'รหัสอ้างอิงคลังสินค้า', `stock_type` varchar(10) NOT NULL COMMENT 'ประเภท รับ หรือ ออก', `product_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงสินค้า', `stock_date` date DEFAULT NULL COMMENT 'วันที่ดำเนินการ', `in_qty` int(11) NOT NULL COMMENT 'จำนวน (เข้า)', `in_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (เข้า)', `in_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (เข้า)', `out_qty` int(11) NOT NULL COMMENT 'จำนวน (ออก)', `out_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (ออก)', `out_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (ออก)', `stock_qty` int(11) NOT NULL COMMENT 'จำนวน (คงเหลือ)', `stock_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (คงเหลือ)', `stock_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (คงเหลือ)', `delivery_note_supplier_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการยืมเข้า', `delivery_note_customer_list_code` varchar(50) DEFAULT NULL COMMENT 'รหัสอ้างอิงรายการยืมออก', `invoice_supplier_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการซื้อเข้า', `invoice_customer_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการขายออก', `stock_move_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการย้ายคลังสินค้า', `stock_issue_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการตัดคลังสินค้า', `credit_note_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการใบลดหนี้', `summit_product_code` varchar(50) NOT NULL COMMENT 'รหัสรายการสินค้ายกยอด', `stock_change_product_list_code` varchar(50) NOT NULL COMMENT 'รหัสรายการสินค้าเปลี่ยนชื่อ', `addby` varchar(50) NOT NULL COMMENT 'ผู้เพิ่ม', `adddate` datetime DEFAULT NULL COMMENT 'เวลาเพิ่ม', `updateby` varchar(50) DEFAULT NULL COMMENT 'ผู้แก้ไข', `lastupdate` datetime DEFAULT NULL COMMENT 'เวลาแก้ไข' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; "; if (mysqli_query(static::$db,$sql)) { $sql = "ALTER TABLE `".$this->table_name."` ADD PRIMARY KEY (`stock_code`), ADD KEY `invoice_code` (`invoice_customer_list_code`,`invoice_supplier_list_code`); "; if (mysqli_query(static::$db,$sql)) { $sql = "ALTER TABLE `".$this->table_name."` MODIFY `stock_code` int(11) NOT NULL AUTO_INCREMENT COMMENT 'รหัสอ้างอิงคลังสินค้า'; "; if (mysqli_query(static::$db,$sql)) {return true;} else {return false;} }else {return false;} }else {return false;} } function deleteStockTable(){ $sql = "DROP TABLE IF EXISTS ".$this->table_name." ;"; if (mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { return true; }else { return false; } } function getStockBy(){ $sql = " SELECT * FROM $table_name WHERE 1 "; if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { $data = []; while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ $data[] = $row; } $result->close(); return $data; } } function getStockLogListByDate($date_start = '', $date_end = '', $stock_group_code = '', $keyword = ''){ $str = " AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') "; $sql_old_in = "SELECT SUM(in_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'in' AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') < STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s')"; $sql_old_out = "SELECT SUM(out_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'out' AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') < STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s')"; $sql_in = "SELECT SUM(in_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'in' ".$str; $sql_out = "SELECT SUM(out_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'out' ".$str; $sql_borrow_in = "SELECT SUM(in_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'borrow_in' ".$str; $sql_borrow_out = "SELECT SUM(out_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'borrow_out' ".$str; $sql_minimum = "SELECT SUM(minimum_stock) FROM tb_product_customer WHERE tb_product_customer.product_code = tb.product_code AND product_status = 'Active' "; $sql_safety = "SELECT SUM(safety_stock) FROM tb_product_customer WHERE tb_product_customer.product_code = tb.product_code AND product_status = 'Active' "; $sql = "SELECT tb.product_code, CONCAT(product_code_first,product_code) as product_code, product_name, product_type, product_status , (IFNULL(($sql_old_in),0) - IFNULL(($sql_old_out),0)) as stock_old, IFNULL(($sql_in),0) as stock_in, IFNULL(($sql_out),0) as stock_out, IFNULL(($sql_borrow_in),0) as stock_borrow_in, IFNULL(($sql_borrow_out),0) as stock_borrow_out, IFNULL(($sql_safety),0) as stock_safety, IFNULL(($sql_minimum),0) as stock_minimum FROM tb_stock_report LEFT JOIN tb_product as tb ON tb_stock_report.product_code = tb.product_code WHERE stock_group_code = '$stock_group_code' AND ( CONCAT(product_code_first,product_code) LIKE ('%$keyword%') OR product_name LIKE ('%$keyword%') ) ORDER BY CONCAT(product_code_first,product_code) "; if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { $data = []; while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ $data[] = $row; } $result->close(); return $data; } } function getStockInByDate($date_start = '', $date_end = ''){ $sql = "SELECT stock_code, stock_date, ".$this->table_name.".product_code, CONCAT(product_code_first,product_code) as product_code, product_name, product_type, product_status , in_qty , supplier_name_th, supplier_name_en FROM ".$this->table_name." LEFT JOIN tb_product ON ".$this->table_name.".product_code = tb_product.product_code LEFT JOIN tb_invoice_supplier_list ON ".$this->table_name.".invoice_supplier_list_code = tb_invoice_supplier_list.invoice_supplier_list_code LEFT JOIN tb_invoice_supplier ON tb_invoice_supplier_list.invoice_supplier_code = tb_invoice_supplier.invoice_supplier_code LEFT JOIN tb_supplier ON tb_invoice_supplier.supplier_code = tb_supplier.supplier_code WHERE stock_type = 'in' AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') ORDER BY STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') "; if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { $data = []; while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ $data[] = $row; } $result->close(); return $data; } } function getStockOutByDate($date_start = '', $date_end = ''){ $sql = "SELECT stock_code, stock_date, ".$this->table_name.".product_code, CONCAT(product_code_first,product_code) as product_code, product_name, product_type, product_status , out_qty , customer_name_th, customer_name_en FROM ".$this->table_name." LEFT JOIN tb_product ON ".$this->table_name.".product_code = tb_product.product_code LEFT JOIN tb_invoice_customer_list ON ".$this->table_name.".invoice_customer_list_code = tb_invoice_customer_list.invoice_customer_list_code LEFT JOIN tb_invoice_customer ON tb_invoice_customer_list.invoice_customer_code = tb_invoice_customer.invoice_customer_code LEFT JOIN tb_customer ON tb_invoice_customer.customer_code = tb_customer.customer_code WHERE stock_type = 'out' AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') ORDER BY STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') "; if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { $data = []; while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ $data[] = $row; } $result->close(); return $data; } } function updateStockByCode($code,$data = []){ $sql = " UPDATE $table_name SET stock_type = '".$data['stock_type']."' , product_code = '".$data['product_code']."' , stock_date = '".$data['stock_date']."' , in_qty = '".$data['in_qty']."' , in_cost_avg = '".$data['in_cost_avg']."' , in_cost_avg_total = '".$data['in_cost_avg_total']."' , out_qty = '".$data['out_qty']."' , out_cost_avg = '".$data['out_cost_avg']."' , out_cost_avg_total = '".$data['out_cost_avg_total']."' , balance_qty = '".$data['balance_qty']."' , balance_price = '".$data['balance_price']."' , balance_total = '".$data['balance_total']."' , delivery_note_supplier_list_code = '".$data['delivery_note_supplier_list_code']."' , delivery_note_customer_list_code = '".$data['delivery_note_customer_list_code']."' , invoice_supplier_list_code = '".$data['invoice_supplier_list_code']."' , invoice_customer_list_code = '".$data['invoice_customer_list_code']."' , stock_move_list_code = '".$data['stock_move_list_code']."' , regrind_supplier_list_code = '".$data['regrind_supplier_list_code']."' , updateby = '".$data['updateby']."', lastupdate = NOW() WHERE stock_code = '$code' "; if (mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { return true; }else { return false; } } function insertStock($data = []){ $sql = " INSERT INTO tb_stock_group ( stock_type, product_code, stock_date, in_qty, in_cost_avg, in_cost_avg_total, out_qty, out_cost_avg, out_cost_avg_total, balance_qty, balance_price, balance_total, delivery_note_supplier_list_code, delivery_note_customer_list_code, invoice_supplier_list_code, invoice_customer_list_code, regrind_supplier_list_code, stock_move_list_code, addby, adddate ) VALUES ( '".$data['stock_type']."', '".$data['product_code']."', '".$data['stock_date']."', '".$data['customer_code']."', '".$data['supplier_code']."', '".$data['in_qty']."', '".$data['in_cost_avg']."', '".$data['in_cost_avg_total']."', '".$data['out_qty']."', '".$data['out_cost_avg']."', '".$data['out_cost_avg_total']."', '".$data['balance_qty']."', '".$data['balance_price']."', '".$data['balance_total']."', '".$data['delivery_note_supplier_list_code']."', '".$data['delivery_note_customer_list_code']."', '".$data['invoice_supplier_list_code']."', '".$data['invoice_customer_list_code']."', '".$data['regrind_supplier_list_code']."', '".$data['stock_move_list_code']."', '".$data['addby']."', NOW() )"; if(mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)){ return true; }else{ return false; } } function deleteStockByCode($code){ $sql = " DELETE FROM $table_name WHERE stock_code = '$code' ;"; if(mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)){ return true; }else{ return false; } } } ?>
    true
    71b97e151d285faf37567f6df8084405fce87756
    PHP
    zhangjiquan1/phpsourcecode
    /web3d/yuncart/include/common/session.class.php
    UTF-8
    4,321
    2.546875
    3
    [ "Apache-2.0" ]
    permissive
    <?php defined('IN_CART') or die; class Session { private $lifetime = 1800; private $session_name = ''; private $session_id = ''; private $session_time = ''; private $session_md5 = ''; private $time = ""; private $initdata = array(); /** * * 构造函数 * */ function __construct($session_name = 'sess', $session_id = '', $lifetime = 1800) { $GLOBALS['_session'] = array(); $this->session_name = $session_name; $this->lifetime = $lifetime; $this->_time = time(); //验证session_id $tmpsess_id = ''; if ($session_id) { $tmpsess_id = $session_id; } else { $tmpsess_id = cgetcookie($session_name); } if ($tmpsess_id && $this->verify($tmpsess_id)) { $this->session_id = substr($tmpsess_id, 0, 32); } if ($this->session_id) { //session_id 存在,加载session $this->read_session(); } else { //session_id 不存在,生成,写入到cookie $this->session_id = $this->gene_session_id(); $this->init_session(); csetcookie($this->session_name, $this->session_id . $this->gene_salt($this->session_id)); } //关闭时执行gc register_shutdown_function(array(&$this, 'gc')); } /** * * DB中insert新的session * */ private function init_session() { DB::getDB()->insert("session", array("session_id" => $this->session_id, "session_data" => serialize(array()), 'time' => $this->_time)); } /** * * 生成session_id * */ private function gene_session_id() { $id = strval(time()); while (strlen($id) < 32) { $id .= mt_rand(); } return md5(uniqid($id, true)); } /** * * 生成salt,验证 * */ private function gene_salt($session_id) { $ip = getClientIp(); return sprintf("%8u", crc32(SITEPATH . (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "") . $ip . $session_id)); } /** * * 生成salt,验证 * */ private function verify($tmpsess_id) { return substr($tmpsess_id, 32) == $this->gene_salt(substr($tmpsess_id, 0, 32)); } /** * * 读出已知session * */ private function read_session() { $session = DB::getDB()->selectrow("session", "*", "session_id = '" . $this->session_id . "'"); if (empty($session)) { //session为空, $this->init_session(); $this->session_md5 = md5('a:0:{}'); $this->session_time = 0; $GLOBALS['_SESSION'] = array(); } else { if (!empty($session['session_data']) && $session['time'] > $this->_time - $this->lifetime) { $this->session_md5 = md5($session['session_data']); $this->session_time = $session['time']; $GLOBALS['_SESSION'] = unserialize($session['session_data']); } else { //session过期 $this->session_md5 = md5(serialize(array())); $this->session_time = 0; $GLOBALS['_SESSION'] = array(); } } } /** * * 更新session * */ private function write_session() { $data = serialize(!empty($GLOBALS['_SESSION']) ? $GLOBALS['_SESSION'] : array()); $this->_time = time(); //session未变化 if (md5($data) == $this->session_md5 && $this->_time - $this->session_time < 10) { return true; } $ret = DB::getDB()->update("session", array("time" => $this->_time, "session_data" => addslashes($data)), "session_id='" . $this->session_id . "'", true); return $ret; } /** * * 执行gc * */ public function gc() { $this->write_session(); if ($this->_time % 2 == 0) { DB::getDB()->delete("session", "time<" . ($this->_time - $this->lifetime)); } return true; } }
    true
    d1c92ef71291db71bb8916a01a27add5639e1a82
    PHP
    cyingfan/m3o-php
    /src/Model/Routing/RouteOutput.php
    UTF-8
    1,739
    2.984375
    3
    [ "MIT" ]
    permissive
    <?php declare(strict_types=1); namespace M3O\Model\Routing; use M3O\Model\AbstractModel; class RouteOutput extends AbstractModel { private float $distance; private float $duration; /** @var Waypoint[] */ private array $waypoints; public function getDistance(): float { return $this->distance; } /** * @param float $distance * @return static */ public function setDistance(float $distance) { $this->distance = $distance; return $this; } public function getDuration(): float { return $this->duration; } /** * @param float $duration * @return static */ public function setDuration(float $duration) { $this->duration = $duration; return $this; } /** * @return Waypoint[] */ public function getWaypoints(): array { return $this->waypoints; } /** * @param Waypoint[]|array[] $waypoints * @return static */ public function setWaypoints(array $waypoints) { $this->waypoints = $this->castModelArray($waypoints, Waypoint::class); return $this; } public static function fromArray(array $array): RouteOutput { return (new RouteOutput()) ->setDistance((float) ($array['distance'] ?? 0.0)) ->setDuration((float) ($array['duration'] ?? 0.0)) ->setWaypoints($array['waypoints'] ?? []); } public function toArray(): array { return [ 'distance' => $this->getDistance(), 'duration' => $this->getDuration(), 'waypoints' => array_map(fn(Waypoint $w) => $w->toArray(), $this->getWaypoints()) ]; } }
    true
    b2b78ec55aff1406eee46b2c68d12ebaaba373a2
    PHP
    renilsoni/mvc
    /Cybercom/Model/Customer/Address.php
    UTF-8
    432
    2.59375
    3
    []
    no_license
    <?php namespace Model\Customer; \Mage::loadFileByClassName('Model\Core\Table'); class Address extends \Model\Core\Table { const STATUS_ENABLED = 1; const STATUS_DISABLED = 0; function __construct() { $this->setTableName('customer_address'); $this->setPrimaryKey('addressId'); } public function getStatusoptions() { return [ self::STATUS_ENABLED => 'Enable', self::STATUS_DISABLED => 'Disable' ]; } } ?>
    true
    48912c8a02aa2a3a77c4ad6c30bbc95f20bf5af9
    PHP
    leanf19/TP_Final_IPOO
    /TPFinal/testTeatroFinal.php
    UTF-8
    10,844
    2.953125
    3
    []
    no_license
    <?php require_once ("ORM/Teatro.php"); require_once "ABM_Teatro.php"; require_once "ABM_FuncionMusical.php"; require_once "ABM_FuncionCine.php"; require_once "ABM_FuncionTeatro.php"; //Leandro Gabriel Fuentes FAI-465 Universidad Nacional del Comahue / Carrera TUDW , Materia: IPOO function menu() { do { echo "************INGRESE UNA OPCION DEL MENU***********\n"; echo "1.- Visualizar la informacion de los teatros de la base de datos \n"; echo "2.- Agregar un nuevo teatro a la base de datos\n"; echo "3.- Eliminar un teatro de la base de datos\n"; echo "4.- Salir.\n"; $opcionTeatro = trim(fgets(STDIN)); switch ($opcionTeatro) { case 1: menuTeatros(); break; case 2: altaTeatro(); break; case 3: bajaTeatro(); break; case 4: echo "*************Terminando Sesion*************\n"; break; default: echo "Ingrese una opcion correcta (1-4)\n"; break; } } while ($opcionTeatro <> 4); } function menuTeatros() { $unTeatro = new Teatro(); $auxTeatros = $unTeatro->listar(); if (count($auxTeatros) != 0) { foreach ($auxTeatros as $teatro) { print $teatro->__toString(); } do { echo "\n***Seleccione el id de uno de estos teatros***\n"; $idteatro = trim(fgets(STDIN)); $exito = $unTeatro->buscar($idteatro); } while (!$exito); echo "***Teatro obtenido, seleccione una de las siguientes opciones***\n"; do { // $exito = $unTeatro->buscar($idteatro); echo "1.- Mostrar Informacion del teatro\n"; echo "2.- Modificar datos del teatro(nombre,direccion,funciones)\n"; echo "3.- Calcular costo total por uso del teatro\n"; echo "4.- Volver al menu de inicio\n"; $opcion = trim(fgets(STDIN)); switch ($opcion) { case 1: print $unTeatro->__toString(); break; case 2: modificarDatos($unTeatro); break; case 3: echo "Costo por el uso de las instalaciones: {$unTeatro->darCosto()}\n"; break; case 4: break; default: echo "Opcion no valida, ingrese una opcion->(1-4)\n"; } } while ($opcion <> 4); } else { echo "***No hay teatros para mostrar***\n"; } } function modificarDatos($unTeatro) { $id = $unTeatro->getIdTeatro(); $op = -1; do { echo "***Seleccione una de las siguientes opciones***\n"; echo "1.- Cambiar datos del teatro(nombre y direccion)\n"; echo "2.- Agregar una nueva funcion\n"; echo "3.- Modificar una funcion\n"; echo "4.- Eliminar una funcion\n"; echo "5.- Volver al menú anterior\n"; $op = trim(fgets(STDIN)); switch ($op) { case 1: modificarTeatro($id); break; case 2: altaFuncion($unTeatro); break; case 3: modificarFuncion($unTeatro); break; case 4: bajaFuncion($unTeatro); break; default: echo "Ingrese una opción correcta(1-5)\n"; } } while ($op <> 5); } //Modifica el nombre y la direccion del teatro con la id pasada por parametro function modificarTeatro($idTeatro) { $unTeatro = new Teatro(); $unTeatro->buscar($idTeatro); $nombre=$unTeatro->getNombre(); $direccion=$unTeatro->getDireccion(); $exito = false; $aux = 0; echo "Desea modificar el nombre del teatro? (s/n):\n"; $resp = trim(fgets(STDIN)); if($resp == 's') { echo "Ingrese el nuevo nombre del teatro seleccionado: \n"; $nombre = trim(fgets(STDIN)); $aux++; } $resp = "n"; echo "Desea modificar la direccion del teatro? (s/n):\n"; $resp = trim(fgets(STDIN)); if($resp == 's'){ echo "Ingrese la nueva direccion del teatro seleccionado: \n"; $direccion = trim(fgets(STDIN)); $aux++; } if($aux != 0){ $exito =ABM_Teatro::modificarTeatro($idTeatro, $nombre, $direccion); if($exito){ echo "Datos del teatro modificados con exito!!!!\n"; } } } function altaFuncion($unTeatro) { echo "Ingrese el nombre de la función a agregar:\n"; $nombreFuncion = strtolower(trim(fgets(STDIN))); do { echo "Ingrese el tipo de funcion (Cine,Teatro,Musical):\n"; $tipo = strtolower(trim(fgets(STDIN))); } while($tipo != "cine" && $tipo != "musical" && $tipo != "teatro"); do { echo "Ingrese el precio de la funcion:\n"; $precio = trim(fgets(STDIN)); } while (!is_numeric($precio)); echo "Ingrese el horario de la funcion en formato 24hrs (HH:MM):\n"; $horaInicio = trim(fgets(STDIN)); do { echo "Ingrese la duracion de la funcion en minutos:\n"; $duracion = trim(fgets(STDIN)); } while (!is_numeric($duracion)); switch ($tipo) { case "teatro": $exito = ABM_FuncionTeatro::altaFuncionTeatro(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro); break; case "cine": echo "Ingrese el pais de origen:\n"; $pais = trim(fgets(STDIN)); echo "Ingrese el genero:\n"; $genero = trim(fgets(STDIN)); $exito = ABM_FuncionCine::altaFuncionCine(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro, $genero, $pais); break; case "musical": echo "Ingrese el director:\n"; $director = trim(fgets(STDIN)); echo "Ingrese la cantidad de personas en escena:\n"; $elenco = trim(fgets(STDIN)); $exito = ABM_FuncionMusical::altaFuncionMusical(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro, $director, $elenco); break; } if (!$exito) { echo "No es posible agregar la funcion, el horario de la funcion ingresada se solapa con otra funcion\n"; } } function modificarFuncion($unTeatro) { $unaFuncion = new Funcion(); echo "Funciones disponibles en este teatro :\n"; $cadenaFunciones = $unTeatro->recorrerFunciones(); do { echo $cadenaFunciones; echo "Ingrese el id de la función a modificar: \n"; $idfuncion = strtolower(trim(fgets(STDIN))); $exito= $unaFuncion->buscar($idfuncion); } while (!is_numeric($idfuncion) || !$exito); echo "Ingrese el nuevo nombre de la función: \n"; $nombreFuncion = trim(fgets(STDIN)); do { echo "Ingrese el nuevo precio de la función: \n"; $precioFuncion = trim(fgets(STDIN)); } while (!is_numeric($precioFuncion)); echo "Ingrese la hora de la funcion en formato 24hrs (HH:MM):\n"; $horaInicio = trim(fgets(STDIN)); do { echo "Ingrese la duracion de la funcion en minutos:\n"; $duracion = trim(fgets(STDIN)); } while (!is_numeric($duracion)); $unaFuncion = $unTeatro->obtenerFunciones($idfuncion); $exito = false; switch (get_class($unaFuncion)) { case "FuncionCine": echo "Ingrese el pais de origen de la funcion de cine:\n"; $pais = trim(fgets(STDIN)); echo "Ingrese el genero de la funcion de cine:\n"; $genero = trim(fgets(STDIN)); $exito = ABM_FuncionCine::modificarFuncionCine($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro, $pais, $genero); break; case "FuncionMusical": echo "Ingrese el director:\n"; $director = trim(fgets(STDIN)); echo "Ingrese la cantidad de personas en escena:\n"; $elenco = trim(fgets(STDIN)); $exito = ABM_FuncionMusical::modificarFuncionMusical($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro, $director, $elenco); break; case "FuncionTeatro": $exito = ABM_FuncionTeatro::modificarFuncionTeatro($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro); } if (!$exito) { echo "No se modificó la función porque el horario se solapa con el de otra funcion existente\n"; } else { echo "La funcion se modifico con exito!!!!"; } } function bajaFuncion($unTeatro) { $unaFuncion = new Funcion(); echo "Funciones disponibles en este teatro :\n"; $funcionesTeatro = $unTeatro->recorrerFunciones(); $exito = false; echo $funcionesTeatro; echo "Seleccione el id de la función a eliminar:\n"; $idfuncion = trim(fgets(STDIN)); $unaFuncion=$unTeatro->obtenerFunciones($idfuncion); switch (get_class($unaFuncion)) { case "FuncionCine": $exito = ABM_FuncionCine::bajaFuncionCine($idfuncion); break; case "FuncionMusical": $exito = ABM_FuncionMusical::bajaFuncionMusical($idfuncion); break; case "FuncionTeatro": $exito = ABM_FuncionTeatro::bajaFuncionTeatro($idfuncion); } if($exito){ echo "Funcion eliminada con exito!!!"; } else { echo "No se ha podido eliminar la funcion elegida"; } } function altaTeatro() { echo "Ingrese el nombre del teatro:\n"; $nombre = trim(fgets(STDIN)); echo "Ingrese la dirección del teatro:\n"; $direccion = trim(fgets(STDIN)); $exito = ABM_Teatro::altaTeatro($nombre, $direccion); if($exito) { echo "***Teatro agregado con exito a la base de datos***\n"; } else { echo "***Fallo la carga del teatro a la base de datos***\n"; } } function bajaTeatro() { mostrarTeatros(); do { $exito = false; echo "Seleccione el id del teatro que desea eliminar \n"; $idteatro = trim(fgets(STDIN)); $exito = ABM_Teatro::eliminarTeatro($idteatro); if($exito) { echo "Se ha eliminado con exito el teatro de la BD\n"; } else { echo "No se pudo eliminar el teatro seleccionado"; } } while (!is_numeric($idteatro)); } function mostrarTeatros() { $teatroTemp = new Teatro(); $teatros = $teatroTemp->listar(); foreach ($teatros as $teatro) print $teatro->__toString(); echo "---------------------------\n"; } function main() { menu(); } main();
    true
    58c651ebc6c3440354274073de3cab20a3bf4cfe
    PHP
    lidonghui-ht/poptrip
    /Libs/ThirdParty/Ctrip/Hotel/Common/getDate.php
    UTF-8
    2,363
    3.296875
    3
    []
    no_license
    <?php /** * 获取年月日形式的日期(参数为空,输出2012年12月23日;输入分隔符,则输出2012-12-23形式) * cltang 2012年5月11日 携程 * @param $linkChar */ function getDateYMD($linkChar) { date_default_timezone_set('PRC');//设置时区 $coutValue=strlen($linkChar)>0?date("Y".$linkChar."m".$linkChar."d"):date("Y年m月d日"); return $coutValue; } /** * 获取年月日形式的日期(参数为空,输出2012年12月23日;输入分隔符,则输出2012-12-23形式) * cltang 2012年5月11日 携程 * @param $linkChar-分隔符号; */ function getDateYMD_addDay($linkChar,$addDay) { $coutValue=strlen($linkChar)>0?date("Y".$linkChar."m".$linkChar."d",strtotime("$d +$addDay day")):date("Y年m月d日",strtotime("$d +$addDay day")); return $coutValue; } date("Y-m-d",strtotime("$d +1 day")); /** * 获取年月日时分秒形式的日期(参数为空,输出2012年12月23日 12:23:50;输入分隔符,则输出2012-12-23 12:23:50形式) * cltang 2012年5月11日 携程 * @param $linkChar */ function getDateYMDSHM($linkChar) { $coutValue=strlen($linkChar)>0?date("Y".$linkChar."m".$linkChar."d H:i:s"):date("Y年m月d日 H:i:s"); return $coutValue; } /** * 获取到当前Unix时间戳:分msec sec两个部分,msec是微妙部分,sec是自Unix纪元(1970-1-1 0:00:00)到现在的秒数 */ function getMicrotime() { return microtime(); } /** * * 将日期转换为秒 * @param $datatime */ function timeToSecond($datatime) { return strtotime($datatime); } /** * * 计算时间的差值:返回{天、小时、分钟、秒} * @param $begin_time * @param $end_time */ function timediff($begin_time,$end_time) { if($begin_time < $end_time){ $starttime = $begin_time; $endtime = $end_time; } else{ $starttime = $end_time; $endtime = $begin_time; } $timediff = $endtime-$starttime; //echo $begin_time.$end_time.$timediff; $days = intval($timediff/86400); $remain = $timediff%86400; $hours = intval($remain/3600); $remain = $remain%3600; $mins = intval($remain/60); $secs = $remain%60; $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs); return $res; } ?>
    true
    72957372cfa2e0c22cf0ff14e39ac22178863d07
    PHP
    Arkos13/auth-service-symfony
    /application/src/Infrastructure/User/Repository/NetworkRepository.php
    UTF-8
    2,163
    2.765625
    3
    []
    no_license
    <?php namespace App\Infrastructure\User\Repository; use App\Model\User\Entity\Network; use App\Model\User\Repository\NetworkRepositoryInterface; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\NonUniqueResultException; class NetworkRepository implements NetworkRepositoryInterface { private EntityManagerInterface $em; public function __construct(EntityManagerInterface $em) { $this->em = $em; } /** * @param string $email * @param string $network * @return Network|null * @throws NonUniqueResultException */ public function findOneByEmailAndNetwork(string $email, string $network): ?Network { return $this->em->createQueryBuilder() ->select("networks") ->from(Network::class, "networks") ->innerJoin("networks.user", "user") ->andWhere("user.email = :email")->setParameter("email", $email) ->andWhere("networks.network = :network")->setParameter("network", $network) ->setMaxResults(1) ->getQuery() ->getOneOrNullResult(); } /** * @param string $email * @param string $accessToken * @param string $network * @return Network|null * @throws NonUniqueResultException */ public function findOneByEmailAndAccessToken(string $email, string $accessToken, string $network): ?Network { return $this->em->createQueryBuilder() ->select("networks") ->from(Network::class, "networks") ->innerJoin("networks.user", "user") ->andWhere("user.email = :email")->setParameter("email", $email) ->andWhere("networks.accessToken = :accessToken")->setParameter("accessToken", $accessToken) ->andWhere("networks.network = :network")->setParameter("network", $network) ->setMaxResults(1) ->getQuery() ->getOneOrNullResult(); } public function updateAccessToken(Network $network, ?string $accessToken): void { $network->setAccessToken($accessToken); $this->em->persist($network); $this->em->flush(); } }
    true
    520f4f5118d97a03206dc6a8fe29bab51f6b10e3
    PHP
    knh/werewolf
    /create_game.php
    UTF-8
    1,917
    2.984375
    3
    []
    no_license
    <?php require_once('init.php'); $raw_role_string = $_POST['role_list']; $role_array = preg_split("/(\r\n|\n|\r)/", $raw_role_string); // parse the raw string $role_num_array = array(); //Holds the final result of parsed role_array. $counter = 0; $player_num = 0; //Parse the role_array. Final result is an array[$role] = num foreach($role_array as &$role){ $sub_role = explode("*", $role); if(isset($sub_role[1])){ $role=$sub_role[0]; $role_num_array[$counter] = (int)$sub_role[1]; } else{ $role_num_array[$counter] = 1; } $player_num += $role_num_array[$counter]; $counter++; } // Output the role table. for($counter=0; $counter < count($role_array); $counter++){ echo $role_array[$counter] . " * " . $role_num_array[$counter] ."</br>"; } $game_id = mt_rand(100000, 999999); //create a better random game id. $query="SELECT * FROM werewolf_gameid WHERE game_id=" . $game_id; // to make sure the game id is unique while(true){ $result=$mysqli->query($query); if($result->num_rows == 0) break; $game_id=rand(100000, 999999); $query="SELECT * FROM werewolf_gameid WHERE game_id = " . $game_id; } if($mysqli->query("INSERT INTO werewolf_gameid (game_id, player_num_limit)" . "VALUES ('" . $game_id . "', '" . $player_num ."')") == true){ echo "</br>Create game succeed. Your game id is " . $game_id .". Your friend can use this number to join in the game.</br>"; }else{ echo "</br>Create game failed. Please try again later.</br>"; } $query="INSERT INTO werewolf_detail (game_id, all_roles) VALUES ('" . $game_id . "', '" . $raw_role_string . "')"; if($mysqli->query($query)){ echo "Redirecting to game console in 3 seconds. Do not refresh the page. </br>"; echo "<script>window.setInterval(function(){document.location='./control_game.php?game_id=". $game_id . "'}, 3000)</script>"; // redirecting to control_game.php after creating game. }else{ echo "Detail writing failed. </br>"; } ?>
    true
    7a53190f49179883fdb49b034066f15c1548e8a1
    PHP
    makasim/yadm-benchmark
    /src/Entity/OrmOrder.php
    UTF-8
    1,175
    2.71875
    3
    [ "MIT" ]
    permissive
    <?php namespace YadmBenchmark\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="orders") */ class OrmOrder { /** * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") * * @var integer $id */ private $id; /** * @ORM\Column(name="number", type="string") */ private $number; /** @ORM\Embedded(class = "OrmPrice") */ private $price; /** * @return int */ public function getId() { return $this->id; } /** * @param int $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getNumber() { return $this->number; } /** * @param mixed $number */ public function setNumber($number) { $this->number = $number; } /** * @return OrmPrice */ public function getPrice() { return $this->price; } /** * @param OrmPrice $price */ public function setPrice(OrmPrice $price = null) { $this->price = $price; } }
    true
    9e85ba580f4363fe1b7830365abc96dd83bcf6d8
    PHP
    michaelvickersuk/laravel-tv-library
    /database/migrations/2020_05_06_203601_create_genres_table.php
    UTF-8
    1,048
    2.59375
    3
    []
    no_license
    <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CreateGenresTable extends Migration { public function up() { Schema::create('genres', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); DB::table('genres') ->insert([ ['name' => 'Action'], ['name' => 'Animation'], ['name' => 'Comedy'], ['name' => 'Crime'], ['name' => 'Documentary'], ['name' => 'Drama'], ['name' => 'Horror'], ['name' => 'Mystery'], ['name' => 'Reality'], ['name' => 'Science Fiction'], ['name' => 'Thriller'], ['name' => 'Western'], ]); } public function down() { Schema::dropIfExists('genres'); } }
    true
    37258cae0c9f72b4856d0d1adaa2843306fc78f9
    PHP
    rosko/AlmazService
    /php/backup/JsonResponseBuilder.php
    UTF-8
    481
    3.109375
    3
    []
    no_license
    <?php include_once 'ResponseBuilder.php'; class JsonResponseBuilder implements ResponseBuilder { private $response = ""; public function makeResponseError($errorType, $errorMsg = '') { $this->response .= "Error " . $errorType . ": " . $errorMsg; } public function addResource($resource) { } public function makeResponse() { } public function printResponse() { echo $this->response; } } ?>
    true
    de54900417e4174abca15868f7b56a9c2cedc232
    PHP
    798256478/Design-Pattern
    /Strategy.php
    UTF-8
    965
    3.6875
    4
    []
    no_license
    <?php /** * 策略模式 * 使用场景:有一个Strategy类, 类中有一个可以直接调用的getData方法 * 返回xml数据,随着业务扩展要求输出json数据,这时就可以使用策略模式 * 根据需求获取返回数据类型 */ class Strategy { protected $arr; function __construct($title, $info) { $this->arr['title'] = $title; $this->arr['info'] = $info; } public function getData($objType) { return $objType->get($this->arr); } } /** * 返回json类型的数据格式 */ class Json { public function get($data) { return json_encode($data); } } /** * 返回xml类型的数据格式 */ class Xml { public function get($data) { $xml = '<?xml version = "1.0" encoding = "utf-8"?>'; $xml .= '<return>'; $xml .= '<data>'.serialize($data).'</data>'; $xml .= '</return>'; return $xml; } } $strategy = new Strategy('cd_1', 'cd_1'); echo $strategy->getData(new Json); echo $strategy->getData(new Xml); ?>
    true
    dcb62df97882fb75c7c6daaecb3568b48b0be456
    PHP
    lesstif/php-jira-rest-client
    /src/ClassSerialize.php
    UTF-8
    1,318
    3.015625
    3
    [ "Apache-2.0" ]
    permissive
    <?php namespace JiraRestApi; trait ClassSerialize { /** * class property to Array. * * @param array $ignoreProperties this properties to be (ex|in)cluded from array whether second param is true or false. * @param bool $excludeMode * * @return array */ public function toArray(array $ignoreProperties = [], bool $excludeMode = true): array { $tmp = get_object_vars($this); $retAr = null; foreach ($tmp as $key => $value) { if ($excludeMode === true) { if (!in_array($key, $ignoreProperties)) { $retAr[$key] = $value; } } else { // include mode if (in_array($key, $ignoreProperties)) { $retAr[$key] = $value; } } } return $retAr; } /** * class property to String. * * @param array $ignoreProperties this properties to be excluded from String. * @param bool $excludeMode * * @return string */ public function toString(array $ignoreProperties = [], bool $excludeMode = true): string { $ar = $this->toArray($ignoreProperties, $excludeMode); return json_encode($ar, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } }
    true
    6d0fa897f2975eb6630c0ba6883559ff1d1d387a
    PHP
    sdboyer/frozone
    /src/Lockable.php
    UTF-8
    1,128
    3.203125
    3
    [ "MIT" ]
    permissive
    <?php namespace Frozone; /** * Interface for 'locking', which locks an object's state using a key. * * State can only be unlocked (that is, state can be mutated) by calling the * unlock method with the same key. */ interface Lockable { /** * Locks this object using the provided key. * * The object can only be unlocked by providing the same key. * * @param mixed $key * The key used to lock the object. * * @throws LockedObjectException * Thrown if the collector is already locked. */ public function lock($key); /** * Attempts to unlock the collector with the provided key. * * Key comparison is done using the identity operator (===). * * @param mixed $key * The key with which to unlock the object. * * @throws LockedObjectException * Thrown if the incorrect key is provided, or if the collector is not * locked. */ public function unlock($key); /** * Indicates whether this collector is currently locked. * * @return bool */ public function isLocked(); }
    true
    ff83a56fc15e796a6c0e3df81ed1e160ae30036a
    PHP
    momentphp/framework
    /src/CallableResolver.php
    UTF-8
    1,286
    2.875
    3
    []
    no_license
    <?php namespace momentphp; /** * CallableResolver */ class CallableResolver implements \Slim\Interfaces\CallableResolverInterface { use traits\ContainerTrait; /** * Base resolver * * @var \Slim\Interfaces\CallableResolverInterface */ protected $baseResolver; /** * Constructor * * @param \Interop\Container\ContainerInterface $container * @param array $options */ public function __construct(\Interop\Container\ContainerInterface $container, \Slim\Interfaces\CallableResolverInterface $baseResolver) { $this->container($container); $this->baseResolver = $baseResolver; } /** * Resolve `$toResolve` into a callable * * @param mixed $toResolve * @return callable */ public function resolve($toResolve) { try { $resolved = $this->baseResolver->resolve($toResolve); return $resolved; } catch (\Exception $e) { } $toResolveArr = explode(':', $toResolve); $class = $toResolveArr[0]; $method = isset($toResolveArr[1]) ? $toResolveArr[1] : null; $instance = $this->container()->get('registry')->load($class); return ($method) ? [$instance, $method] : $instance; } }
    true
    0187e9344bfe37285930b758eb4d9b0e052d39f1
    PHP
    DamienKusters/wbsMonitor
    /functions/removeProject.php
    UTF-8
    287
    2.515625
    3
    []
    no_license
    <?php include("../connect.php"); $projectId = $_POST["projectId"]; $sql = "DELETE FROM project WHERE id='$projectId'"; if(mysqli_query($conn ,$sql)) { echo "Project removed!"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
    true
    d805a65f6877fc03a2848a40cc4908fb140a3074
    PHP
    DMPR-dev/woocommerce-2plus1
    /wc_2plus1action/wc_2plus1action.php
    UTF-8
    2,643
    2.953125
    3
    [ "MIT" ]
    permissive
    <?php /* Plugin Name: WooCommerce 2+1 Action Description: Purchase 2, get 1 free! This plugin provides an ability to make an action "2+1", each 3rd item on WooCommerce cart produces one free item(the cheapest one on the cart). Author: Dmytro Proskurin Version: 0.0.1 Author URI: http://github.com/DMPR-dev */ namespace WC_2plus1; /* Included additional classes */ require_once plugin_dir_path(__FILE__) . '/classes/checkers.php'; require_once plugin_dir_path(__FILE__) . '/classes/getters.php'; require_once plugin_dir_path(__FILE__) . '/classes/setters.php'; require_once plugin_dir_path(__FILE__) . '/functions.php'; /* This class provides an ability to make an action "2+1", each 3rd item on Woocommerce cart produces one free item(the cheapest one on the cart) */ class Action { /* Constructor */ public function __construct() { $this->initHooks(); } /* Inits needed hook(s) */ protected function initHooks() { add_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree"),10,1); } /* This method is attached to 'woocommerce_before_calculate_totals' hook @param $cart - an object of current cart that is being processed @returns VOID */ public function setThirdItemAsFree($cart) { /* Keep free items refreshed everytime cart gets updated */ $this->cleanCart($cart); if ($cart->cart_contents_count > 2) { /* Detect the cheapest product on cart */ $cheapest_product_id = Getters::getCheapestProduct($cart,array("return" => "ID")); if($cheapest_product_id === FALSE || intval($cheapest_product_id) < 0) return; /* Make one of the cheapest items free @returns the original item quantity decreased on 1 */ $this->addFreeItem($cart); } } /* Prevents recursion because adding a new item to cart will cause hook call @param $cart - an object of cart @returns VOID */ protected function addFreeItem($cart) { remove_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree")); Functions::addAsUniqueFreeProductToCart($cart,Getters::getCheapestProduct($cart,array("return" => "object")),"0.00"); add_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree"),10,1); } /* Prevents recursion because removing an item from cart will cause hook call @param $cart - an object of cart @returns VOID */ protected function cleanCart($cart) { remove_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree")); Functions::removeFreeItemsFromCart($cart); add_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree"),10,1); } } new Action();
    true
    b92975b84e42d13c5c6157470b829629195587ee
    PHP
    kerolesgeorge/php-products
    /product.php
    UTF-8
    1,621
    2.5625
    3
    []
    no_license
    <?php include_once __DIR__ . '/includes/autoload.php'; $product_id = $_GET['id']; function getProduct($product, $product_id) { return $product->readByID($product_id); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>PHP Products Home Page</title> <link rel="stylesheet" href="style/css/bootstrap.min.css"> <!-- bootstrap --> <link rel="stylesheet" href="style/css/all.min.css"> <!-- fontaweson --> <link rel="stylesheet" href="style/css/product.css"> <!-- my-style --> </head> <body> <div class="wrapper"> <header class="nav_bar"></header> <section class="main-section"> <div class="card"> <?php $product = getProduct(new Product(), $product_id); foreach($product as $details): ?> <img src="<?= $details['image_url'] ?>" class="card-img-top" alt="Product Image"> <div class="card-body"> <h5 class="card-title"><?= $details['name'] ?></h5> <div class="space">Price: <b><?= $details['price'] ?></b></div> <div class="card-text space"><?= $details['description'] ?></div> <div class="space"> <button class="btn btn-primary">Add to cart</button> <button class="btn btn-secondary">Save to list</button> </div> </div> <?php endforeach; ?> </div> </section> </div> <script src="js/jquery-3.4.1.min.js"></script> <!-- jQuery script --> <script src="js/bootstrap.min.js"></script> <!-- bootstrap --> <script src="js/front.js"></script> </body> </html>
    true