{ // 获取包含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 }); }); } })(); \n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914256,"cells":{"blob_id":{"kind":"string","value":"02423975680c33f3579bae27932db24eafe5de40"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"kristiankeep/decibel-framework"},"path":{"kind":"string","value":"/stream/DHttpStream.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":836,"string":"836"},"score":{"kind":"number","value":2.875,"string":"2.875"},"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 tuples\n *\n */\n public function setHeaders(array $headers);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914257,"cells":{"blob_id":{"kind":"string","value":"a3bca224e6c48e27a9de5edd342861ed0df6a2f8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"eabatalov/educational-gaming-platform"},"path":{"kind":"string","value":"/website/protected/models/entities/UserSkill.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1403,"string":"1,403"},"score":{"kind":"number","value":3.359375,"string":"3.359375"},"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":"setUserId($userId);\n $this->setSkillId($skillId);\n $this->setValue($value);\n }\n\n public function getUserId() {\n return $this->userId;\n }\n\n public function getSkillId() {\n return $this->skillId;\n }\n\n public function getValue() {\n return $this->value;\n }\n\n public function setUserId($userId) {\n self::validateUserId($userId);\n $this->userId = $userId;\n }\n\n public function setSkillId($skillId) {\n self::validateSkillId($skillId);\n $this->skillId = $skillId;\n }\n\n public function setValue($value) {\n TU::throwIfNot(is_int($value), TU::INVALID_ARGUMENT_EXCEPTION, \"value must be integer\");\n $this->value = $value;\n }\n\n public static function validateUserId($userId) {\n TU::throwIfNot(is_numeric($userId), TU::INVALID_ARGUMENT_EXCEPTION, \"user id must be integer\");\n }\n\n public static function validateSkillId($skillId) {\n TU::throwIfNot(is_numeric($skillId), TU::INVALID_ARGUMENT_EXCEPTION, \"skill id must be integer\");\n }\n\n //Numeric\n private $userId;\n //Numeric\n private $skillId;\n //Int\n private $value;\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914258,"cells":{"blob_id":{"kind":"string","value":"21ac2db0b9be261643098e4815171aa919b12d6b"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"tipsypastels/relibrary"},"path":{"kind":"string","value":"/ratings.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":945,"string":"945"},"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":"\n\n $_GET['book_id']]);\n }\n?>\n\n
\n

Ratings

\n\n \n $book]); ?>\n \n\n
\n \n Back Home\n \n\n \n link() ?>\" class=\"btn block\">\n Back to Book\n \n \n
\n\n \n $rating]);\n }\n ?> \n \n No ratings found for the given parameters.\n \n
\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914259,"cells":{"blob_id":{"kind":"string","value":"dd39a72d2ce764a7af0f5508d6c894240b587acb"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"andparsons/mage-app-start"},"path":{"kind":"string","value":"/app/code/Magento/VisualMerchandiser/Model/Sorting/SortInterface.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":551,"string":"551"},"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":"_running !== false) {\n trigger_error('Timer has already been started', E_USER_NOTICE);\n return false;\n }\n else\n $this->_running = microtime(true);\n }\n\n /**\n * function to stop the timer\n *\n * @return void\n */\n public function stop() {\n if($this->_running === false) {\n trigger_error('Timer has already been stopped/paused or has not been started', E_USER_NOTICE);\n return false;\n } else {\n $this->_elapsed += microtime(true) - $this->_running;\n $this->_running = false;\n }\n }\n\n /**\n * reset the timer\n *\n * @return void\n */\n public function reset() {\n $this->_elapsed = 0.;\n }\n\n /**\n * function to get the summed time in human readable format\n *\n * @value int\n * @return int|float\n */\n public function get() {\n // stop timer if it is still running\n if($this->_running !== false) {\n trigger_error('Forcing timer to stop', E_USER_NOTICE);\n $this->stop();\n }\n\n list($s, $ms) = explode('.', $this->_elapsed);\n $time = '0.'.$ms;\n if($s != 0) {\n $m = (int)($s / 60);\n $time = $s.'.'.$ms;\n }\n if($m != 0) {\n $s -= $m * 60;\n $h = (int)($m / 60);\n $time = $m.':'.$s.'.'.$ms;\n }\n if($h != 0) {\n $m -= $h * 60;\n $time = $h.':'.$m.':'.$s.'.'.$ms;\n }\n\n return $time;\n }\n\n /**\n * The elapsed time in milliseconds.\n *\n * @return float\n */\n public function getElapsed()\n {\n return $this->_elapsed;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914261,"cells":{"blob_id":{"kind":"string","value":"dd7530877d5c30972a2b1c82662447c3bd19281e"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"softscripts/WWEX-SpeedShip"},"path":{"kind":"string","value":"/Rate/Options/MynewServiceStructRateServiceOptions.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8773,"string":"8,773"},"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":"\n * @version 20140325-01\n * @date 2014-03-29\n */\n/**\n * This class stands for MynewServiceStructRateServiceOptions originally named RateServiceOptions\n * Meta informations extracted from the WSDL\n * - from schema : http://app6.wwex.com:8080/s3fWebService/services/SpeedShip2Service?wsdl\n\n * @author Soft Scripts Team \n * @version 20140325-01\n * @date 2014-03-29\n */\nclass MynewServiceStructRateServiceOptions extends MynewServiceWsdlClass\n{\n /**\n * The additionalParameters\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var MynewServiceStructAdditionalParameters\n */\n public $additionalParameters;\n /**\n * The carbonNeutralIndicator\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var string\n */\n public $carbonNeutralIndicator;\n /**\n * The codIndicator\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var string\n */\n public $codIndicator;\n /**\n * The confirmDeliveryIndicator\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var string\n */\n public $confirmDeliveryIndicator;\n /**\n * The deliveryOnSatIndicator\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var string\n */\n public $deliveryOnSatIndicator;\n /**\n * The handlingChargeIndicator\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var string\n */\n public $handlingChargeIndicator;\n /**\n * The returnLabelIndicator\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var string\n */\n public $returnLabelIndicator;\n /**\n * The schedulePickupIndicator\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var string\n */\n public $schedulePickupIndicator;\n /**\n * The shipmentType\n * Meta informations extracted from the WSDL\n * - minOccurs : 0\n * - nillable : true\n * @var string\n */\n public $shipmentType;\n /**\n * Constructor method for RateServiceOptions\n * @see parent::__construct()\n * @param MynewServiceStructAdditionalParameters $_additionalParameters\n * @param string $_carbonNeutralIndicator\n * @param string $_codIndicator\n * @param string $_confirmDeliveryIndicator\n * @param string $_deliveryOnSatIndicator\n * @param string $_handlingChargeIndicator\n * @param string $_returnLabelIndicator\n * @param string $_schedulePickupIndicator\n * @param string $_shipmentType\n * @return MynewServiceStructRateServiceOptions\n */\n public function __construct($_additionalParameters = NULL,$_carbonNeutralIndicator = NULL,$_codIndicator = NULL,$_confirmDeliveryIndicator = NULL,$_deliveryOnSatIndicator = NULL,$_handlingChargeIndicator = NULL,$_returnLabelIndicator = NULL,$_schedulePickupIndicator = NULL,$_shipmentType = NULL)\n {\n parent::__construct(array('additionalParameters'=>$_additionalParameters,'carbonNeutralIndicator'=>$_carbonNeutralIndicator,'codIndicator'=>$_codIndicator,'confirmDeliveryIndicator'=>$_confirmDeliveryIndicator,'deliveryOnSatIndicator'=>$_deliveryOnSatIndicator,'handlingChargeIndicator'=>$_handlingChargeIndicator,'returnLabelIndicator'=>$_returnLabelIndicator,'schedulePickupIndicator'=>$_schedulePickupIndicator,'shipmentType'=>$_shipmentType),false);\n }\n /**\n * Get additionalParameters value\n * @return MynewServiceStructAdditionalParameters|null\n */\n public function getAdditionalParameters()\n {\n return $this->additionalParameters;\n }\n /**\n * Set additionalParameters value\n * @param MynewServiceStructAdditionalParameters $_additionalParameters the additionalParameters\n * @return MynewServiceStructAdditionalParameters\n */\n public function setAdditionalParameters($_additionalParameters)\n {\n return ($this->additionalParameters = $_additionalParameters);\n }\n /**\n * Get carbonNeutralIndicator value\n * @return string|null\n */\n public function getCarbonNeutralIndicator()\n {\n return $this->carbonNeutralIndicator;\n }\n /**\n * Set carbonNeutralIndicator value\n * @param string $_carbonNeutralIndicator the carbonNeutralIndicator\n * @return string\n */\n public function setCarbonNeutralIndicator($_carbonNeutralIndicator)\n {\n return ($this->carbonNeutralIndicator = $_carbonNeutralIndicator);\n }\n /**\n * Get codIndicator value\n * @return string|null\n */\n public function getCodIndicator()\n {\n return $this->codIndicator;\n }\n /**\n * Set codIndicator value\n * @param string $_codIndicator the codIndicator\n * @return string\n */\n public function setCodIndicator($_codIndicator)\n {\n return ($this->codIndicator = $_codIndicator);\n }\n /**\n * Get confirmDeliveryIndicator value\n * @return string|null\n */\n public function getConfirmDeliveryIndicator()\n {\n return $this->confirmDeliveryIndicator;\n }\n /**\n * Set confirmDeliveryIndicator value\n * @param string $_confirmDeliveryIndicator the confirmDeliveryIndicator\n * @return string\n */\n public function setConfirmDeliveryIndicator($_confirmDeliveryIndicator)\n {\n return ($this->confirmDeliveryIndicator = $_confirmDeliveryIndicator);\n }\n /**\n * Get deliveryOnSatIndicator value\n * @return string|null\n */\n public function getDeliveryOnSatIndicator()\n {\n return $this->deliveryOnSatIndicator;\n }\n /**\n * Set deliveryOnSatIndicator value\n * @param string $_deliveryOnSatIndicator the deliveryOnSatIndicator\n * @return string\n */\n public function setDeliveryOnSatIndicator($_deliveryOnSatIndicator)\n {\n return ($this->deliveryOnSatIndicator = $_deliveryOnSatIndicator);\n }\n /**\n * Get handlingChargeIndicator value\n * @return string|null\n */\n public function getHandlingChargeIndicator()\n {\n return $this->handlingChargeIndicator;\n }\n /**\n * Set handlingChargeIndicator value\n * @param string $_handlingChargeIndicator the handlingChargeIndicator\n * @return string\n */\n public function setHandlingChargeIndicator($_handlingChargeIndicator)\n {\n return ($this->handlingChargeIndicator = $_handlingChargeIndicator);\n }\n /**\n * Get returnLabelIndicator value\n * @return string|null\n */\n public function getReturnLabelIndicator()\n {\n return $this->returnLabelIndicator;\n }\n /**\n * Set returnLabelIndicator value\n * @param string $_returnLabelIndicator the returnLabelIndicator\n * @return string\n */\n public function setReturnLabelIndicator($_returnLabelIndicator)\n {\n return ($this->returnLabelIndicator = $_returnLabelIndicator);\n }\n /**\n * Get schedulePickupIndicator value\n * @return string|null\n */\n public function getSchedulePickupIndicator()\n {\n return $this->schedulePickupIndicator;\n }\n /**\n * Set schedulePickupIndicator value\n * @param string $_schedulePickupIndicator the schedulePickupIndicator\n * @return string\n */\n public function setSchedulePickupIndicator($_schedulePickupIndicator)\n {\n return ($this->schedulePickupIndicator = $_schedulePickupIndicator);\n }\n /**\n * Get shipmentType value\n * @return string|null\n */\n public function getShipmentType()\n {\n return $this->shipmentType;\n }\n /**\n * Set shipmentType value\n * @param string $_shipmentType the shipmentType\n * @return string\n */\n public function setShipmentType($_shipmentType)\n {\n return ($this->shipmentType = $_shipmentType);\n }\n /**\n * Method called when an object has been exported with var_export() functions\n * It allows to return an object instantiated with the values\n * @see MynewServiceWsdlClass::__set_state()\n * @uses MynewServiceWsdlClass::__set_state()\n * @param array $_array the exported values\n * @return MynewServiceStructRateServiceOptions\n */\n public static function __set_state(array $_array,$_className = __CLASS__)\n {\n return parent::__set_state($_array,$_className);\n }\n /**\n * Method returning the class name\n * @return string __CLASS__\n */\n public function __toString()\n {\n return __CLASS__;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914262,"cells":{"blob_id":{"kind":"string","value":"617a497ff7baee1cbfff599d5e4eb13685c86f82"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"BradCrumb/ze-swagger-codegen"},"path":{"kind":"string","value":"/src/V30/Hydrator/CallbackHydrator.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1206,"string":"1,206"},"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":"pathItemHydrator = $pathItemHydrator;\n }\n\n /**\n * @inheritDoc\n *\n * @param Callback $object\n *\n * @return Callback\n */\n public function hydrate(array $data, $object)\n {\n foreach ($data as $name => $pathItem) {\n $object->setExpression($name, $this->pathItemHydrator->hydrate($pathItem, new PathItem()));\n }\n\n return $object;\n }\n\n /**\n * @inheritDoc\n *\n * @param Callback $object\n *\n * @return array\n */\n public function extract($object)\n {\n $data = [];\n\n foreach ($object->getExpressions() as $name => $pathItem) {\n $data[$name] = $this->pathItemHydrator->extract($pathItem);\n }\n\n return $data;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914263,"cells":{"blob_id":{"kind":"string","value":"52d4dc3fbe2b301ff27f2ba43b3d30e40be79fde"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"shayleydon/deputy"},"path":{"kind":"string","value":"/Role.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":770,"string":"770"},"score":{"kind":"number","value":3.421875,"string":"3.421875"},"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 = $id;\n $this->name = $name;\n $this->parentId = $parentId;\n }\n\n /**\n * Returns the role id.\n *\n * @return int\n */\n public function getId()\n {\n return $this->id;\n }\n\n /**\n * Returns the role name.\n *\n * @return string\n */\n public function getName()\n {\n return $this->name;\n }\n \n /**\n * Returns the parent role id.\n *\n * @return int\n */\n public function getParentId()\n {\n return $this->parentId;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914264,"cells":{"blob_id":{"kind":"string","value":"91508b6175bfafd46c6ef0a168f15c73a551118d"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"pedrosland/zf2-console-test"},"path":{"kind":"string","value":"/module/Transactions/src/Transactions/Data/CurrencyWebservice.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":930,"string":"930"},"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":"abrirConexion();\n\t\t}\n\n\t\tfunction abrirConexion(){\n\t\t\ttry{\n\t\t\t\t/*$handler = new PDO('mysql:host=127.0.0.1;dbname=residenciasitsa','root',''); //Localhost\n\t\t\t\t$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);*/\n\t\t\t\t$handler = new PDO('mysql:host=185.201.11.65;dbname=u276604013_dbres','u276604013_itsa','jesus_321'); //Localhost\n\t\t\t\t$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\t\t\t} catch(PDOException $e) {\n\t\t\t\techo $e->getMessage();\n\t\t\t}\n\t\t\t$this->conection = $handler;\n\t\t}\n\n\t\tfunction obtenerAlumnos(){\n\t\t\t\t$sql = \"\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tidAlumno AS id,\n\t\t\t\t\t\t\tCONCAT(vNombre,' ',vApellidoPaterno,' ',vApellidoMaterno,' ',vNumeroControl) AS descripcion\n\t\t\t\t\t\tFROM alumnos\n\t\t\t\t\";\n\t\t\t\t$alumnos = $this->conection->prepare($sql);\n\t\t\t\t$alumnos->execute();\n\t\t\t\t$respuesta = $alumnos->fetchAll();\n\t\t\t\treturn $respuesta;\n\t\t}\n\t\tfunction obtenerAlumnosPorCarrera($idCarrera){\n\t\t\t$sql = \"\n\t\t\t\tSELECT\n\t\t\t\t\tidAlumno AS id,\n\t\t\t\t\tCONCAT(vNombre,' ',vApellidoPaterno,' ',vApellidoMaterno,' ',vNumeroControl) AS descripcion\n\t\t\t\tFROM alumnos\n\t\t\t\tWHERE idCarrera = '$idCarrera'\n\t\t\t\";\n\t\t\t$alumnos = $this->conection->prepare($sql);\n\t\t\t$alumnos->execute();\n\n\n\t\t\t$respuesta = $alumnos->fetchAll();\n\n\n\t\t\treturn $respuesta;\n\t\t}\n\n\t\tpublic function getCarreras(){\n\t\t\t$sql = \"SELECT\n\t\t\t\t\t\tidCarrera AS id,\n\t\t\t\t\t\tvCarrera AS descripcion\n\t\t\t\t\tFROM carreras WHERE bActivo = 1 \";\n\t\t\t$carreras = $this->conection->prepare($sql);\n\t\t\t$carreras->execute();\n\t\t\treturn $carreras->fetchAll();\n\t\t}\n\t\tfunction guardarMensaje($idAlumno,$msg,$titulo,$bActive,$idMensaje){\n\t\t\tif($idMensaje == 0){\n\t\t\t\t$sql = \"\n\t\t\t\t\t\t\t INSERT INTO mensajesporalumno\n\t\t\t\t\t\t\t (\n\t\t\t\t\t\t\t\t\tidAlumno,\n\t\t\t\t\t\t\t\t\tvMensaje,\n\t\t\t\t\t\t\t\t\tvTitulo,\n\t\t\t\t\t\t\t\t\tbActive\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t VALUES(\n\t\t\t\t\t\t\t\t $idAlumno,\n\t\t\t\t\t\t\t\t '\".$msg.\"',\n\t\t\t\t\t\t\t\t '\".$titulo.\"',\n\t\t\t\t\t\t\t\t $bActive\n\t\t\t\t\t\t\t)\n\t\t\t\t\";\n\t\t\t}else{\n\t\t\t\t$sql = \"\n\t\t\t\t\t\t\t UPDATE mensajesporalumno\n\t\t\t\t\t\t\t SET\n\t\t\t\t\t\t\t\t\tvMensaje = '\".$msg.\"',\n\t\t\t\t\t\t\t\t\tvTitulo = '\".$titulo.\"'\n\t\t\t\t\t\t\t WHERE idMensaje = $idMensaje\n\t\t\t\t\";\n\t\t\t}\n\t\t\t$mensajes = $this->conection->prepare($sql);\n\t\t\treturn $mensajes->execute();\n\t\t}\n\n\t\tfunction getMensajes($inicio,$rowMax,$activo,$idAlumno){\n\n\t\t\t$sql = \"\n\t\t\t\t\tSELECT\n\t\t\t\t\t\ta.idMensaje,\n\t\t\t\t\t\ta.vMensaje,\n\t\t\t\t\t\tCONCAT(b.vNombre,' ',b.vApellidoPaterno,' ',b.vApellidoPaterno) AS vNombre,\n\t\t\t\t\t\ta.bActive\n\t\t\t\t\tFROM mensajesporalumno AS a\n\t\t\t\t\tINNER JOIN alumnos b ON(a.idAlumno = b.idAlumno)\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tCASE WHEN $activo = -1 THEN a.bActive = a.bActive ELSE a.bActive = $activo END AND\n\t\t\t\t\t\t\t\tCASE WHEN $idAlumno = 0 THEN a.idAlumno = a.idAlumno ELSE a.idAlumno = $idAlumno END\n\t\t\t\t\tORDER BY a.idMensaje DESC LIMIT $inicio,$rowMax\n\t\t\t\";\n\t\t\t$mensajes = $this->conection->prepare($sql);\n\t\t\t$mensajes->execute();\n\t\t\treturn $mensajes->fetchAll();\n\t\t}\n\t\tfunction obtenerNumeroDeMensajes($activo,$idAlumno){\n\t\t\t$sql = \"\n\t\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\t\tCOUNT(1)\n\t\t\t\t\t\t\t\tFROM mensajesporalumno\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t \t\t\tCASE WHEN $activo = -1 THEN bActive = bActive ELSE bActive = $activo END AND\n\t\t\t\t\t\t\t\t\t\t\tCASE WHEN $idAlumno = 0 THEN idAlumno = idAlumno ELSE idAlumno = $idAlumno END\n\t\t\t\t\t\t\t\";\n\t\t\t$numeroMensajes = $this->conection->prepare($sql);\n\t\t\t$numeroMensajes->execute();\n\t\t\treturn $numeroMensajes->fetchColumn();\n\t\t}\n\t\tfunction DesactivarActivar($idMensaje,$bit){\n\t\t\t$sql = \"\n\t\t\t\tUPDATE mensajesporalumno\n\t\t\t\t\t\t\t SET bActive = $bit\n\t\t\t\tWHERE idMensaje = $idMensaje\n\t\t\t\";\n\t\t\t$desactivar = $this->conection->prepare($sql);\n\t\t\tif($desactivar->execute()){\n\t\t\t\treturn 1;\n\t\t\t}else{\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tfunction obtenerInformacionMensaje($idMensaje){\n\t\t\t$sql = \"\n\t\t\t\tSELECT\n\t\t\t\t\t\ta.idMensaje,\n\t\t\t\t\t\ta.vMensaje,\n\t\t\t\t\t\ta.idAlumno,\n\t\t\t\t\t\ta.vTitulo,\n\t\t\t\t\t\tb.idCarrera\n\t\t\t\tFROM mensajesporalumno AS a\n\t\t\t\tINNER JOIN alumnos b ON(a.idAlumno = b.idAlumno)\n\t\t\t\tWHERE idMensaje = $idMensaje\n\t\t\t\";\n\t\t\t$info = $this->conection->prepare($sql);\n\t\t\t$info->execute();\n\t\t\treturn $info->fetchAll();\n\t\t}\n\t}\n\n\n\t$operacion = @$_POST[\"operacion\"];\n\n\tswitch ($operacion) {\n\t\t\tcase 1:\n\t\t\t\t$helper = new helper();\n\t\t\t\t$idCarrera = $_POST[\"idCarrera\"];\n\t\t\t\t$alumnos = $helper->obtenerAlumnosPorCarrera($idCarrera);\n\t\t\t\techo \"\";\n\t\t\t\tforeach ($alumnos AS $k) {\n\t\t\t\t\techo \"\";\n\t\t\t\t}\n\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t$helper = new helper();\n\t\t\t\t$idMensaje = $_POST[\"idMensaje\"];\n\t\t\t\t$idAlumno = $_POST[\"idAlumno\"];\n\t\t\t\t$msg = $_POST[\"mensaje\"];\n\t\t\t\t$titulo = $_POST[\"titulo\"];\n\t\t\t\t$bActive = $_POST[\"bActive\"];\n\n\t\t\t echo\t$helper->guardarMensaje($idAlumno,$msg,$titulo,$bActive,$idMensaje);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t$helper = new helper();\n\t\t\t\t$mensajes = $helper->getMensajes($_POST[\"inicio\"],$_POST[\"fin\"],$_POST[\"activo\"],$_POST[\"idAlumno\"]);\n\n\n\t\t\t\t$tabla = \"\";\n\t\t\t\t\t$tabla .= \"\";\n\t\t\t\t\t\t$tabla .= \"Id mensaje\";\n\t\t\t\t\t\t$tabla .= \"Mensajes\";\n\t\t\t\t\t\t$tabla .= \"Nombre\";\n\t\t\t\t\t\t$tabla .= \"Activo\";\n\t\t\t\t\t\t$tabla .= \"Editar\";\n\t\t\t\t\t\t$tabla .= \"Desactivar\";\n\t\t\t\t\t$tabla .= \"\";\n\t\t\t\t$tabla .= \"\";\n\t\t\t\tforeach ($mensajes as $m) {\n\t\t\t\t\t$tabla .= \"\";\n\n\t\t\t\t\t$tabla .= \"\".$m[\"idMensaje\"].\"\";\n\t\t\t\t\t$tabla .= \"\".$m[\"vMensaje\"].\"\";\n\t\t\t\t\t$tabla .= \"\".$m[\"vNombre\"].\"\";\n\t\t\t\t\tif($m[\"bActive\"] == 1){\n\t\t\t\t\t\t$tabla .= \"\";\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$tabla .= \"\";\n\t\t\t\t\t}\n\t\t\t\t\t$tabla .= \"\";\n\t\t\t\t\tif($m[\"bActive\"] == 1){\n\t\t\t\t\t\t\t$tabla .= \"\";\n\t\t\t\t\t}else{\n\t\t\t\t\t \t$tabla .= \"\";\n\t\t\t\t\t}\n\t\t\t\t\t$tabla .= \"\";\n\t\t\t\t}\n\t\t\t\t$paginador = $helper->obtenerNumeroDeMensajes($_POST[\"activo\"],$_POST[\"idAlumno\"]);\n\t\t\t\t$respuesta = \"
    \";\n\t\t\t\t$j = 1;\n\t\t\t\tfor($i = 0;$i < $paginador; $i+=7){\n\t\t\t\t\t\t$respuesta .= \"
  • \".$j.\"
  • \";\n\t\t\t\t\t\t$j++;\n\t\t\t\t}\n\n\t\t\t\t$respuesta .= \"
\";\n\n\t\t\t\t $res = array(\"mensajes\" => $tabla , \"paginador\" => $respuesta);\n\n\t\t\t\techo json_encode($res);\n\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\t$helper = new helper();\n\t\t\t\techo $helper->DesactivarActivar($_POST[\"idMensaje\"],$_POST[\"activo\"]);\n\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\t$helper = new helper();\n\t\t\t\techo json_encode($helper->obtenerInformacionMensaje($_POST[\"idMensaje\"]));\n\t\t\tbreak;\n\n\t\t\tdefault:\n\n\t\t\t\tbreak;\n\t\t}\n?>\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914266,"cells":{"blob_id":{"kind":"string","value":"8c37d82c1738a642e8c66b3c6edf112138d60e1c"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"iakbarp/bukuangkatan"},"path":{"kind":"string","value":"/edit.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8348,"string":"8,348"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"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":"\r\n
\r\n
\r\n

Data Mahasiswa &raquo; Edit Data

\r\n
\r\n\r\n Data gagal disimpan, silahkan coba lagi.
'; // maka tampilkan 'Data gagal disimpan, silahkan coba lagi.'\r\n }\r\n }\r\n\r\n if(isset($_GET['pesan']) == 'sukses'){ // jika terdapat pesan=sukses sebagai bagian dari berhasilnya query update dieksekusi\r\n echo '
Data berhasil disimpan. <- Kembali
'; // maka tampilkan 'Data berhasil disimpan.'\r\n }\r\n ?>\r\n \r\n
\r\n
\r\n \r\n
\r\n \" class=\"form-control\" placeholder=\"nim\" required>\r\n
\r\n
\r\n
\r\n \r\n
\r\n \" class=\"form-control\" placeholder=\"Nama\" required>\r\n
\r\n
\r\n
\r\n \r\n
\r\n '; ?>\r\n
\r\n
\r\n Ganti Foto (3x4 cm) : \r\n
\r\n
\r\n
\r\n \r\n
\r\n \r\n
\r\n
\r\n
\r\n \r\n
\r\n \" class=\"form-control\" placeholder=\"Tempat Lahir\" required>\r\n
\r\n
\r\n
\r\n \r\n
\r\n \" class=\"input-group datepicker form-control\" date=\"\" data-date-format=\"dd-mm-yyyy\" placeholder=\"dd-mm-yyyy\" required>\r\n
\r\n
\r\n\r\n
\r\n \r\n
\r\n \r\n
\r\n
\r\n
\r\n \r\n
\r\n \r\n
\r\n
\r\n
\r\n \r\n
\r\n \" class=\"form-control\" placeholder=\"No Telepon\" required>\r\n
\r\n
\r\n
\r\n \r\n
\r\n \r\n
\r\n
\r\n Prodi Sekarang : \r\n
\r\n
\r\n
\r\n \r\n
\r\n \r\n Batal\r\n
\r\n
\r\n
\r\n
\r\n
\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914267,"cells":{"blob_id":{"kind":"string","value":"965ee5a2bf9ba4e440d82d8de935b8c2afe7651a"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"evgKoval/exchanger"},"path":{"kind":"string","value":"/app/Http/Controllers/Api/V1/CurrenciesRatesController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1799,"string":"1,799"},"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":"getPrice('BTC', 'UAH');\n\t // $rates[] = $coinbase->getPrice('ETH', 'UAH');\n\t // $rates[] = $coinbase->getPrice('BCH', 'UAH');\n\t // $rates[] = $coinbase->getPrice('LTC', 'UAH');\n\t return $coinbase->user();\n\n\t //return $rates;\n\t}\n\n\t/**\n\t * Show the form for creating a new resource.\n\t *\n\t * @return \\Illuminate\\Http\\Response\n\t */\n\tpublic function create()\n\t{\n\t //\n\t}\n\n\t/**\n\t * Store a newly created resource in storage.\n\t *\n\t * @param \\Illuminate\\Http\\Request $request\n\t * @return \\Illuminate\\Http\\Response\n\t */\n\tpublic function store(Request $request)\n\t{\n\t $coinbase = new Coinbase();\n\n\t return $coinbase->buy($request->all());\n\t}\n\n\t/**\n\t * Display the specified resource.\n\t *\n\t * @param int $id\n\t * @return \\Illuminate\\Http\\Response\n\t */\n\tpublic function show($id)\n\t{\n\t //\n\t}\n\n\t/**\n\t * Show the form for editing the specified resource.\n\t *\n\t * @param int $id\n\t * @return \\Illuminate\\Http\\Response\n\t */\n\tpublic function edit($id)\n\t{\n\t //\n\t}\n\n\t/**\n\t * Update the specified resource in storage.\n\t *\n\t * @param \\Illuminate\\Http\\Request $request\n\t * @param int $id\n\t * @return \\Illuminate\\Http\\Response\n\t */\n\tpublic function update(Request $request, $id)\n\t{\n\t //\n\t}\n\n\t/**\n\t * Remove the specified resource from storage.\n\t *\n\t * @param int $id\n\t * @return \\Illuminate\\Http\\Response\n\t */\n\tpublic function destroy($id)\n\t{\n\t //\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914268,"cells":{"blob_id":{"kind":"string","value":"115317a27fc7fda3619020f6df06d123cdaf5419"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"prodigyworks/Trianik"},"path":{"kind":"string","value":"/session-image-upload.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":488,"string":"488"},"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":"beginTransaction();\n\t\t\n\t\t$image = new ImageClass();\n\t\t$image->setDescription(\"User Profile\");\n\t\t$image->uploadFromFile(\"file\", 16000, 16000);\n\t\t$image->setSessionid(session_id());\n\t\t$image->insertRecord();\n\t\t\n\t\tSessionControllerClass::getDB()->commit();\n\t\t\n\t} catch (Exception $e) {\n\t\tSessionControllerClass::getDB()->rollBack();\n\t}\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914269,"cells":{"blob_id":{"kind":"string","value":"b3ad15670204e0309b6f87a685cb34631bb550ba"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"mpiton/cours-php"},"path":{"kind":"string","value":"/vendredi/test.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":858,"string":"858"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"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":"\";\necho \"\";\necho \"\";\necho \"\";\n\n\n$destination = 'upload';\n$existe = file_exists($destination);\n\nif ($existe) {\n echo \"La destination existe\";\n}\nelse {\n echo \"il va falloir créer un repertoire upload
\";\n $creationRepertoire = mkdir($destination);\n if ($creationRepertoire) {\n echo \"repertoire crée !\";\n }\n else {\n echo \"on a un problème !\";\n }\n}\n\n\n\n\n\n\n\nuploadMonFichier($tableau);\n\n\nrequire(\"footer.php\");\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914270,"cells":{"blob_id":{"kind":"string","value":"c57fa56f9b5096fc9e5bc6a8e6d9fd0e218fa939"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"JoshuaW5/COMP3512_ASG2"},"path":{"kind":"string","value":"/includes/SubjectDB.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1104,"string":"1,104"},"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":"baseSQL;}\r\n\r\nprotected function getKeyFieldName(){return $this->keyFieldName;}\r\n\r\npublic function getByPaintingID ($id) {\r\n\r\n$sql = \"SELECT DISTINCT SubjectName, SubjectID FROM Subjects JOIN PaintingSubjects USING (SubjectID) WHERE PaintingID = ?\";\r\n\r\n\r\n\r\nif (count($id) > 1) {\r\n\r\n$sql = \"SELECT DISTINCT SubjectName, SubjectID FROM Subjects JOIN PaintingSubjects USING (SubjectID) WHERE PaintingID IN (\";\r\n\r\nfor ($i=1; $i <= count($id); $i++) {\r\n\r\n$sql .= \" ? \";\r\n\r\nif ($i != count($id)) { $sql .= \",\"; }\r\n\r\n\r\n\r\n}\r\n\r\n$sql .= \")\";\r\n\r\n}\r\n\r\n\r\n\r\n$result = DBHelper::runQuery($this->getConnection(), $sql, $id);\r\n\r\n\r\n\r\nreturn $result;\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914271,"cells":{"blob_id":{"kind":"string","value":"8b029674029f7349b4dec509bcbb2740c6fb5e80"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"fanzhaogui/PHP_More_Testing"},"path":{"kind":"string","value":"/code_test/pattern/2_factory/2_3_abstract_factory/SQLiteFactory.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":300,"string":"300"},"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":"';\n\t}\n\n\n\tpublic function createArticle()\n\t{\n\t\techo \"sqlite create article at \" . __FUNCTION__ . '
';\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914272,"cells":{"blob_id":{"kind":"string","value":"d7382d9b1fe0bd090a69fc38498202c11604ca1a"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"BialekM/training"},"path":{"kind":"string","value":"/Eagles/SarosTest/Konwerter języków PHP-Java/wycinara.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":485,"string":"485"},"score":{"kind":"number","value":3.390625,"string":"3.390625"},"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":"wytnijZmienna($t1->znajdz1('System.out.println(\"z upa\");'));\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914273,"cells":{"blob_id":{"kind":"string","value":"7b5fcdcbfbc37d0ab96eccb14126b3b3f67c2a68"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"tapiau/php-playground"},"path":{"kind":"string","value":"/fourier/src/FFT.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":667,"string":"667"},"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":"sampleList = $sampleList;\n\t}\n\n\tpublic function calcWeight($freq)\n\t{\n\t\t$modConst = $freq*2*M_PI;\n\n\t\treturn array_reduce(\n\t\t\t$this->sampleList->sampleList,\n\t\t\tfunction($state,$item) use ($modConst)\n\t\t\t{\n\t\t\t\treturn [\n\t\t\t\t\t'sum'=> $state['sum']+cos($modConst*$state['count']/$this->sampleList->sampleRate)*$item,\n\t\t\t\t\t'count'=>$state['count']+1\n\t\t\t\t];\n\t\t\t},\n\t\t\t[\n\t\t\t\t'sum'=>0,\n\t\t\t\t'count'=>0\n\t\t\t]\n\t\t)['sum'];\n\n\t}\n\n\tpublic function normalizeWeightList()\n\t{\n\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914274,"cells":{"blob_id":{"kind":"string","value":"c34357a9858781bf4ae27cb3790ac33c531899eb"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"ahmedAlraimi/Tasarim"},"path":{"kind":"string","value":"/Term Project/1 Full Project/Design_Pattern/models/ManagementProfile.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":586,"string":"586"},"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":"position = $position;\n\t}\n\n\tpublic function setAddress($address){\n\t\t$this->address = $address;\n\t}\n\n\tpublic function setPhoneNumber($phone_number){\n\t\t$this->phone_number = $phone_number;\n\t}\n\n\n \n public function preview(){\n \t$profile = array(\n \t\t'position' \t\t=> $this->position,\n \t\t'address' \t\t=> $this->address,\n \t\t'phone_number' \t=> $this->phone_number\n \t);\n return $profile;\n }\n\n}\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914275,"cells":{"blob_id":{"kind":"string","value":"5fece835b6b7dc2e363dad94a89a13c713e51dde"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"denst/38076DGF"},"path":{"kind":"string","value":"/www/application/classes/helper/password.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":522,"string":"522"},"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":"companyDepartmentId;\n }\n\n /**\n * @param mixed $companyDepartmentId\n */\n public function setCompanyDepartmentId($companyDepartmentId)\n {\n $this->companyDepartmentId = $companyDepartmentId;\n }\n\n /**\n * @return mixed\n */\n public function getCompanyIdFk()\n {\n return $this->companyIdFk;\n }\n\n /**\n * @param mixed $companyIdFk\n */\n public function setCompanyIdFk($companyIdFk)\n {\n $this->companyIdFk = $companyIdFk;\n }\n\n /**\n * @return mixed\n */\n public function getCompanyDepartmentName()\n {\n return $this->companyDepartmentName;\n }\n\n /**\n * @param mixed $companyDepartmentName\n */\n public function setCompanyDepartmentName($companyDepartmentName)\n {\n $this->companyDepartmentName = $companyDepartmentName;\n }\n\n /**\n * @return mixed\n */\n public function getCompanyDepartmentDateInsert()\n {\n return $this->companyDepartmentDateInsert;\n }\n\n /**\n * @param mixed $companyDepartmentDateInsert\n */\n public function setCompanyDepartmentDateInsert($companyDepartmentDateInsert)\n {\n $this->companyDepartmentDateInsert = $companyDepartmentDateInsert;\n }\n\n /**\n * @return mixed\n */\n public function getCompanyDepartmentDateUpdate()\n {\n return $this->companyDepartmentDateUpdate;\n }\n\n /**\n * @param mixed $companyDepartmentDateUpdate\n */\n public function setCompanyDepartmentDateUpdate($companyDepartmentDateUpdate)\n {\n $this->companyDepartmentDateUpdate = $companyDepartmentDateUpdate;\n }\n\n\n\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914277,"cells":{"blob_id":{"kind":"string","value":"24efc5f7c53299b1b0b5da1fa27f90a3fda15cda"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"liangpig1/worddestructor"},"path":{"kind":"string","value":"/WordDestructor/Lib/Model/WordlistModel.class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1001,"string":"1,001"},"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":"where(\"id=\".$listId)->find();\r\n }\r\n \r\n public function getListByName($name)\r\n {\r\n return $this->where(\"name='\".$name.\"'\")->find();\r\n }\r\n\r\n public function getListsByUser($userId)\r\n {\r\n return $this->where(\"userId=\".$userId)->select();\r\n }\r\n \r\n public function getAllLists()\r\n {\r\n return $this->select();\r\n }\r\n \r\n public function removeWordList($listId)\r\n {\r\n return $this->where(\"id=\".$listId)->delete();\r\n }\r\n \r\n public function removeWordListByUser($userId)\r\n {\r\n return $this->where(\"userId=\".$userId)->delete();\r\n }\r\n\r\n //new Empty WordList\r\n public function addWordList($listData)\r\n {\r\n\t\t$listData[\"progress\"] = 0;\r\n return $this->add($listData);\r\n }\r\n \r\n public function updateWordList($listInfo)\r\n {\r\n return $this->save($listInfo);\r\n }\r\n}\r\n?>\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914278,"cells":{"blob_id":{"kind":"string","value":"fbf77b9d309f21fe1a74be01e2de6d87ed3a910a"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"borry262921984/genaku"},"path":{"kind":"string","value":"/demo4.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2313,"string":"2,313"},"score":{"kind":"number","value":3.5,"string":"3.5"},"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":" ';\n echo $_sxe->version;\n echo \"\\n\\n\";\n\n // 2) 如果加上索引号则可以指定打印目标(前提是存在的数组索引号)\n echo '2 -> ';\n echo $_sxe->version[2];\n echo \"\\n\\n\";\n\n // 3) 如果有多个version标签$_sxe->version其实是一个数组\n echo '3 -> ';\n print_r($_sxe->version);\n echo \"\\n\\n\";\n\n // 4) 遍历数组(一级)标签\n echo '4 -> ';\n foreach ($_sxe->version as $v){\n echo '['.$v.']';\n }\n echo \"\\n\\n\";\n\n // 5) 访问二级数组的标签\n //如果要访问二级标签,必须一层一层指明\n echo '5 -> ';\n echo $_sxe->user[1]->name;\n echo \"\\n\\n\";\n\n // 6) 遍历所有的二级标签的name值\n echo '6 -> ';\n foreach ($_sxe->user as $_user){\n echo '['.$_user->name.']';\n }\n echo \"\\n\\n\";\n\n // 7) 输出第二个user里的author的性别谁谁谁\n //attributes()函数能获取SimpleXML元素的属性\n //如果元素里面有多个属性,则以属性名称来指向属性内容(虽然不显示数字索引,但默认生成)\n //元素指针也会生成数字索引,顺序则按照属性在元素内的先后顺序生成\n //例1: 生成数组是[0]->女 [1]->woman\n //例2: 生成数组是[0]->woman [1]->女\n echo '7 -> ';\n print_r($_sxe->user[1]->author->attributes());\n echo \"\\t\";\n echo $_sxe->user[1]->author->attributes()['E_sex'];\n echo \"\\n\\t\";\n echo $_sxe->user[1]->author->attributes()[1];\n echo \"\\n\\n\";\n\n // 8) 使用xpath来获取xml节点操作\n //获取version标签的值\n echo '8 -> ';\n $_version = $_sxe -> xpath('/root');\n //由于转换后属于SimpleXML数组,所以需要通过json来编译成普通数组才能正常操作\n $jsonStr = json_encode($_version);\n $jsonArray = json_decode($jsonStr,true);\n print_r($jsonArray[0]);\n echo '这是最高级的数组元素:'.$jsonArray[0]['user'][2]['author'];\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914279,"cells":{"blob_id":{"kind":"string","value":"b0d7a6921f814c24cf1ab274b291f5bc15271d29"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"wuluo/KMB"},"path":{"kind":"string","value":"/kohana/modules/misc/classes/Base62.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":798,"string":"798"},"score":{"kind":"number","value":3.28125,"string":"3.28125"},"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);\n\t\t\n\t\treturn $output;\n\t}\n\t\n\tpublic function decode($input) {\n\t\t$length = strlen($input);\n\t\t\n\t\t$number = 0;\n\t\t$baseChars = array_flip(str_split(Base62::$baseChars));\n\t\tfor($i = 0; $i < $length; ++$i) {\n\t\t\t$number += $baseChars[$input[$i]] * pow(Base62::BASE, $length - $i - 1);\n\t\t}\n\t\treturn number_format($number, 0, '', '');\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914280,"cells":{"blob_id":{"kind":"string","value":"a59ead04ca3c143d574dfdb58a6ef5e0959b0fe3"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"DyoungDsea/frenxy"},"path":{"kind":"string","value":"/webcontrol/clean.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1401,"string":"1,401"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"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":"real_escape_string($value);\n return $value; \n }\n\n @$idc = clean($_SESSION['userid']);\n\n\n function formatDate($data){\n return date(\"d M, Y\", strtotime($data));\n }\n\n function formatDateTime($data){\n return date(\"d M Y, h:i:sa\", strtotime($data));\n }\n\n function fetchAssoc($data){\n return $data->fetch_assoc();\n }\n\n\n function formatTime($data){\n return date(\"H:i\", strtotime($data));\n }\n\n function runQuery($statement){\n GLOBAL $conn;\n return $conn->query($statement);\n }\n\n function addToDate($now, $howManyDays){\n $date = $now;\n $date = strtotime($date);\n $date = strtotime($howManyDays.' day', $date); //strtotime(\"+7 day\", $date);\n return date('Y-m-d h:i:s', $date);\n }\n\n function datePlusOneHour(){ \n $now = gmdate(\"Y-m-d H:i:s\");\n $date = date('Y-m-d H:i:s',strtotime(\"+1 hour\",strtotime($now)));\n return $date;\n }\n\n function limitText($text,$limit){\n if(str_word_count($text, 0)>$limit){\n $word = str_word_count($text,2);\n $pos=array_keys($word);\n $text=substr($text,0,$pos[$limit]). '...';\n }\n return $text;\n}\n\n $_SESSION['current_page'] = $_SERVER['REQUEST_URI']; //get the current url link"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914281,"cells":{"blob_id":{"kind":"string","value":"b6b47103d5c848189584461d16e392a1ee4e12e7"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"halvaroz/restaurant"},"path":{"kind":"string","value":"/library/FlashBag.class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":750,"string":"750"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"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":"image = new Logo();\n $this->map_image = new Logo();\n $this->base = new BaseHelper();\n }\n\n /**\n * @return mixed\n */\n public function getId()\n {\n return $this->id;\n }\n\n /**\n * @param mixed $id\n */\n public function setId($id)\n {\n $this->id = $id;\n }\n\n /**\n * @return mixed\n */\n public function getName()\n {\n return $this->name;\n }\n\n /**\n * @param mixed $name\n */\n public function setName($name)\n {\n $this->name = $name;\n }\n\n /**\n * @return mixed\n */\n public function getNameEn()\n {\n return $this->nameEn;\n }\n\n /**\n * @param mixed $nameEn\n */\n public function setNameEn($nameEn)\n {\n $this->nameEn = $nameEn;\n }\n\n /**\n * @return mixed\n */\n public function getManufacture()\n {\n return $this->manufacture;\n }\n\n /**\n * @param mixed $manufacture\n */\n public function setManufacture($manufacture)\n {\n $this->manufacture = $manufacture;\n }\n\n /**\n * @return mixed\n */\n public function getOriginCountries()\n {\n return $this->base->getIterator($this->originCountries);\n }\n\n /**\n * @param mixed $originCountries\n */\n public function setOriginCountries($originCountries)\n {\n $this->originCountries = $this->base->getIterator($originCountries);\n }\n\n /**\n * @return mixed\n */\n public function getDistanceType()\n {\n return $this->distanceType;\n }\n\n /**\n * @param mixed $distanceType\n */\n public function setDistanceType($distanceType)\n {\n $this->distanceType = $distanceType;\n }\n\n /**\n * @return mixed\n */\n public function getFuselageType()\n {\n return $this->fuselageType;\n }\n\n /**\n * @param mixed $fuselageType\n */\n public function setFuselageType($fuselageType)\n {\n $this->fuselageType = $fuselageType;\n }\n\n /**\n * @return mixed\n */\n public function getCapacity()\n {\n return $this->capacity;\n }\n\n /**\n * @param mixed $capacity\n */\n public function setCapacity($capacity)\n {\n $this->capacity = $capacity;\n }\n\n /**\n * @return mixed\n */\n public function getCruiseSpeed()\n {\n return $this->cruiseSpeed;\n }\n\n /**\n * @param mixed $cruiseSpeed\n */\n public function setCruiseSpeed($cruiseSpeed)\n {\n $this->cruiseSpeed = $cruiseSpeed;\n }\n\n /**\n * @return mixed\n */\n public function getIsTurbineAirctaft()\n {\n return $this->isTurbineAirctaft;\n }\n\n /**\n * @param mixed $isTurbineAirctaft\n */\n public function setIsTurbineAirctaft($isTurbineAirctaft)\n {\n $this->isTurbineAirctaft = $isTurbineAirctaft;\n }\n\n /**\n * @return mixed\n */\n public function getIsHomeAirctaft()\n {\n return $this->isHomeAirctaft;\n }\n\n /**\n * @param mixed $isHomeAirctaft\n */\n public function setIsHomeAirctaft($isHomeAirctaft)\n {\n $this->isHomeAirctaft = $isHomeAirctaft;\n }\n\n /**\n * @return mixed\n */\n public function getImage()\n {\n return $this->image;\n }\n\n /**\n * @param mixed $image\n */\n public function setImage($image)\n {\n $this->image = $image;\n }\n\n /**\n * @return mixed\n */\n public function getMapImage()\n {\n return $this->map_image;\n }\n\n /**\n * @param mixed $map_image\n */\n public function setMapImage($map_image)\n {\n $this->map_image = $map_image;\n }\n\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914283,"cells":{"blob_id":{"kind":"string","value":"e2ea9610a70dc13d5695e34731b2727b2001f049"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"menkveld/parallel"},"path":{"kind":"string","value":"/yii/modules/person/controllers/DefaultController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2980,"string":"2,980"},"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":" array(\n\t\t\t\t\t\t'class' => 'parallel\\yii\\actions\\EntityUpdateAction',\n\t\t\t\t\t\t'model' => 'Person',\n\t\t\t\t\t\t'childModels' => array(\n\t\t\t\t\t\t\t\t'parallel\\yii\\models\\Addresses\\Address' => 'addressItems',\n\t\t\t\t\t\t\t\t'parallel\\yii\\models\\ContactDetails\\ContactDetail' => 'contactDetailItems',\t// Child Model Name => Detail Item Behavior Name (see Company)\n\t\t\t\t\t\t),\n\t\t\t\t),\n\t\n\t\t\t\t'create' => array(\n\t\t\t\t\t\t'class' => 'parallel\\yii\\actions\\EntityUpdateAction',\n\t\t\t\t\t\t'model' => 'Person',\n\t\t\t\t\t\t'childModels' => array(\n\t\t\t\t\t\t\t\t'parallel\\yii\\models\\Addresses\\Address' => 'addressItems',\n\t\t\t\t\t\t\t\t'parallel\\yii\\models\\ContactDetails\\ContactDetail' => 'contactDetailItems',\t// Child Model Name => Detail Item Behavior Name (see Company)\n\t\t\t\t\t\t),\n\t\t\t\t),\n\t\n\t\t\t\t'delete' => array(\n\t\t\t\t\t\t'class' => 'parallel\\yii\\actions\\EntityDeleteAction',\n\t\t\t\t\t\t'model' => 'Person',\n\t\t\t\t),\n\t\t\t\t\n\t\t\t\t'ajaxAddContactDetail' => array(\n\t\t\t\t\t\t'class' => 'parallel\\yii\\widgets\\ContactDetails\\AddContactDetailItemAction',\n\t\t\t\t\t\t'bridgeModel' => 'PersonContactDetail',\n\t\t\t\t),\n\n\t\t\t\t'suburbOptions' => array(\n\t\t\t\t\t\t'class' => 'parallel\\yii\\zii\\widgets\\jui\\AutoCompleteAction',\n\t\t\t\t\t\t'model' => 'parallel\\yii\\models\\Addresses\\AddressSuburb',\n\t\t\t\t\t\t'attributes' => array(\n\t\t\t\t\t\t\t\t'label' => 'label',\n\t\t\t\t\t\t\t\t'postal_code' => 'postal_code',\n\t\t\t\t\t\t\t\t'province_state' => 'province_state_label'\n\t\t\t\t\t\t),\n\t\t\t\t\t\t'order' => 'label',\n\t\t\t\t\t\t'searchType' => parallel\\yii\\zii\\widgets\\jui\\AutoCompleteAction::SEARCH_FIRST_CHARS\n\t\t\t\t),\n\t\t\t\t\n\t\t);\n\t}\n\t\n\t/**\n\t * Lists all models.\n\t */\n\tpublic function actionIndex()\n\t{\n\t\t$this->actionList();\n\t}\n\t\n\t/**\n\t * Manages all models.\n\t */\n\tpublic function actionList()\n\t{\n\t\tif(\\Yii::app()->user->checkAccess('Person.view')) {\t\t\t\n\t\t\t$model=new Person('search');\n\t\t\t$model->unsetAttributes(); // clear any default values\n\t\t\tif(isset($_GET['Person']))\n\t\t\t\t$model->attributes=$_GET['Person'];\n\t\t\n\t\t\t$this->render('list',array(\n\t\t\t\t\t'model'=>$model,\n\t\t\t));\n\t\t} else {\n\t\t\tthrow new \\CHttpException(403, \"User does not have sufficient permission for this action.\");\n\t\t}\t\t\n\t}\n\t\n\t/**\n\t * Displays a particular model.\n\t * @param integer $id the ID of the model to be displayed\n\t */\n\tpublic function actionView($id)\n\t{\n\t\t$this->render('view',array(\n\t\t\t\t'model'=>$this->loadModel($id),\n\t\t));\n\t}\n\t\n\t/**\n\t * Performs the AJAX validation.\n\t * @param CModel the model to be validated\n\t */\n\tprotected function performAjaxValidation($model)\n\t{\n\t\tif(isset($_POST['ajax']) && $_POST['ajax']==='person-form')\n\t\t{\n\t\t\techo CActiveForm::validate($model);\n\t\t\tYii::app()->end();\n\t\t}\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914284,"cells":{"blob_id":{"kind":"string","value":"7d72d06c1497857733923e7e92189b5c5f8eff28"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"c9s/CLIFramework"},"path":{"kind":"string","value":"/tests/CLIFramework/TestAppCommandTest.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":870,"string":"870"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-4-Clause-UC"],"string":"[\n \"BSD-4-Clause-UC\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"init();\n\n $argInfos = $command->getArgInfoList();\n $this->assertNotEmpty($argInfos);\n $this->assertCount(1, $argInfos);\n $this->assertEquals('var', $argInfos[0]->name);\n }\n\n public function testArginfoCommand() {\n $cmd = new TestApp\\Command\\ArginfoCommand(new Application);\n $cmd->init();\n\n $argInfos = $cmd->getArgInfoList();\n $this->assertNotEmpty($argInfos);\n $this->assertCount(3, $argInfos);\n\n foreach( $argInfos as $arginfo ) {\n $this->assertInstanceOf('CLIFramework\\ArgInfo', $arginfo);\n }\n }\n}\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914285,"cells":{"blob_id":{"kind":"string","value":"e2ebfb543062b95787007821aa2ef574499ca0e8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"passerellesnumeriques/SDB-0.1-prototype"},"path":{"kind":"string","value":"/www/component/authentication/FakeAuthenticationSystem.inc"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":199,"string":"199"},"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":""},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914286,"cells":{"blob_id":{"kind":"string","value":"b68aa920a096082c4df1592056f2a47f695ad93f"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"gotohr/simple-php-code-gen"},"path":{"kind":"string","value":"/src/GoToHr/SimpleCodeGen/InterfaceMethodTemplate.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":167,"string":"167"},"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":"load($html);\n\nforeach ($dom->find('table tr') as $row) {\n \n \n echo $row . \"\\n\";\n // echo $row->find('a',3)->href . $row->find('a',4)->href . $row->find('a',5)->href . $row->find('a',6)->href;\n\n \n\n $vals = $row->find('td');\n//print_r($vals) ;\n\n//echo test.$vals[4].test;\n\n// if (!empty($vals)) {\n\n // if (preg_match('/[0-9a-fA-F]{64}/', $vals[1]->innertext, $matches )) {\n\n\n\n\n$string = $vals[4]->plaintext; \n\npreg_match_all('/\\d+/', $string, $ing); \n\n\n\n $data[] = array(\n 'col1' => $vals[0]->plaintext,\n // '#2' => $matches[0],\n 'col2' => $vals[1]->plaintext,\n 'col3' => $vals[2]->plaintext,\n 'col4' => $vals[3]->plaintext,\n 'col6' => $ing[0][0],\n 'col7' => str_replace('-',' ',strstr($row->find('a',3)->href, '-')),\n 'col8' => $ing[0][1],\n 'col9' => str_replace('-',' ',strstr($row->find('a',4)->href, '-')),\n 'col10' => $ing[0][2],\n 'col11' => str_replace('-',' ',strstr($row->find('a',5)->href, '-')),\n 'col12' => $ing[0][3],\n 'col13' => str_replace('-',' ',strstr($row->find('a',6)->href, '-')),\n // 'col5' => $vals[4]->plaintext\n // \n );\n // };\n// }\n};\n\nscraperwiki::save_sqlite(array('col1'),$data, \"data\"); \n\n/* Extract block data */\n\n/* Extract transactions */\n}\n\n?>\n\n\nload($html);\n\nforeach ($dom->find('table tr') as $row) {\n \n \n echo $row . \"\\n\";\n // echo $row->find('a',3)->href . $row->find('a',4)->href . $row->find('a',5)->href . $row->find('a',6)->href;\n\n \n\n $vals = $row->find('td');\n//print_r($vals) ;\n\n//echo test.$vals[4].test;\n\n// if (!empty($vals)) {\n\n // if (preg_match('/[0-9a-fA-F]{64}/', $vals[1]->innertext, $matches )) {\n\n\n\n\n$string = $vals[4]->plaintext; \n\npreg_match_all('/\\d+/', $string, $ing); \n\n\n\n $data[] = array(\n 'col1' => $vals[0]->plaintext,\n // '#2' => $matches[0],\n 'col2' => $vals[1]->plaintext,\n 'col3' => $vals[2]->plaintext,\n 'col4' => $vals[3]->plaintext,\n 'col6' => $ing[0][0],\n 'col7' => str_replace('-',' ',strstr($row->find('a',3)->href, '-')),\n 'col8' => $ing[0][1],\n 'col9' => str_replace('-',' ',strstr($row->find('a',4)->href, '-')),\n 'col10' => $ing[0][2],\n 'col11' => str_replace('-',' ',strstr($row->find('a',5)->href, '-')),\n 'col12' => $ing[0][3],\n 'col13' => str_replace('-',' ',strstr($row->find('a',6)->href, '-')),\n // 'col5' => $vals[4]->plaintext\n // \n );\n // };\n// }\n};\n\nscraperwiki::save_sqlite(array('col1'),$data, \"data\"); \n\n/* Extract block data */\n\n/* Extract transactions */\n}\n\n?>\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914288,"cells":{"blob_id":{"kind":"string","value":"35524e6fd7669c7059c9d428aeb9ae9ad3113329"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"zgolus/kw"},"path":{"kind":"string","value":"/src/Command/Write.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1719,"string":"1,719"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"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":"reasonRepair = $reasonRepair;\n $this->reasonValidator = $reasonValidator;\n }\n\n protected function configure()\n {\n $this->setName('kw:retoure:write')\n ->addArgument('input', InputArgument::REQUIRED, 'Input file')\n ->addArgument('output', InputArgument::REQUIRED, 'Output file');\n }\n\n protected function execute(InputInterface $input, OutputInterface $output)\n {\n $inputHandle = fopen($input->getArgument('input'), \"r\");\n $outputHandle = fopen($input->getArgument('output'), 'w');\n if ($inputHandle) {\n while (($line = fgets($inputHandle)) !== false) {\n $line = trim($line);\n list($retourId, $retoureReason) = explode(',', $line, 2);\n $originalReason = trim($retoureReason);\n\n $repairedReason = $this->reasonRepair->repair($originalReason);\n fwrite($outputHandle, sprintf(\"%s,%s\\n\", $retourId, $repairedReason));\n\n }\n fclose($inputHandle);\n }\n fclose($outputHandle);\n $output->writeln('Done.');\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914289,"cells":{"blob_id":{"kind":"string","value":"3f5016657542e4f7cc68a60582c1e708870656b1"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"andres2r/prueba-tecnica"},"path":{"kind":"string","value":"/app/Http/Controllers/UsersController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":925,"string":"925"},"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":"json();\n $collection = collect($users);\n $uniqueUserId = $collection->unique('userId');\n\n //Crando un array para contenter la cantidad de ToDo´s compledatos por cada usuario\n $completedArray = [];\n for($i = 1; $i <= count($uniqueUserId); $i++){\n $completedArray[$i] = 0;\n }\n\n //Llenando array\n foreach($collection as $item){\n if ($item['completed'] == true) {\n $completedArray[$item['userId']] += 1;\n }\n }\n \n return view('users.index', compact('uniqueUserId', 'completedArray'));\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914290,"cells":{"blob_id":{"kind":"string","value":"285b85d8c6740e19498f95955bec7ad617d16549"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"hbour/Bibliotheque"},"path":{"kind":"string","value":"/indexArticle.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2285,"string":"2,285"},"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":"\n \n\n\n\n\t\n\t\t\n\t\t\n\t\t\n\t\tExam Library\n\t\n\t\n\t\n\t\t
\n\t\t\t\n\t\t\t
\n\t\t\t\t\n\t\t\t
\n\t\t\t\n\t\t\t

Fiche article

\n\t\t\t\n\t\t\tquery($requete);\n\t\t\t\tif(!$result) {\n\t\t\t\t\techo \"

Erreur requête

\";\n\t\t\t\t} else {\n\t\t\t\t\twhile($res = $result->fetch_assoc()) {\n\t\t\t\t\t\techo \"

Titre : \".utf8_encode($res['OUV_Titre']).\"

\";\n\t\t\t\t\t\techo \"

Auteur : \".utf8_encode($res['OUV_Auteur']).\"

\";\n\t\t\t\t\t\techo \"

Code : \".utf8_encode($id).\"

\";\n\t\t\t\t\t\techo \"

Support : \".utf8_encode($res['TYP_Support']).\"

\";\n\t\t\t\t\t\techo \"

Editeur : \".utf8_encode($res['OUV_Editeur']).\"

\";\n\t\t\t\t\t\techo \"

Collection : \".utf8_encode($res['OUV_Collection']).\"

\";\n\t\t\t\t\t\techo \"

Date de parution : \".utf8_encode($res['OUV_Date_parution']).\"

\";\n\t\t\t\t\t\techo \"

Thème : \".utf8_encode($res['OUV_Theme']).\"

\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$result->close();\n\t\t\t}\n\t\t\t?>\n\t\t\t\n\t\t\t

Statut des exemplaires

\n\t\t\t\n\t\t\tquery($requete2);\n\t\t\techo \"

\".$result2->num_rows.\" exemplaire(s) :

\";\n\t\t\t$present = 0;\n\t\t\twhile($row = $result2->fetch_array(MYSQLI_NUM)) {\n\t\t\t\tforeach($row as $item) {\n\t\t\t\t\techo \"

- \".utf8_encode($item).\" : \";\n\t\t\t\t\tif($item == 'Present') {\n\t\t\t\t\t\t$present = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($present == 1) {\n\t\t\t\techo \"

\".\n\t\t\t\t\"\".\n\t\t\t\t\"\";\n\t\t\t}\n\t\t\t$result2->close();\n\t\t\t?>\n\t\t
\n\t\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914291,"cells":{"blob_id":{"kind":"string","value":"54cdff040d08bbe0ac4c56801d331fcd81a9f464"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"Idimma/piller-api"},"path":{"kind":"string","value":"/app/Services/ExpoNotification.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1108,"string":"1,108"},"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":" [\n 'Host' => 'exp.host',\n 'Accept' => 'application/json',\n 'Accept-Encoding' => 'gzip, deflate',\n 'Content-Type' => 'application/json'\n ]\n ]);\n\n try {\n $response = $client->post('https://exp.host/--/api/v2/push/send', [\n 'form_params' => [\n 'to' => $notification_token,\n 'sound' => 'default',\n 'title' => $title,\n 'body' => $message,\n 'data' => $data\n ]\n ]);\n } catch (ClientException $e) {\n //throw $th;\n $response = $e->getResponse();\n } \n return json_decode($response->getBody(), true);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914292,"cells":{"blob_id":{"kind":"string","value":"73720d0978872ec11e8109d3890e277514f3ba54"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"lukisanjaya/LumenElasticSearch"},"path":{"kind":"string","value":"/app/Http/Controllers/Controller.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":925,"string":"925"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"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":"getValidationFactory()\n ->make(\n $request->all(), \n $rules, $messages, \n $customAttributes\n );\n if ($validator->fails()) {\n throw new ValidationHttpException(\n $validator->errors()\n );\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914293,"cells":{"blob_id":{"kind":"string","value":"6edfc46c8ced8c5187abc1614d7280926bbc45ef"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"bigshoesdev/KindWorker"},"path":{"kind":"string","value":"/protected/components/TToolButtons.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3392,"string":"3,392"},"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\t\t\t'update' => '',\n\t\t\t'view' => '',\n\t\t\t'delete' => '' \n\t];\n\t\n\t/**\n\t *\n\t * @var string|Closure Translated model name depends on actions.\n\t */\n\tpublic $modelName;\n\t\n\t/**\n\t *\n\t * @var Closure Function can check whether action exist or not.\n\t */\n\tpublic $hasAction;\n\t\n\t/**\n\t * @inheritdoc\n\t */\n\tpublic function init() {\n\t\tparent::init ();\n\t\tif (! $this->actionId) {\n\t\t\t$this->actionId = Yii::$app->controller->action->id;\n\t\t}\n\t\t\n\t\t$this->modelName = get_class ( $this->model );\n\t\t$this->modelName = StringHelper::basename ( $this->modelName );\n\t}\n\t\n\t/**\n\t * @inheritdoc\n\t */\n\tpublic function run() {\n\t\techo '
';\n\n\t\tif (is_array ( \\Yii::$app->controller->menu ))\n\t\t\tforeach ( \\Yii::$app->controller->menu as $key => $menu ) {\n\t\t\t\t\n\t\t\t\tif (! $this->hasAction ( $menu ['url'] ))\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tif (isset ( $this->actions [$key] )) {\n\t\t\t\t\tif ($key == 'delete') {\n\t\t\t\t\t\t\n\t\t\t\t\t\t$menu ['class'] = 'btn btn-danger';\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * $menu ['label'] = $this->actions [$key];\n\t\t\t\t\t\t * $menu ['data'] = [\n\t\t\t\t\t\t * 'method' => 'POST',\n\t\t\t\t\t\t * 'confirm' => Yii::t ( 'app', 'Are you sure you want to delete this {modelName} #{id}', [\n\t\t\t\t\t\t * 'modelName' => $this->modelName,\n\t\t\t\t\t\t * 'id' => ( isset( $this->model->id) )? $this->model->id :null\n\t\t\t\t\t\t * ] )\n\t\t\t\t\t\t * ];\n\t\t\t\t\t\t */\n\t\t\t\t\t}\n\t\t\t\t\tif (! isset ( $menu ['label'] )) {\n\t\t\t\t\t\t$menu ['label'] = $this->actions [$key];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$visible = true;\n\t\t\t\tif (isset ( $menu ['visible'] ))\n\t\t\t\t\tif ($menu ['visible'] == true)\n\t\t\t\t\t\t$visible = true;\n\t\t\t\t\telse\n\t\t\t\t\t\t$visible = false;\n\t\t\t\t$this->htmlOptions = [ \n\t\t\t\t\t\t'class' => isset ( $menu ['class'] ) ? $menu ['class'] : 'btn btn-success ',\n\t\t\t\t\t\t'title' => isset ( $menu ['title'] ) ? $menu ['title'] : $menu ['label'],\n\t\t\t\t\t\t'id' => isset ( $menu ['id'] ) ? $menu ['id'] : \"tool-btn-\" . $key \n\t\t\t\t];\n\t\t\t\tif (isset ( $menu ['htmlOptions'] ))\n\t\t\t\t\t$this->htmlOptions = array_merge ( $menu ['htmlOptions'], $this->htmlOptions );\n\t\t\t\tif ($visible)\n\t\t\t\t\techo ' ' . Html::a ( $menu ['label'], $menu ['url'], $this->htmlOptions );\n\t\t\t}\n\t\techo '
';\n\t}\n\t\n\t/**\n\t * Returns a value indicating whether a controller action is defined.\n\t *\n\t * @param string $id\n\t * \tAction id\n\t * @return bool\n\t */\n\tprotected function hasAction($url) {\n\t\t//$enableEmails = yii::$app->setting->get ( 'Enable Emails' );\n\t\t\n\t\t/*\n\t\t * if ( is_array($url))\n\t\t * if ( $id == 'manage') $id = 'index';\n\t\t *\n\t\t * $actionMap = ->actions ();\n\t\t *\n\t\t * if (isset ( $actionMap [$id] )) {\n\t\t * return true;\n\t\t * } else {\n\t\t * $action = Inflector::id2camel($id);\n\t\t * $methodName = 'action' . ucfirst($action);\n\t\t * if (method_exists ( Yii::$app->controller, $methodName )) {\n\t\t * return true;\n\t\t * }\n\t\t * }\n\t\t *\n\t\t * return false;\n\t\t */\n\t\treturn true;\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914294,"cells":{"blob_id":{"kind":"string","value":"a8059985a3803e33f7be75b2a9d303c5ae14a8e9"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"MFDonadeli/trigorh"},"path":{"kind":"string","value":"/website/models/vaga_model.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":15666,"string":"15,666"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"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":"load->helper('password_helper');\n }\n\n \n /**\n * registra_acao\n *\n * Grava ação do profissional no site\n *\n * @param\tint\n * @param\tint (constante da classe Acao)\n * @return\tstring O hash da acao gravada no banco\n */\n public function registra_acao($id, $acao)\n {\n log_message('debug', 'registra_acao. Param1: {' . $id . '} Param2: {' . $acao . '}');\n\n $hash = sha1(date('Y-m-d H:i:s') . $id . $acao);\n\n $nova_acao = array(\n 'idprofissional' => $id,\n 'idacao' => $acao,\n 'hash' => $hash\n );\n\n $this->db->insert('profissional_historico', $nova_acao);\n \n return $hash;\n }\n\n /**\n * insere_vaga\n *\n * Insere vaga\n *\n * @param\tstring\n * @param\tstring\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function insere_vaga($vaga, $id)\n {\n log_message('debug', 'insere_vaga. Param1: ' . $vaga . \" Param2: \" . $id);\n\n $arr = array(\n 'codvaga' => $vaga,\n 'idempresa' => $id\n );\n\n $this->db->insert('vaga', $arr); \n\n log_message('debug', 'Last Query: ' . $this->db->last_query()); \n\n return $this->db->insert_id(); \n }\n\n /**\n * apaga_vaga\n *\n * Apaga vaga\n *\n * @param\tstring\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function apaga_vaga($vaga)\n {\n log_message('debug', 'apaga_vaga. Param1: ' . $vaga);\n\n $this->db->where('idvaga', $vaga);\n $result = $this->db->get('profissional_vaga');\n\n if($result->num_rows() > 0)\n {\n return false;\n }\n\n $this->db->where('idvaga', $vaga);\n\n $this->db->delete('vaga'); \n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n }\n\n /**\n * update_dados_vaga\n *\n * Atualiza dados pessoais de profissional\n *\n * @param\tarray\n * @param\tarray\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function update_dados_vaga($arr, $beneficio)\n {\n log_message('debug', 'update_dados_vaga');\n\n $this->db->where('idvaga', $arr['idvaga']);\n $this->db->update('vaga', $arr);\n\n if(is_array($beneficio))\n {\n $this->db->where('idvaga', $arr['idvaga']);\n $this->db->delete('beneficio_vaga');\n\n foreach($beneficio as $benef)\n {\n $arrbenef = array(\n 'idvaga' => $arr['idvaga'],\n 'idbeneficio' => $benef\n );\n $this->db->insert('beneficio_vaga', $arrbenef);\n }\n } \n else\n log_message('debug', 'Benefício não é array'); \n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n }\n\n /**\n * get_dados_vaga\n *\n * Busca dados pessoais de vaga\n *\n * @param\tint\n * @return\tarray\n */\n public function get_dados_vaga($id)\n {\n log_message('debug', 'get_dados_vaga. Param1: ' . $id);\n\n $this->db->where('idvaga', $id);\n $result = $this->db->get('vaga');\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->row();\n }\n\n /**\n * get_beneficios_vaga\n *\n * Busca dados pessoais de vaga\n *\n * @param\tint\n * @return\tarray\n */\n public function get_beneficios_vaga($id)\n {\n log_message('debug', 'get_beneficios_vaga. Param1: ' . $id);\n\n $this->db->where('idvaga', $id);\n $result = $this->db->get('beneficio_vaga');\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->result();\n }\n\n /**\n * update_idioma\n *\n * Insere/Atualiza dados de formação acadêmica da vaga\n *\n * @param\tarray\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function update_idioma($arr, $ididioma)\n {\n log_message('debug', 'update_idioma. Idioma: ' . $ididioma);\n\n if(empty($ididioma))\n {\n $this->db->insert('conhecimento_vaga', $arr);\n }\n else\n {\n $this->db->where('idconhecimento_vaga', $ididioma);\n $this->db->update('conhecimento_vaga', $arr); \n }\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n }\n\n /**\n * update_idioma\n *\n * Insere/Atualiza dados de formação acadêmica do profissional\n *\n * @param\tarray\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function update_informatica($arr, $idinformatica)\n {\n log_message('debug', 'update_idioma');\n\n if(empty($idinformatica))\n {\n $this->db->insert('conhecimento_vaga', $arr);\n }\n else\n {\n $this->db->where('idconhecimento_vaga', $idinformatica);\n $this->db->update('conhecimento_vaga', $arr); \n }\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n }\n\n /**\n * update_curso\n *\n * Insere/Atualiza dados de cursos da vaga\n *\n * @param\tarray\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function update_curso($arr, $idcurso)\n {\n log_message('debug', 'update_curso. Param1: ' . $idcurso);\n\n if(empty($idcurso))\n {\n $this->db->insert('formacao_vaga', $arr);\n }\n else\n {\n $this->db->where('idformacao_vaga', $idcurso);\n $this->db->update('formacao_vaga', $arr); \n }\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n }\n\n \n /**\n * get_idioma\n *\n * Seleciona um idioma da vaga\n *\n * @param\tint\n * @param\tint\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function get_idioma($id, $id_idioma)\n {\n log_message('debug', 'get_idioma. Param1: ' . $id . ' Param2: ' . $id_idioma);\n\n $this->db->select('conhecimento_vaga.idconhecimento_vaga, conhecimento_vaga.idconhecimento,\n conhecimento_vaga.id_vaga, conhecimento_vaga.conhecimento, conhecimento_vaga.obrigatorio, \n conhecimento_vaga.nivel, nivel_idioma.nivel_idioma');\n $this->db->from('conhecimento_vaga');\n $this->db->join('nivel_idioma', \n 'conhecimento_vaga.nivel = nivel_idioma.idnivel_idioma');\n $this->db->where('conhecimento_vaga.id_vaga', $id);\n $this->db->where('conhecimento_vaga.idconhecimento_vaga', $id_idioma);\n $result = $this->db->get();\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->row();\n }\n\n /**\n * get_idiomas\n *\n * Busca os idiomas do profissional\n *\n * @param\tint\n * @return\tarray\n */\n public function get_idiomas($id)\n {\n log_message('debug', 'get_idiomas. Param1: ' . $id);\n\n $this->db->select('conhecimento_vaga.*, nivel_idioma.nivel_idioma');\n $this->db->from('conhecimento_vaga');\n $this->db->join('conhecimento', \n 'conhecimento_vaga.idconhecimento = conhecimento.idconhecimento');\n $this->db->join('nivel_idioma', \n 'conhecimento_vaga.nivel = nivel_idioma.idnivel_idioma');\n $this->db->where('conhecimento.idtipo_conhecimento = 2');\n $this->db->where('conhecimento_vaga.id_vaga', $id);\n $result = $this->db->get();\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->result(); \n }\n\n /**\n * apaga_idioma\n *\n * Apaga dados de idioma do profissional\n *\n * @param\tint\n * @param\tint\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function apaga_idioma($id, $id_idioma)\n {\n log_message('debug', 'apaga_idioma');\n\n $this->db->where('idconhecimento_vaga', $id_idioma);\n $this->db->where('id_vaga', $id);\n $this->db->delete('conhecimento_vaga');\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n }\n\n//****** INFORMATICA\n\n /**\n * get_informatica\n *\n * Seleciona um conhecimento de informática da vaga\n *\n * @param\tint\n * @param\tint\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function get_informatica($id, $id_informatica)\n {\n log_message('debug', 'get_informatica. Param1: ' . $id . ' Param2: ' . $id_informatica);\n\n $this->db->where('conhecimento_vaga.id_vaga', $id);\n $this->db->where('conhecimento_vaga.idconhecimento_vaga', $id_informatica);\n $result = $this->db->get('conhecimento_vaga');\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->row();\n }\n\n /**\n * get_idiomas\n *\n * Busca os conhecimento de informática da vaga\n *\n * @param\tint\n * @return\tarray\n */\n public function get_informaticas($id)\n {\n log_message('debug', 'get_idiomas. Param1: ' . $id);\n\n $this->db->select('conhecimento_vaga.*, subtipo_conhecimento.subtipo_conhecimento');\n $this->db->from('conhecimento_vaga');\n $this->db->join('conhecimento', \n 'conhecimento_vaga.idconhecimento = conhecimento.idconhecimento');\n $this->db->join('subtipo_conhecimento', \n 'conhecimento.idsubtipo_conhecimento = subtipo_conhecimento.idsubtipo_conhecimento');\n $this->db->where('conhecimento.idtipo_conhecimento = 1');\n $this->db->where('conhecimento_vaga.id_vaga', $id);\n $this->db->order_by('subtipo_conhecimento.subtipo_conhecimento');\n $result = $this->db->get();\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->result(); \n }\n\n /**\n * apaga_informática\n *\n * Apaga dados de informática do profissional\n *\n * @param\tint\n * @param\tint\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function apaga_informatica($id, $id_informatica)\n {\n log_message('debug', 'apaga_informática');\n\n $this->db->where('idconhecimento_vaga', $id_informatica);\n $this->db->where('id_vaga', $id);\n $this->db->delete('conhecimento_vaga');\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n }\n\n/*** CURSOS\n /**\n * get_curso\n *\n * Seleciona um curso requerido da vaga\n *\n * @param\tint\n * @param\tint\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function get_curso($id, $idcurso)\n {\n log_message('debug', 'get_curso. Param1: ' . $id . ' Param2: ' . $idcurso);\n\n $this->db->where('idvaga', $id);\n $this->db->where('idformacao_vaga', $idcurso);\n $result = $this->db->get('formacao_vaga');\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->row();\n }\n\n /**\n * get_cursos\n *\n * Busca as formações necessárias para a vaga\n *\n * @param\tint\n * @return\tarray\n */\n public function get_cursos($id)\n {\n log_message('debug', 'get_cursos. Param1: ' . $id);\n\n $this->db->where('idvaga', $id);\n $result = $this->db->get('formacao_vaga');\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->result(); \n }\n\n /**\n * apaga_cursos\n *\n * Apaga curso requerido para a vaga\n *\n * @param\tint\n * @param\tint\n * @return\tboolean\ttrue ou false se existir o pedido\n */\n public function apaga_cursos($id, $idcurso)\n {\n log_message('debug', 'apaga_idioma');\n\n $this->db->where('idvaga', $id);\n $this->db->where('idformacao_vaga', $idcurso);\n $this->db->delete('formacao_vaga');\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n }\n\n /**\n * informacao_basica\n *\n * Traz nome, porcentagem do currículo preenchido e data da última atualização do currículo\n *\n * @param\tint\n * @return\tarray\n */\n public function informacao_basica($id)\n {\n log_message('debug', 'informacao_basica. Param1: ' . $id);\n\n $this->db->select('p.nome, p.porcentagem_cadastro, ph.data');\n $this->db->from('profissional p');\n $this->db->join('profissional_historico ph', 'p.idprofissional = ph.idprofissional');\n $this->db->where('p.idprofissional', $id);\n $this->db->where('ph.idacao = 2');\n $this->db->order_by('ph.idprofissional_historico', 'DESC');\n $this->db->limit(1);\n $result = $this->db->get();\n\n return $result->row();\n }\n\n public function busca_informatica($conhecimento)\n {\n log_message('debug', 'busca_idioma. Param1: ' . $conhecimento);\n\n $this->db->select('conhecimento.idconhecimento, conhecimento.conhecimento');\n $this->db->from('conhecimento');\n $this->db->like('conhecimento.conhecimento', $conhecimento, 'both');\n $this->db->where('idtipo_conhecimento', '1');\n $this->db->order_by('conhecimento.conhecimento');\n \n $result = $this->db->get();\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->result();\n }\n\n public function busca_idioma($conhecimento)\n {\n log_message('debug', 'busca_idioma. Param1: ' . $conhecimento);\n\n $this->db->select('conhecimento.idconhecimento, conhecimento.conhecimento');\n $this->db->from('conhecimento');\n $this->db->like('conhecimento.conhecimento', $conhecimento, 'both');\n $this->db->where('idtipo_conhecimento', '2');\n $this->db->order_by('conhecimento.conhecimento');\n \n $result = $this->db->get();\n\n log_message('debug', 'Last Query: ' . $this->db->last_query());\n\n return $result->result();\n }\n\n }\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914295,"cells":{"blob_id":{"kind":"string","value":"0dd0b1602c8ac8f97073613307c94a30711e6b23"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"LoicFeuga/ShareEverything"},"path":{"kind":"string","value":"/php/classes/Room.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1523,"string":"1,523"},"score":{"kind":"number","value":3.078125,"string":"3.078125"},"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\t\t$this->description = $description;\n\t\t$this->pdo = $pdo;\n\t}\n\n\n\n\tpublic function insertRoom(){\n\t\t$this->pdo->execute(\"INSERT INTO se_room (name, description) VALUES ('\".$this->name.\"', '\".$this->description.\"') \");\n\t}\n\n\tpublic function createTchat(){\n\t\t$req = $this->pdo->queryOne(\"SELECT MAX(id_tchat) AS id_tchat FROM se_room \");\n\t\t$this->id_tchat = $req->id_tchat;\n\t\t$this->id_tchat++;\n\t\t$this->pdo->execute(\"UPDATE se_room SET id_tchat = '\".$this->id_tchat.\"' WHERE name= '\".$this->name.\"' \");\n\t}\n\n\tpublic function getId(){\n\t\treturn $this->id;\n\t}\n\n\tpublic function getIdTchat(){\n\t\treturn $this->id_tchat;\n\t}\n\n\tpublic function setId($id){\n\t\t$this->id=$id;\n\t}\n\n\tpublic function exist(){\n\t\t$req = $this->pdo->queryOne(\"SELECT * FROM se_room WHERE name = '\".$this->name.\"' \");\n\t\tif($req->id != 0 && $req !=NULL){\n\t\t\treturn 1;\n\t\t}else{\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tpublic function getRoom(){\n\t\t$req = $this->pdo->queryOne(\"SELECT * FROM se_room WHERE name = '\".$this->name.\"' \");\n\t\t$this->id = $req->id;\n\t\t$this->description = $req->description;\n\t}\n\n\tpublic function setRoomFromBDD(){\n\t\t$req = $this->pdo->queryOne(\"SELECT * FROM se_room WHERE name = '\".$this->name.\"' \");\n\n\t\t$this->id = $req->id;\n\t\t$this->description = $req->description;\n\t\t$this->id_tchat = $req->id_tchat;\n\t\t$this->name = $req->name;\n\n\t}\n\n}\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914296,"cells":{"blob_id":{"kind":"string","value":"f833529a38a8a0ffc17a4977d4c9c86d784a813e"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"newsukarun/nts_hackathon"},"path":{"kind":"string","value":"/inc/rest-api/sms/sms-no-food.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1521,"string":"1,521"},"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":"ntsfood_namespacce . $this->ntsfood_version;\n\t\t$base = 'nofood';\n\t\tregister_rest_route(\n\t\t\t$namespace,\n\t\t\t'/' . $base,\n\t\t\tarray(\n\t\t\t\tarray(\n\t\t\t\t\t'methods' => WP_REST_Server::CREATABLE,\n\t\t\t\t\t'callback' => array( $this, 'food_opt_out' ),\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\t}\n\n\t// Register our REST Server\n\tpublic function hook_rest_server() {\n\t\tadd_action( 'rest_api_init', array( $this, 'register_routes' ) );\n\t}\n\n\tpublic function food_opt_out( WP_REST_Request $request ) {\n\t\t$keyword = filter_input( INPUT_POST, 'keyword', FILTER_SANITIZE_STRING );\n\t\t$message = filter_input( INPUT_POST, 'message', FILTER_SANITIZE_STRING );\n\t\t$msg_fragments = explode( ' ', $message );\n\t\t$msg_fragments = array_map( 'trim', $msg_fragments );\n\n\t\tif( 2 < count( $msg_fragments ) ) {\n\t\t\treturn new WP_REST_Response( [ 'message' => __( 'Invalid SMS!' ) ], 403 );\n\t\t}\n\n\t\t$sms_handler = new NTSFOOD\\SMS_Sender( [ 'employee' => $message ] );\n\t\t$send_sms = $sms_handler->send_sms();\n\n\t\tif( is_wp_error( $send_sms ) ) {\n\n\t\t\treturn new WP_REST_Response( [ 'message' => $send_sms->get_error_message() ], 403 );\n\t\t}\n\n\t\treturn new WP_REST_Response( [ 'message' => __( 'Coupon sent successfully' ) ], 200 );\n\t}\n}\n\n$my_rest_server = new NTS_FOOD_Coupon();\n$my_rest_server->hook_rest_server();\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914297,"cells":{"blob_id":{"kind":"string","value":"5fa47589bab66673a63eb8ddc7100155121c9894"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"MarijaJankovic623/PSI_Implementacija"},"path":{"kind":"string","value":"/application/models/UserValidationModel.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":33112,"string":"33,112"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"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":"load->library(\"my_database\");\r\n }\r\n\r\n /**\r\n * Provera sesije za sve vrste korisnika.\r\n * \r\n * Poziva se unutar ostalih funkcija za proveru sesija\r\n * ona proverava samo da li je korisnik koji pokusava da prostupi\r\n * ulogovan i ako nije vraca ga na pocetnu stranu sistema.\r\n * \r\n * \r\n */\r\n public function checkSession() {\r\n $is_logged_in = $this->session->userdata('loggedIn');\r\n\r\n\r\n if (!isset($is_logged_in) || $is_logged_in != true) {\r\n redirect(\"ErrorCtrl\");\r\n }\r\n }\r\n\r\n public function checkSessionKorisnik() {\r\n $this->checkSession();\r\n $korisnik = $this->session->userdata('korisnik');\r\n\r\n if (!$korisnik) {\r\n redirect(\"ErrorCtrl\");\r\n }\r\n }\r\n\r\n public function checkSessionRestoran() {\r\n $this->checkSession();\r\n $restoran = $this->session->userdata('restoran');\r\n\r\n if (!$restoran) {\r\n redirect(\"ErrorCtrl\");\r\n }\r\n }\r\n\r\n public function checkSessionKonobar() {\r\n $this->checkSession();\r\n $konobar = $this->session->userdata('konobar');\r\n\r\n if (!$konobar) {\r\n redirect(\"ErrorCtrl\");\r\n }\r\n }\r\n\r\n public function checkSessionAdmin() {\r\n $this->checkSession();\r\n $admin = $this->session->userdata('admin');\r\n\r\n if (!$admin) {\r\n redirect(\"ErrorCtrl\");\r\n }\r\n }\r\n\r\n /**\r\n * Logovanje korisnika.\r\n * \r\n * Proverava da li korisnik sa datim imenom i sifrom\r\n * postoji, i ako postoji puni podatke o sesiji i vraca\r\n * poruku o uspehu, u suprotnom o neuspehu.\r\n * \r\n * @param string $kime Korisnicko ime\r\n * @param string $lozinka Korisnicka lozinka\r\n * @return boolean Informacija o uspehu logovanja\r\n */\r\n public function loginKorisnik($kime, $lozinka) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init(); //dohvatanje iskaza\r\n $stmt->prepare(\"SELECT * FROM korisnik WHERE KIme = ? AND Lozinka = ?\"); //pravljenje istog\r\n $stmt->bind_param(\"ss\", $kime, $lozinka); //vezivanej parametara \r\n $stmt->execute();\r\n\r\n $kor = $stmt->get_result()->fetch_assoc();\r\n if (isset($kor['IDKorisnik'])) {\r\n $data = array(\r\n 'userid' => $kor['IDKorisnik'],\r\n 'username' => $kime,\r\n 'loggedIn' => true,\r\n 'korisnik' => true,\r\n 'restoran' => false,\r\n 'konobar' => false,\r\n 'admin' => false\r\n );\r\n\r\n $this->session->set_userdata($data);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Logovanje restorana.\r\n * \r\n * Proverava da li restoran sa datim imenom i sifrom\r\n * postoji, i ako postoji puni podatke o sesiji i vraca\r\n * poruku o uspehu, u suprotnom o neuspehu.\r\n * \r\n * @param string $kime Korisnicko ime\r\n * @param string $lozinka Korisnicka lozinka\r\n * @return boolean Informacija o uspehu logovanja\r\n */\r\n public function loginRestoran($kime, $lozinka) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init(); //dohvatanje iskaza\r\n $stmt->prepare(\"SELECT * FROM restoran WHERE KIme = ? AND Lozinka = ?\"); //pravljenje istog\r\n $stmt->bind_param(\"ss\", $kime, $lozinka); //vezivanej parametara \r\n $stmt->execute();\r\n\r\n $res = $stmt->get_result()->fetch_assoc();\r\n if (isset($res['IDRestoran'])) {\r\n $data = array(\r\n 'userid' => $res['IDRestoran'],\r\n 'username' => $kime,\r\n 'loggedIn' => true,\r\n 'restoran' => true,\r\n 'konobar' => false,\r\n 'korisnik' => false,\r\n 'admin' => false\r\n );\r\n\r\n $this->session->set_userdata($data);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Logovanje konobara.\r\n * \r\n * Proverava da li konobar sa datim imenom i sifrom\r\n * postoji, i ako postoji puni podatke o sesiji i vraca\r\n * poruku o uspehu, u suprotnom o neuspehu.\r\n * \r\n * @param string $kime Korisnicko ime\r\n * @param string $lozinka Korisnicka lozinka\r\n * @return boolean Informacija o uspehu logovanja\r\n */\r\n public function loginKonobar($kime, $lozinka) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init(); //dohvatanje iskaza\r\n $stmt->prepare(\"SELECT * FROM konobar WHERE KIme = ? AND Lozinka = ?\"); //pravljenje istog\r\n $stmt->bind_param(\"ss\", $kime, $lozinka); //vezivanej parametara \r\n $stmt->execute();\r\n\r\n $res = $stmt->get_result()->fetch_assoc();\r\n if (isset($res['IDKonobar'])) {\r\n $data = array(\r\n 'userid' => $res['IDKonobar'],\r\n 'username' => $kime,\r\n 'loggedIn' => true,\r\n 'konobar' => true,\r\n 'korisnik' => false,\r\n 'restoran' => false,\r\n 'admin' => false\r\n );\r\n\r\n $this->session->set_userdata($data);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Logovanje administratora.\r\n * \r\n * Proverava da li administrator sa datim imenom i sifrom\r\n * postoji, i ako postoji puni podatke o sesiji i vraca\r\n * poruku o uspehu, u suprotnom o neuspehu.\r\n * \r\n * @param string $kime Korisnicko ime\r\n * @param string $lozinka Korisnicka lozinka\r\n * @return boolean Informacija o uspehu logovanja\r\n */\r\n public function loginAdmin($kime, $lozinka) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"SELECT * FROM admin WHERE KIme = ? AND Lozinka = ?\");\r\n $stmt->bind_param(\"ss\", $kime, $lozinka);\r\n $stmt->execute();\r\n\r\n $res = $stmt->get_result()->fetch_assoc();\r\n if (isset($res['IDAdmin'])) {\r\n $data = array(\r\n 'userid' => $res['IDAdmin'],\r\n 'username' => $kime,\r\n 'loggedIn' => true,\r\n 'admin' => true,\r\n 'konobar' => false,\r\n 'korisnik' => false,\r\n 'restoran' => false\r\n );\r\n\r\n $this->session->set_userdata($data);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Proverava da li je moguce loginovanje bilo kog tipa korisnika\r\n * \r\n * Metoda poziva sve metode vezane za proveru loginovanja odredjee vrste korisnika\r\n * \r\n * \r\n * @param string $kime korisniko ime\r\n * @param string $lozinka korisnicka lozinka\r\n * @return boolean uspesnos mogucnosti logovanja\r\n */\r\n public function login($kime, $lozinka) {\r\n\r\n\r\n if ($this->loginKorisnik($kime, $lozinka) || $this->loginKonobar($kime, $lozinka) || $this->loginRestoran($kime, $lozinka) || $this->loginAdmin($kime, $lozinka)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Proverava da li je registracija restorana moguca\r\n * \r\n * Metoda prihvata sve parametre vezane za registraciju restorana i proverava ih\r\n * shodno pravilima sistema. Ukoliko sve provere prodju kreira se restoran sa odredjenom galerijom slika,\r\n * i stolovima.(sto i slike su naglaseni jer oni nisu samo polja u restoranu vec i posebne tabele u bazi)\r\n * \r\n * @param array $res asocijativni niz koji sadrzi sve podatke unete preko forme za registraciju restorana\r\n * @return boolean uspesnost registracije restorana\r\n */\r\n public function validateCreateRestoran($res) {\r\n $conn = $this->my_database->conn;\r\n $conn->autocommit(FALSE);\r\n $ok = true;\r\n\r\n $this->load->library('form_validation');\r\n $this->form_validation->set_error_delimiters('
', '
');\r\n\r\n $this->load->database();\r\n $this->form_validation->set_rules('kime', 'korisnicko ime', 'is_unique[Korisnik.KIme]|is_unique[Restoran.KIme]|is_unique[Konobar.KIme]|is_unique[Admin.KIme]|min_length[4]|max_length[49]|trim|required');\r\n\r\n $this->form_validation->set_rules('kod', 'kod za registraciju konobara', 'is_unique[Restoran.KodKonobara]|trim|required|min_length[3]|max_length[10]');\r\n $this->form_validation->set_rules('lozinka', 'lozinka', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('iobj', 'ime objekta', 'required|trim|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('ivlasnika', 'ime vlasnika', 'required|trim|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('pvlasnika', 'prezime vlasnika', 'required|trim|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('kuhinje', 'kuhinje', 'required|trim|min_length[4]|max_length[999]');\r\n $this->form_validation->set_rules('opis', 'opis restorana', 'required|trim|min_length[4]|max_length[2999]');\r\n\r\n if ($this->form_validation->run() == FALSE) {\r\n return false;\r\n } else {\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"INSERT INTO restoran(KIme,Lozinka,ImeObjekta,\r\n ImeVlasnika,PrezimeVlasnika,Email,Opis,Kuhinja,Opstina,KodKonobara)VALUES(?,?,?,?,?,?,?,?,?,?)\");\r\n $stmt->bind_param(\"sssssssssi\", $res['kime'], $res['lozinka'], $res['iobj'], $res['ivlasnika'], $res['pvlasnika'], $res['email'], $res['opis'], $res['kuhinje'], $res['opstina'], $res['kod']);\r\n $stmt->execute() ? null : $ok = false;\r\n $restoranId = $stmt->insert_id;\r\n\r\n if (is_numeric($res['sto2'])) {\r\n for ($i = 1; $i <= $res['sto2']; $i++) {\r\n $this->createSto(2, $restoranId) ? null : $ok = false;\r\n }\r\n }\r\n if (is_numeric($res['sto4'])) {\r\n for ($i = 1; $i <= $res['sto4']; $i++) {\r\n $this->createSto(4, $restoranId) ? null : $ok = false;\r\n }\r\n }\r\n if (is_numeric($res['sto6'])) {\r\n for ($i = 1; $i <= $res['sto6']; $i++) {\r\n $this->createSto(6, $restoranId) ? null : $ok = false;\r\n }\r\n }\r\n if(!( $this->uploadSlika($restoranId) == true)) $ok = false;\r\n\r\n if ($ok == false) {\r\n $conn->rollback();\r\n $conn->autocommit(TRUE);\r\n return false;\r\n\r\n } else {\r\n $conn->commit();\r\n }\r\n\r\n $conn->autocommit(TRUE);\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Vrsi cuvanje napravljenih izmena na profilu restorana\r\n * \r\n * Metoda prima sve parametre vezane za izmenu profila restorana\r\n * i vrsi provere nad njima shodno pravilima sistema. Ukoliko sve\r\n * provere prodju, pamte se promene u bazi. Ukoliko ne prodju, izmene\r\n * nece biti upamcene i vraca se poruka o neuspehu.\r\n * \r\n * @param array $restoran asocijativni niz koji sadrzi sve podatke o restoranu koji su uneti u formu\r\n * @param integer $id ID restorana\r\n * @return boolean Uspeh/neuspeh\r\n */\r\n public function updateRestaurant($restoran, $id) {\r\n $this->load->library('form_validation');\r\n $this->form_validation->set_error_delimiters('
', '
');\r\n $this->load->database();\r\n\r\n $this->form_validation->set_rules('lozinka', 'lozinka', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('iobj', 'ime objekta', 'required|trim|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('ivlasnika', 'ime vlasnika', 'required|trim|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('pvlasnika', 'prezime vlasnika', 'required|trim|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim|min_length[4]|max_length[49]');\r\n \r\n $this->form_validation->set_rules('kuhinje', 'kuhinje', 'required|trim|min_length[4]|max_length[999]');\r\n $this->form_validation->set_rules('opis', 'opis restorana', 'required|trim|min_length[4]|max_length[2999]');\r\n\r\n if ($this->form_validation->run() == FALSE) {\r\n return false;\r\n } else {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"UPDATE restoran SET Lozinka=?,ImeObjekta=?,ImeVlasnika=?,PrezimeVlasnika=?,Email=?,Opis=?,Kuhinja=?,Opstina=? WHERE IDRestoran=?\");\r\n $stmt->bind_param(\"ssssssssi\", $restoran['lozinka'], $restoran['iobj'], $restoran['ivlasnika'], $restoran['pvlasnika'], $restoran['email'], $restoran['opis'], $restoran['kuhinje'], $restoran['opstina'], $id);\r\n $stmt->execute();\r\n $restoranId = $stmt->insert_id;\r\n\r\n if (is_numeric($restoran['sto2'])) {\r\n $this->TableForTwo($restoran, $id);\r\n }\r\n if (is_numeric($restoran['sto4'])) {\r\n $this->TableForFour($restoran, $id);\r\n }\r\n if (is_numeric($restoran['sto6'])) {\r\n $this->TableForSix($restoran, $id);\r\n }\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Pravi nove stolove za dvoje, ili brise stare, prilikom update-a\r\n * profila restorana\r\n * \r\n * Metoda prima asocijativni niz svih podataka o restoranu \r\n * cija se izmena vrsi i, na osnovu novog broja stolova koji je\r\n * za tu kolicinu ljudi, dodaju se novi stolovi u bazu, ili se\r\n * brise razlika prethodnih i novih.\r\n * \r\n * @param array $restoran asocijativni niz podataka o restoranu\r\n * @param integer $id ID restorana\r\n */\r\n public function TableForTwo($restoran, $id) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $param['broj'] = 2;\r\n $stmt->prepare(\"SELECT * FROM sto WHERE IDRestoranFK=? AND BrojOsoba=?\");\r\n $stmt->bind_param(\"ii\", $id, $param['broj']);\r\n $stmt->execute();\r\n $result = $stmt->get_result()->num_rows;\r\n if ($result > $restoran['sto2']) {\r\n for ($i = 1; $i <= ($result - $restoran['sto2']); $i++) {\r\n $this->deleteSto(2, $id);\r\n }\r\n } else if ($result < $restoran['sto2']) {\r\n for ($i = 1; $i <= ($restoran['sto2'] - $result); $i++) {\r\n $this->createSto(2, $id);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Dodaje nove stolove za cetvoro, ili brise stare, prilikom\r\n * update-a profila restorana\r\n * \r\n * Metoda prima asocijativni niz svih podataka o restoranu \r\n * cija se izmena vrsi i, na osnovu novog broja stolova koji je\r\n * za tu kolicinu ljudi, dodaju se novi stolovi u bazu, ili se\r\n * brise razlika prethodnih i novih.\r\n * \r\n * @param array $restoran asocijativni niz podataka o restoranu\r\n * @param integer $id ID restorana\r\n */\r\n public function TableForFour($restoran, $id) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $param['broj'] = 4;\r\n $stmt->prepare(\"SELECT * FROM sto WHERE IDRestoranFK=? AND BrojOsoba=?\");\r\n $stmt->bind_param(\"ii\", $id, $param['broj']);\r\n $stmt->execute();\r\n $result = $stmt->get_result()->num_rows;\r\n if ($result > $restoran['sto4']) {\r\n for ($i = 1; $i <= ($result - $restoran['sto4']); $i++) {\r\n $this->deleteSto(4, $id);\r\n }\r\n } else if ($result < $restoran['sto4']) {\r\n for ($i = 1; $i <= ($restoran['sto4'] - $result); $i++) {\r\n $this->createSto(4, $id);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Dodaje nove stolove za sestoro, ili brise stare, prilikom\r\n * update-a profila restorana\r\n * \r\n * Metoda prima asocijativni niz svih podataka o restoranu \r\n * cija se izmena vrsi i, na osnovu novog broja stolova koji je\r\n * za tu kolicinu ljudi, dodaju se novi stolovi u bazu, ili se\r\n * brise razlika prethodnih i novih.\r\n * \r\n * @param array $restoran asocijativni niz podataka o restoranu\r\n * @param integer $id ID restorana\r\n */\r\n public function TableForSix($restoran, $id) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $param['broj'] = 6;\r\n $stmt->prepare(\"SELECT * FROM sto WHERE IDRestoranFK=? AND BrojOsoba=?\");\r\n $stmt->bind_param(\"ii\", $id, $param['broj']);\r\n $stmt->execute();\r\n $result = $stmt->get_result()->num_rows;\r\n if ($result > $restoran['sto6']) {\r\n for ($i = 1; $i <= ($result - $restoran['sto6']); $i++) {\r\n $this->deleteSto(6, $id);\r\n }\r\n } else if ($result < $restoran['sto6']) {\r\n for ($i = 1; $i <= ($restoran['sto6'] - $result); $i++) {\r\n $this->createSto(6, $id);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Funkcija koja kreira sto za odredjeni restoran\r\n * \r\n * Funkcija koja vrsi insertovanje u bazu \r\n * Kreira novu tabelu sto za oredjeni restoran\r\n * \r\n * @param Integer $brojOsoba tip stola koji se kreira, koliko ljudi moze da sedne za isti\r\n * @param Integer $restoranId id restorana kome sto pripada\r\n */\r\n public function createSto($brojOsoba, $restoranId) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"INSERT INTO sto(IDRestoranFK,BrojOsoba)VALUES(?,?)\");\r\n $stmt->bind_param(\"ii\", $restoranId, $brojOsoba);\r\n return $stmt->execute();\r\n }\r\n\r\n /**\r\n * Funkcija koja brise sto za odredjeni restoran\r\n * \r\n * Metoda prima broj osoba i id restorana, na osnovu kojih\r\n * povezuje koji sto u bazi treba da izbrise. Vrsi brisanje reda\r\n * iz baze. \r\n * \r\n * @param integer $brojOsoba koliko ljudi moze da sedne za sto\r\n * @param integer $id ID restorana kome taj sto pripada\r\n */\r\n public function deleteSto($brojOsoba, $id) {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"DELETE FROM sto WHERE IDRestoranFK=? AND BrojOsoba=? LIMIT 1\");\r\n $stmt->bind_param(\"ii\", $id, $brojOsoba);\r\n $stmt->execute();\r\n }\r\n\r\n /**\r\n * Proverava da li je registracija korisnika moguca.\r\n * \r\n * Metoda proverava sve parametre vezane za registraciju korisnika i \r\n * proverava ih u skladu sa pravilima sistema. Ukoliko su provere prosle\r\n * uspesno kreira se novi korisnik.\r\n * \r\n * @param array $kor Asocijativni niz koji sadrzi sve podatke\r\n * unete preko forme za registraciju korisnika\r\n * @return boolean Informacija o uspehu ili neuspehu registracije\r\n */\r\n public function validateCreateKorisnik($kor) {\r\n $this->load->library('form_validation');\r\n $this->form_validation->set_error_delimiters('
', '
');\r\n\r\n $this->load->database();\r\n $this->form_validation->set_rules('username', 'korisnicko ime', 'is_unique[Korisnik.KIme]|is_unique[Restoran.KIme]|is_unique[Konobar.KIme]|is_unique[Admin.KIme]|trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('name', 'ime vlasnika', 'trim|required|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('lastname', 'prezime vlasnika', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email');\r\n\r\n if ($this->form_validation->run() == FALSE) {\r\n return false;\r\n } else {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"INSERT INTO korisnik(KIme,Lozinka,Ime,Prezime,Email)VALUES(?,?,?,?,?)\");\r\n $stmt->bind_param(\"sssss\", $kor['username'], $kor['password'], $kor['name'], $kor['lastname'], $kor['email']);\r\n $stmt->execute();\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Vrsi cuvanje napravljenih izmena na profilu korisnika\r\n * \r\n * Metoda prima sve parametre vezane za izmenu profila korisnika\r\n * i vrsi provere nad njima shodno pravilima sistema. Ukoliko sve\r\n * provere prodju, pamte se promene u bazi. Ukoliko ne prodju, izmene\r\n * nece biti upamcene i vraca se poruka o neuspehu.\r\n * \r\n * @param array $korisnik asocijativni niz podataka o korisniku koji se prosledjuju kroz formu\r\n * @param integer $id ID korisnika\r\n * @return boolean Uspeh/neuspeh\r\n */\r\n public function updateUser($korisnik, $id) {\r\n $this->load->library('form_validation');\r\n $this->form_validation->set_error_delimiters('
', '
');\r\n\r\n $this->load->database();\r\n $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('name', 'ime vlasnika', 'trim|required|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('lastname', 'prezime vlasnika', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email');\r\n\r\n if ($this->form_validation->run() == FALSE) {\r\n return false;\r\n } else {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"UPDATE korisnik SET Lozinka=?,Ime=?,Prezime=?,Email=? WHERE IDKorisnik=?\");\r\n $stmt->bind_param(\"ssssi\", $korisnik['password'], $korisnik['name'], $korisnik['lastname'], $korisnik['email'], $id);\r\n $stmt->execute();\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Proverava da li je registracija konobara moguca.\r\n * \r\n * Metoda prihvata sve parametre vezane za registraciju admina i proverava ih \r\n * u skladu sa pravilima sistema. Ukoliko sve provere prodju uspesno, \r\n * kreira se novi konobar.\r\n * \r\n * @param array $konobar Asocijativni niz koji sadrzi sve podatke\r\n * unete preko forme za registraciju konobara\r\n * @return boolean Informacija o uspehu ili neuspehu registracije\r\n */\r\n public function validateCreateKonobar($konobar) {\r\n $this->load->library('form_validation');\r\n $this->form_validation->set_error_delimiters('
', '
');\r\n\r\n $this->load->database();\r\n $this->form_validation->set_rules('username', 'korisnicko ime', 'is_unique[Korisnik.KIme]|is_unique[Restoran.KIme]|is_unique[Konobar.KIme]|is_unique[Admin.KIme]|min_length[4]|max_length[49]|trim|required');\r\n $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('name', 'ime vlasnika', 'trim|required|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('lastname', 'prezime vlasnika', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email');\r\n $this->form_validation->set_rules('kod', 'kod konobara', 'required|trim|min_length[3]|max_length[10]');\r\n\r\n\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"SELECT IDRestoran FROM restoran WHERE KodKonobara = ?\");\r\n $konobar['kod'] +=0;\r\n $stmt->bind_param(\"i\", $konobar['kod']);\r\n $stmt->execute();\r\n $result = $stmt->get_result()->fetch_array();\r\n\r\n\r\n\r\n\r\n if ($this->form_validation->run() == FALSE || $result == null) {\r\n return false;\r\n } else {\r\n $konobar['IDRestoranFK'] = $result['IDRestoran'] + 0;\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"INSERT INTO konobar(KIme,Lozinka,Ime,Prezime,Email,IDRestoranFK)VALUES(?,?,?,?,?,?)\");\r\n $stmt->bind_param(\"sssssi\", $konobar['username'], $konobar['password'], $konobar['name'], $konobar['lastname'], $konobar['email'], $konobar['IDRestoranFK']);\r\n $stmt->execute();\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Vrsi cuvanje napravljenih izmena na profilu konobara\r\n * \r\n * Metoda prima sve parametre vezane za izmenu profila konobara\r\n * i vrsi provere nad njima shodno pravilima sistema. Ukoliko sve\r\n * provere prodju, pamte se promene u bazi. Ukoliko ne prodju, izmene\r\n * nece biti upamcene i vraca se poruka o neuspehu.\r\n * \r\n * @param array $konobar asocijativni niz podataka o konobaru koji se prosledjuju iz forme\r\n * @param integer $id ID konobar\r\n * @return boolean Uspeh/neuspeh\r\n */\r\n public function updateWaiter($konobar, $id) {\r\n $this->load->library('form_validation');\r\n $this->form_validation->set_error_delimiters('
', '
');\r\n $this->load->database();\r\n $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('name', 'ime vlasnika', 'trim|required|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('lastname', 'prezime vlasnika', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email');\r\n\r\n if ($this->form_validation->run() == FALSE) {\r\n return false;\r\n } else {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"UPDATE konobar SET Lozinka=?,Ime=?,Prezime=?,Email=? WHERE IDKonobar=?\");\r\n $stmt->bind_param(\"ssssi\", $konobar['password'], $konobar['name'], $konobar['lastname'], $konobar['email'], $id);\r\n $stmt->execute();\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Proverava da li je registracija admina moguca.\r\n * \r\n * Metoda prihvata sve parametre vezane za registraciju admina i proverava ih \r\n * u skladu sa pravilima sistema. Ukoliko sve provere prodju uspesno kreira se novi admin.\r\n *\r\n * @param array $admin Asocijativni niz koji sadrzi sve podatke \r\n * unete preko forme za registraciju admina\r\n * @return boolean Informacija o uspehu ili neuspehu registracije\r\n */\r\n public function validateCreateAdmin($admin) {\r\n\r\n $this->load->library('form_validation');\r\n $this->form_validation->set_error_delimiters('
', '
');\r\n $this->load->database();\r\n\r\n $this->form_validation->set_rules('username', 'korisnicko ime', 'is_unique[Korisnik.KIme]|is_unique[Restoran.KIme]|is_unique[Konobar.KIme]|is_unique[Admin.KIme]|trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('name', 'ime admina', 'trim|required|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('lastname', 'prezime admina', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email');\r\n $this->form_validation->set_rules('code', 'kod za admina', 'required|trim|min_length[3]|max_length[10]');\r\n\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"SELECT IDAdmin FROM admin WHERE KodAdmina = ?\");\r\n $admin['kod'] +=0;\r\n $stmt->bind_param(\"i\", $admin['kod']);\r\n $stmt->execute();\r\n $result = $stmt->get_result()->fetch_array();\r\n\r\n if ($this->form_validation->run() == FALSE || $result == NULL) {\r\n return false;\r\n } else {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"INSERT INTO admin(KIme,Lozinka,Ime,Prezime,Email,KodAdmina)VALUES(?,?,?,?,?,?)\");\r\n $stmt->bind_param(\"sssssi\", $admin['username'], $admin['password'], $admin['ime'], $admin['prezime'], $admin['email'], $admin['kod']);\r\n $stmt->execute();\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Vrsi cuvanje napravljenih izmena na profilu admina\r\n * \r\n * Metoda prima sve parametre vezane za izmenu profila admina\r\n * i vrsi provere nad njima shodno pravilima sistema. Ukoliko sve\r\n * provere prodju, pamte se promene u bazi. Ukoliko ne prodju, izmene\r\n * nece biti upamcene i vraca se poruka o neuspehu.\r\n * \r\n * @param array $admin asocijativni niz podataka o adminu koji se prosledjuju kroz formu\r\n * @param integer $id ID admin\r\n * @return boolean Uspeh/neuspeh\r\n */\r\n public function updateAdmin($admin, $id) {\r\n $this->load->library('form_validation');\r\n $this->form_validation->set_error_delimiters('
', '
');\r\n\r\n $this->load->database();\r\n $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('name', 'ime admina', 'trim|required|min_length[3]|max_length[49]');\r\n $this->form_validation->set_rules('lastname', 'prezime admina', 'trim|required|min_length[4]|max_length[49]');\r\n $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email');\r\n\r\n if ($this->form_validation->run() == FALSE) {\r\n return false;\r\n } else {\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"UPDATE admin SET Lozinka=?,Ime=?,Prezime=?,Email=? WHERE IDAdmin=?\");\r\n $stmt->bind_param(\"ssssi\", $admin['password'], $admin['ime'], $admin['prezime'], $admin['email'], $id);\r\n $stmt->execute();\r\n return true;\r\n }\r\n }\r\n\r\n public function uploadSlika($id) {\r\n $target_dir = \"./slike/\" . $id . \"/\";\r\n mkdir($target_dir);\r\n\r\n $total = count($_FILES['slike']['name']);\r\n\r\n for ($i = 0; $i < $total; $i++) {\r\n\r\n $target_file = $target_dir . basename($_FILES[\"slike\"][\"name\"][$i]);\r\n $uploadOk = 1;\r\n $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);\r\n // Check if image file is a actual image or fake image\r\n if (isset($_POST[\"submit\"])) {\r\n $check = getimagesize($_FILES[\"slike\"][\"tmp_name\"][$i]);\r\n if ($check !== false) {\r\n\r\n $uploadOk = 1;\r\n } else {\r\n return \"File is not an image.\";\r\n $uploadOk = 0;\r\n }\r\n }\r\n // Check if file already exists\r\n if (file_exists($target_file)) {\r\n return \"Sorry, file already exists.\";\r\n $uploadOk = 0;\r\n }\r\n // Check file size\r\n if ($_FILES[\"slike\"][\"size\"][$i] > 500000) {\r\n return \"Sorry, your file is too large.\";\r\n $uploadOk = 0;\r\n }\r\n // Allow certain file formats\r\n if ($imageFileType != \"jpg\" && $imageFileType != \"png\" && $imageFileType != \"jpeg\" && $imageFileType != \"gif\") {\r\n return \"Sorry, only JPG, JPEG, PNG & GIF files are allowed.\";\r\n $uploadOk = 0;\r\n }\r\n // Check if $uploadOk is set to 0 by an error\r\n if ($uploadOk == 0) {\r\n return \"Sorry, your file was not uploaded.\";\r\n // if everything is ok, try to upload file\r\n } else {\r\n if (move_uploaded_file($_FILES[\"slike\"][\"tmp_name\"][$i], $target_file)) {\r\n\r\n $this->insertSlika($id, $target_file);\r\n } else {\r\n return \"Sorry, there was an error uploading your file.\";\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n public function insertSlika($id, $target) {\r\n\r\n $conn = $this->my_database->conn;\r\n $stmt = $conn->stmt_init();\r\n $stmt->prepare(\"INSERT INTO slika(IDRestoranFK, Putanja) VALUES(?,?)\");\r\n $stmt->bind_param(\"is\", $id, $target);\r\n $stmt->execute();\r\n }\r\n\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914298,"cells":{"blob_id":{"kind":"string","value":"6db1335f586ccb6014ee05ab512bd40aa0a05832"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"christian-reis/loja-web-reis"},"path":{"kind":"string","value":"/App/Action/Admin/LoginAction.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2071,"string":"2,071"},"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":"withRedirect(PATH.'/admin/products');\n }\n //return $this->view->render($response,'admin/login/login.phtml');\n\n $vars['title'] = 'Faça seu login';\n $vars['page'] = 'login';\n return $this->view->render($response,'template.phtml',$vars);\n\n //return $this->view->render($response,'page/login.phtml');\n }\n\n public function login($request, $response){ //realiza o login, faz a operação com o banco de dados\n $data = $request->getParsedBody();\n\n $email = strip_tags(filter_var($data['email'],FILTER_SANITIZE_STRING));\n $pass = strip_tags(filter_var($data['pass'],FILTER_SANITIZE_STRING));\n\n if($email != '' && $pass != ''){\n $sql = \"SELECT * FROM `user` WHERE email_user = ? AND pass_user = ?\";\n $user = $this->db->prepare($sql);\n $user->execute(array($email,$pass));\n if($user->rowCount() > 0){\n $r = $user->fetch(\\PDO::FETCH_OBJ);\n $_SESSION[PREFIX.'logado'] = true;\n $_SESSION[PREFIX.'id_user'] = $r->iduser;\n return $response->withRedirect(PATH.'/admin/products');\n }else{\n $vars['erro'] = 'Você não foi encontrado no sistema.';\n return $this->view->render($response,'admin/login/login.phtml',$vars);\n }\n\n }else{\n $vars['erro'] = 'Preencha todos os campos.';\n return $this->view->render($response,'admin/login/login.phtml',$vars);\n }\n }\n\n public function logout($request, $response){ //destroi a sessão, saindo da área administrativa\n unset($_SESSION[PREFIX.'logado']);\n session_destroy();\n return $response->withRedirect(PATH.'/');\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9914299,"cells":{"blob_id":{"kind":"string","value":"04ea58ec13273e53ebabdad319663de93963abcd"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"dru-id/sdk-consumer-rewards"},"path":{"kind":"string","value":"/src/Security/Authentication.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2223,"string":"2,223"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"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":"credentials;\n }\n\n /**\n * @param AuthCredentials $credentials\n * @return Authentication\n */\n public function setCredentials(AuthCredentials $credentials): Authentication\n {\n $this->credentials = $credentials;\n return $this;\n }\n\n /**\n * @return JWT\n */\n public function getJwt(): JWT\n {\n return $this->jwt;\n }\n\n /**\n * @param JWT $jwt\n */\n public function setJwt(JWT $jwt)\n {\n $this->jwt = $jwt;\n }\n\n /**\n * @return JWT token for Bearer Auth Request\n * @throws ConsumerRewardsSdkAuthException\n */\n public function authorize() {\n\n $this->checkRequiredParameters($this->getRequiredRequestParameters(), $this->getCredentials()->jsonSerialize());\n\n $options['body'] = \\GuzzleHttp\\json_encode($this->getCredentials());\n\n $request = Container::get('http')->getRequest('POST', Container::get('http')->buildApiUrl('/auth'), $options);\n $response = Container::get('http')->getResponse($request, ['http_errors' => false]);\n\n if (($response->hasHeader('Authorization')) && ($response->hasHeader('Expires'))) {\n $this->setJwt(new JWT($response->getHeaderLine('Authorization'), strtotime($response->getHeaderLine('Expires'))));\n } else {\n throw new ConsumerRewardsSdkAuthException(\"Not Auth Response from Server\");\n }\n\n return $this->getJwt();\n }\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":99142,"numItemsPerPage":100,"numTotalItems":9914478,"offset":9914200,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODEzNTk4NSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9waHAiLCJleHAiOjE3NTgxMzk1ODUsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.Cm2Ww-a0qyDrqYhCC-SZdtlwNJPI2l_QHY6Z_RYfD2eJG7jAZL1HkqOONWsdccTmSvyIIPcCcLGGCHiWwwE4Dg","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
a4c6e2b929af9ab6ab82267310eee6a20bf0cfb7
PHP
hou1202/exampro-admin
/application/admin/validate/Mold.php
UTF-8
952
2.53125
3
[ "Apache-2.0" ]
permissive
<?php namespace app\admin\validate; use app\common\validate\CommonValidate; class Mold extends CommonValidate { /** * 定义验证规则 * 格式:'字段名' => ['规则1','规则2'...] * * @var array */ protected $rule = [ 'id|类型ID' => 'require|number|isExist:mold,id', 'title|类型名称' => 'require|max:10', 'code|类型代码' => 'require|number|integer|gt:0', ]; /** * 定义错误信息 * 格式:'字段名.规则名' => '错误信息' * * @var array */ protected $message = [ 'id.require' => '类型信息有误', 'id.number' => '类型信息有误', 'id.isExist' => '类型信息有误', ]; /* * 定义验证场景 * 格式:'场景名' => ['字段名1','字段名2'] * */ protected $scene = [ 'save' => ['code','title'], 'edit' => ['id','code','title'], ]; }
true
1be387a90814605ec52e41b9c27f13eb487ffb69
PHP
omaymalberji/ProjetGL
/Ptravel/app/Http/Controllers/admin/volController.php
UTF-8
1,018
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\admin; use App\Vol; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class volController extends Controller { public function createVol() { $vol= new Vol(); $vol->port_depart=1; $vol->port_depart=2; $vol->port_arrivee=2; $vol->heure_depart="18:00"; $vol->heure_arrivee="20:00"; $vol->nb_place=400; $vol->place_dispo=400; $vol->name="hamzat"; $vol->save(); echo "c'est bien mon ami"; } public function deleteVol() { $vol=Vol::find(2); //dd($vol); $vol->delete(); echo "il est supprimé "; } public function updateVol($id) { $vol=Vol::find(1); } public function getVol() { $vols=Vol::all(); echo "hello"; /*foreach ($vols as $vol) { echo $vol->name ." </br> "; echo $vol->avion; }*/ $arr=Array('vols'=>$vols); return view("vols",$arr); } }
true
01a4bd9d677e927c12a0439cb4560686ef15e19e
PHP
eddysiu/imcc
/cms/controllers/main.php
UTF-8
2,143
2.640625
3
[]
no_license
<?php // get config value in one specfic language function getConfigValueInOneLang($item, $lang){ $result = ""; $result = htmlspecialchars(data_configValueInOneLang($item, $lang)); return $result; } // get config value in all languages function getConfigValueInAllLang($item){ $result = ""; $result = htmlspecialchars(data_configValueInAllLang($item)); return $result; } // get the language config from the db for view layout function getlanguageEnable($item, $lang, $currentValue){ $checked = ""; $result = data_configValueInOneLang($item, $lang); if ($result == $currentValue){ $checked = 'checked="checked"'; } return $checked; } // covert <br/> to breakline (in this case convert to "" only) function convertBrToBreakline($content){ $content = str_replace("<br/>","",$content); return $content; } function updateDB($universityname, $title, $address, $email, $map, $tel, $weekday, $weekday_officehour, $weekend, $brochure, $disclaimer, $lang_tw, $lang_cn){ $results; for ($i = 0; $i < 3; $i++){ // $i = 0 English // $i = 1 Tranditional Chinese // $i = 2 Simplified Chinese switch ($i){ case "0": $value = "valueEN"; break; case "1": $value = "valueTW"; break; case "2": $value = "valueCN"; break; } $results[] = db_update("universityname", $universityname[$i], $value); $results[] = db_update("title", $title[$i], $value); $results[] = db_update("address", $address[$i], $value); $results[] = db_update("email", $email[$i], $value); $results[] = db_update("googlemap", $map[$i], $value); $results[] = db_update("tel", $tel[$i], $value); $results[] = db_update("weekday", $weekday[$i], $value); $results[] = db_update("weekday_officehour", $weekday_officehour[$i], $value); $results[] = db_update("weekend", $weekend[$i], $value); $results[] = db_update("brochure", $brochure[$i], $value); $results[] = db_update("disclaimer", $disclaimer[$i], $value); } // for language bar $results[] = db_update("langbar", $lang_tw, "valueTW"); $results[] = db_update("langbar", $lang_cn, "valueCN"); if(in_array("-1", $results)){ return false; } else { return true; } } ?>
true
b1ff7e485f27c2dc25a18e1bb1ecb062ad20bbcc
PHP
sanjeevan/codelovely
/lib/model/doctrine/base/BaseComment.class.php
UTF-8
4,131
2.578125
3
[ "MIT" ]
permissive
<?php /** * BaseComment * * This class has been auto-generated by the Doctrine ORM Framework * * @property integer $id * @property integer $thing_id * @property integer $user_id * @property integer $article_id * @property integer $reply_id * @property integer $reply_depth * @property string $content * @property string $content_html * @property User $User * @property Article $Article * @property Thing $Thing * * @method integer getId() Returns the current record's "id" value * @method integer getThingId() Returns the current record's "thing_id" value * @method integer getUserId() Returns the current record's "user_id" value * @method integer getArticleId() Returns the current record's "article_id" value * @method integer getReplyId() Returns the current record's "reply_id" value * @method integer getReplyDepth() Returns the current record's "reply_depth" value * @method string getContent() Returns the current record's "content" value * @method string getContentHtml() Returns the current record's "content_html" value * @method User getUser() Returns the current record's "User" value * @method Article getArticle() Returns the current record's "Article" value * @method Thing getThing() Returns the current record's "Thing" value * @method Comment setId() Sets the current record's "id" value * @method Comment setThingId() Sets the current record's "thing_id" value * @method Comment setUserId() Sets the current record's "user_id" value * @method Comment setArticleId() Sets the current record's "article_id" value * @method Comment setReplyId() Sets the current record's "reply_id" value * @method Comment setReplyDepth() Sets the current record's "reply_depth" value * @method Comment setContent() Sets the current record's "content" value * @method Comment setContentHtml() Sets the current record's "content_html" value * @method Comment setUser() Sets the current record's "User" value * @method Comment setArticle() Sets the current record's "Article" value * @method Comment setThing() Sets the current record's "Thing" value * * @package socialhub * @subpackage model * @author Sanjeevan Ambalavanar * @version SVN: $Id: Builder.php 6820 2009-11-30 17:27:49Z jwage $ */ abstract class BaseComment extends sfDoctrineRecord { public function setTableDefinition() { $this->setTableName('comment'); $this->hasColumn('id', 'integer', 4, array( 'type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '4', )); $this->hasColumn('thing_id', 'integer', 4, array( 'type' => 'integer', 'length' => '4', )); $this->hasColumn('user_id', 'integer', 4, array( 'type' => 'integer', 'length' => '4', )); $this->hasColumn('article_id', 'integer', 4, array( 'type' => 'integer', 'length' => '4', )); $this->hasColumn('reply_id', 'integer', 4, array( 'type' => 'integer', 'length' => '4', )); $this->hasColumn('reply_depth', 'integer', 4, array( 'type' => 'integer', 'length' => '4', )); $this->hasColumn('content', 'string', null, array( 'type' => 'string', )); $this->hasColumn('content_html', 'string', null, array( 'type' => 'string', )); } public function setUp() { parent::setUp(); $this->hasOne('User', array( 'local' => 'user_id', 'foreign' => 'id')); $this->hasOne('Article', array( 'local' => 'article_id', 'foreign' => 'id')); $this->hasOne('Thing', array( 'local' => 'thing_id', 'foreign' => 'id')); $timestampable0 = new Doctrine_Template_Timestampable(); $this->actAs($timestampable0); } }
true
e50e1aa3d19658df1e4a8bcd41877946a5bc9e1c
PHP
AlexP007/a2c.helper
/lib/traits/loader.php
UTF-8
726
2.65625
3
[]
no_license
<?php namespace A2c\Helper\Traits; use Bitrix\Main\Loader as BxLoader; use Bitrix\Main\LoaderException; /** * Trait Loader * * Этот трейт предоставляет статический * метод-обертку над методом * Loader::includeModule * * @author Alexander Panteleev * @package a2c.helper */ trait Loader { /** * @param string $moduleName * * @return void */ protected static function includeModule() { try { BxLoader::includeModule(static::MODULE_NAME) or die("something wrong with" . static::MODULE_NAME); } catch(LoaderException $e) { die("something wrong with" . static::MODULE_NAME); } } }
true
d52369b3a40a2f2442ee76b82135dd9f121a27ab
PHP
janeczko/vpp
/app/model/UserModel.php
UTF-8
811
2.8125
3
[]
no_license
<?php namespace App\Model; use Nette; class UserModel extends Model { const TABLE = 'user'; /** * @param string $attr * @param string $value * @param string $attrs * @return bool|Nette\Database\IRow|Nette\Database\Row */ public function findBy($attr, $value, $attrs = 'id, username, email, first_name, last_name, password, role') { return parent::findBy($attr, $value, $attrs); } /** * @param array $user * @return bool|int|Nette\Database\Table\IRow */ public function add(array $user) { return $this->db->table($this::TABLE)->insert($user); } public function findAll() { return $this->db->query('SELECT id, username, email, first_name, last_name, role FROM user ORDER BY id')->fetchAll(); } }
true
2c9a301cbfc31e6958291a3b25e238eb7067b295
PHP
Rmy5/symfonyBlog
/src/Entity/Article.php
UTF-8
6,521
2.625
3
[ "MIT" ]
permissive
<?php /* * Create : php bin/console make:entity * * */ namespace App\Entity; use App\Repository\ArticleRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Mapping\ClassMetadata; /** * @ORM\Entity(repositoryClass=ArticleRepository::class) * @ORM\HasLifecycleCallbacks() */ class Article { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $title; /** * @ORM\Column(type="string", length=255) */ private $image; /** * @ORM\Column(type="string", length=255) */ private $intro; /** * @ORM\Column(type="text") */ private $content; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\Column(type="datetime",nullable=true) */ private $updatedAt; /** * @ORM\ManyToMany(targetEntity=Category::class, inversedBy="articles") */ private $categories; /** * @ORM\OneToMany(targetEntity=Comment::class, mappedBy="article", orphanRemoval=true) */ private $comments; public function __construct() { $this->categories = new ArrayCollection(); $this->comments = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(string $image): self { $this->image = $image; return $this; } public function getIntro(): ?string { return $this->intro; } public function setIntro(string $intro): self { $this->intro = $intro; return $this; } public function getContent(): ?string { return $this->content; } public function setContent(string $content): self { $this->content = $content; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): self { $this->createdAt = $createdAt; return $this; } public function getUpdatedAt(): ?\DateTimeInterface { return $this->updatedAt; } public function setUpdatedAt(\DateTimeInterface $updatedAt): self { $this->updatedAt = $updatedAt; return $this; } /* * Validation des datas de l'entity * -> réutilisé par le form pour controler les inputs */ public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint( 'title', new Assert\Length([ 'min' => 10, 'max' => 255, 'minMessage' => 'Le title est trop court !' ]) ); $metadata->addPropertyConstraint( 'image', new Assert\Url() ); $metadata->addPropertyConstraint( 'intro', new Assert\Length([ 'min' => 10, 'max' => 255, 'minMessage' => 'L\'intro est trop courte !' ]) ); $metadata->addPropertyConstraint( 'content', new Assert\Length([ 'min' => 10, 'max' => 255, 'minMessage' => 'Le content est trop court !' ]) ); $metadata->addPropertyConstraint( 'categories', new Assert\Count(['min'=>1]), ); /* Marche pas sur le type $metadata->addPropertyConstraint( 'categories', new Assert\Type(Category::class), //new Assert\Type(\ArrayCollection|Category::class), //new Assert\Type(\ArrayCollection::class), ); */ } /** * Call avant insertion * @ORM\PrePersist */ public function prePersist():void{ if(!$this->getCreatedAt()){ $this->setCreatedAt(new \DateTime()); } //$this->setUpdatedAt(new \DateTime()); } /** * Call après insertion * @ORM\PostPersist */ public function postPersist():void{ } /** * Call avant Update * @ORM\PreUpdate */ public function preUpdate():void{ $this->setUpdatedAt(new \DateTime()); } /** * Call après Update * @ORM\PostUpdate */ public function postUpdate():void{ } /** * @return Collection|Category[] */ public function getCategories(): Collection { return $this->categories; } public function addCategory(Category $category): self { if (!$this->categories->contains($category)) { $this->categories[] = $category; } return $this; } public function removeCategory(Category $category): self { $this->categories->removeElement($category); return $this; } public function addCategories(Collection $categories): self{ foreach($categories as $category){ $this->addCategory($category); } return $this; } public function removeCategories(Collection $categories): self{ foreach($categories as $category){ $this->removeCategory($category); } return $this; } /** * @return Collection|Comment[] */ public function getComments(): Collection { return $this->comments; } public function addComment(Comment $comment): self { if (!$this->comments->contains($comment)) { $this->comments[] = $comment; $comment->setArticle($this); } return $this; } public function removeComment(Comment $comment): self { if ($this->comments->removeElement($comment)) { // set the owning side to null (unless already changed) if ($comment->getArticle() === $this) { $comment->setArticle(null); } } return $this; } }
true
307bff31869ed2dcab186d0405e4ab2e7b22b09e
PHP
Manh-Nguyen-JB/LaravelGacha
/app/Repositories/MyAccountRepository.php
UTF-8
640
2.921875
3
[ "MIT" ]
permissive
<?php namespace App\Repositories; use Auth; class MyAccountRepository extends BaseRepository{ /** * Create a new UserRepository instance. * * @param App\Models\User $user * @return void */ public function __construct() { $this->model = Auth::user(); } public function is_logined() { return (isset($this->model) ? TRUE : FALSE);; } public function giveBonusCoin() { $user = $this->model; $now = time(); $given_coin = $now - strtotime($user->last_add_coint_time); if($given_coin > 0){ $user->coin += $given_coin; $user->last_add_coint_time = date('Y-m-d H:i:s', $now); $user->save(); } } }
true
a64392be171a62bf43366c6608488b7267af6a84
PHP
amkoroew/hse.labor
/Classes/Domain/Model/StudentExercise.php
UTF-8
3,156
2.890625
3
[]
no_license
<?php namespace HSE\Labor\Domain\Model; /* * * This script belongs to the FLOW3 package "HSE.Labor". * * * * */ use TYPO3\FLOW3\Annotations as FLOW3; use Doctrine\ORM\Mapping as ORM; /** * A StudentExercise * * @FLOW3\Entity */ class StudentExercise implements StudentInterface, ExerciseInterface { /** * The student * @var \HSE\Labor\Domain\Model\Student * @ORM\ManyToOne(inversedBy="exercises") */ protected $student; /** * The exercise * @var \HSE\Labor\Domain\Model\Exercise * @ORM\ManyToOne(inversedBy="students") */ protected $exercise; /** * Exercise already answered * @var boolean */ protected $answered; /** * Constructs a new StudentExercise * * @param \HSE\Labor\Domain\Model\Student $student * @param \HSE\Labor\Domain\Model\Exercise $exercise * @return void */ public function __construct($student, $exercise) { $this->student = $student; $this->exercise = $exercise; $this->answered = false; } /** * @param \HSE\Labor\Domain\Model\Student $student * @return void */ public function setStudent($student) { $this->student = $student; } /** * @return \HSE\Labor\Domain\Model\Student */ public function getStudent() { return $this->student; } /** * @param \HSE\Labor\Domain\Model\Exercise $exercise * @return void */ public function setExercise($exercise) { $this->exercise = $exercise; } /** * @return \HSE\Labor\Domain\Model\Exercise */ public function getExercise() { return $this->exercise; } /** * @return void */ public function remove() { $this->student->removeExercise($this); $this->exercise->removeStudent($this); } /** * @param boolean $answered * @return void */ public function setAnswered($answered) { $this->answered = $answered; } /** * @return boolean */ public function getAnswered() { return $this->answered; } /** * @param \HSE\Labor\Domain\Model\StudentExercise $studentExercise * @return void */ public function addStudent($studentExercise) { $this->exercise->addStudent($studentExercise); } /** * @return \HSE\Labor\Domain\Model\Lab */ public function getLab() { return $this->exercise->getLab(); } /** * @return integer */ public function getExerciseNumber() { return $this->exercise->getExerciseNumber(); } /** * @return string */ public function getQuestion() { return $this->exercise->getQuestion(); } /** * @return string */ public function getHint() { return $this->exercise->getHint(); } /** * @return string */ public function getAnswer() { return $this->exercise->getAnswer(); } /** * @return boolean */ public function getRequired() { return $this->exercise->getRequired(); } /** * @return string */ public function __toString() { return 'Student '.$this->student->getName()->getFullName().' has to Solve Exercise '.$this->exercise->getExerciseNumber(); } }
true
e780cc0e45a8aabbe1cb150f04662f54f2838906
PHP
010Minds/api
/module/Stock/src/Operation/Model/Operation.php
UTF-8
4,789
2.75
3
[]
no_license
<?php namespace Operation\Model; use Zend\I18n\Validator\Float; use Zend\Validator\NotEmpty; use Zend\Validator\AbstractValidator; use Zend\InputFilter\InputFilter; use Zend\InputFilter\Factory; use Zend\InputFilter\InputFilterAwareInterface; use Zend\InputFilter\InputFilterInterface; /* Sets the operation status */ class OperationStatus { const PENDING = 1; const ACCEPTED = 2; const REJECTED = 3; public static function getStatus($status) { switch($status) { case 'pending': $status = self::PENDING; break; case 'accepted': $status = self::ACCEPTED; break; case 'rejected': $status = self::REJECTED; break; default: throw new \Exception("Status invalid in getStatus", 1); } $status = (int)$status; return $status; } } /* Sets the type status */ class TypeStatus { const BUY = 1; const SELL = 2; public static function getType($type) { switch($type) { case 'buy': $type = self::BUY; break; case 'sell': $type = self::SELL; break; default: throw new \Exception("Type invalid in getType", 1); } $type = (int)$type; return $type; } } class Operation implements InputFilterAwareInterface { public $id; public $userId; public $stockId; public $qtd; public $value; public $type; public $status; public $reason; public $createDate; protected $inputFilter; public function exchangeArray($data) { $this->id = (!empty($data['id'])) ? $data['id'] : null; $this->userId = (!empty($data['user_id'])) ? $data['user_id'] : null; $this->stockId = (!empty($data['stock_id'])) ? $data['stock_id'] : null; $this->qtd = (!empty($data['qtd'])) ? $data['qtd'] : null; $this->value = (!empty($data['value'])) ? $data['value'] : null; $this->type = (!empty($data['type'])) ? $data['type'] : null; $this->status = (!empty($data['status'])) ? $data['status'] : null; $this->reason = (!empty($data['reason'])) ? $data['reason'] : null; $this->createDate = (!empty($data['create_date'])) ? $data['create_date'] : null; } public function getArrayCopy() { return get_object_vars($this); } public function setInputFilter(InputFilterInterface $inputFilter) { throw new \Exception("Not used"); } public function getInputFilter() { if(!$this->inputFilter) { $inputFilter = new InputFilter(); $factory = new Factory(); $inputFilter->add($factory->createInput( array( 'name' => 'id', 'required' => false, 'filters' => array( array('name' => 'Int'), ) ) )); $inputFilter->add($factory->createInput( array( 'name' => 'user_id', 'required' => true, 'filters' => array( array('name' => 'Int'), ), 'validators' => array( array( 'name' => 'Between', 'options' => array( 'min' => 1, 'max' => 1000, ), ), ), ) )); $inputFilter->add($factory->createInput( array( 'name' => 'stock_id', 'required' => true, 'filters' => array( array('name' => 'Int'), ), 'validators' => array( array( 'name' => 'Between', 'options' => array( 'min' => 1, 'max' => 1000, ), ), ), ) )); $inputFilter->add($factory->createInput( array( 'name' => 'qtd', 'required' => true, 'filters' => array( array('name' => 'Int'), ), 'validators' => array( array( 'name' => 'Between', 'options' => array( 'min' => 1, 'max' => 1000, ), ), ), ) )); $inputFilter->add($factory->createInput( array( 'name' => 'value', 'required' => true, 'filters' => array( array('name' => 'NumberFormat'), ), 'validators' => array( array( 'name' => 'Float', 'options' => array( 'messages' => array( Float::INVALID => 'Invalid', Float::NOT_FLOAT => 'NOT_FLOAT', ), ), ), ), ) )); $inputFilter->add($factory->createInput( array( 'name' => 'type', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ) ) )); $inputFilter->add($factory->createInput( array( 'name' => 'status', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ) ) )); $this->inputFilter = $inputFilter; } return $this->inputFilter; } }
true
46d134a0d57621ae87e599508e1c8ee24c2964e4
PHP
voximplant/apiclient-php
/src/Examples/RoleSystem/SetSubUserInfo.php
UTF-8
1,343
2.78125
3
[ "Apache-2.0" ]
permissive
<?php /** * @method SetSubUserInfo Edits a subuser. */ // Path to your autoload.php require_once '/path/to/vendor/autoload.php'; use Voximplant\VoximplantApi; use Voximplant\Resources\Params\SetSubUserInfoParams; /** * In order to use Voximplant PHP SDK, you need the following: * 1. A developer account. If you don't have one, sign up here https://voximplant.com/sign-up/. * 2. A private API key. To create it, call the [CreateKey] method. Save the result value in a file. */ // Create API Object $voxApi = new VoximplantApi('path/to/private/api/key.json'); /** * @param array $params (See below) * subuser_id - The subuser's ID * old_subuser_password - The subuser old password. It is required if __new_subuser_password__ is specified * new_subuser_password - The new user password. Must be at least 8 characters long and contain at least one uppercase and lowercase letter, one number, and one special character * description - The new subuser description */ $params = new SetSubUserInfoParams(); $params->subuser_id = 12; $params->old_subuser_password = 'old_test_password'; $params->new_subuser_password = 'test_pass'; $params->description = 'test_desc'; // Edit the password and description for the subuser with id = 12 from account_id = 1. $result = $voxApi->RoleSystem->SetSubUserInfo($params); // Show result var_dump($result);
true
abcaf4878a3b4a6762cb2befa0e690c0eecdeca7
PHP
tahirgit/cloudstore
/controllers/BillingController.php
UTF-8
2,459
2.578125
3
[]
no_license
<?php class BillingController extends Controller { public function filters() { return array( 'accessControl' // required to enable accessRules ); } /** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow authenticated users to access all actions 'actions'=>array('index'), 'users'=>array('@'), ), array('deny', // deny all users 'users'=>array('*'), ), ); } /* Manage Billing Profile */ public function actionIndex() { $customer_id = Yii::app()->user->pk_customer_id; $customer_model = new Customers; $billing_model = new Billings; //$customer_model->scenario = "billing"; $billing_model->scenario = "billing"; $customerInfo = $customer_model->find('pk_customer_id = '.$customer_id); $profile = $customer_model->find('pk_customer_id = "'.$customer_id.'" or pk_customer_id = '.$customerInfo->parent_id); /* Child Accounts Setting */ $related_customer = $customer_model->getAllRelatedCustomers( $customer_id ); if($customerInfo->parent_id == 0) $billing = $billing_model->find('fk_customer_id = "'.$customer_id.'"'); else $billing = $billing_model->find('fk_customer_id = "'.$customerInfo->parent_id.'"'); if(count($billing) < 1) { $billing = $billing_model; } /* if Submit Form for Update */ if( isset($_POST['Customers']) or isset($_POST['Billings']) ) { $customer_model->attributes = $_POST['Customers']; $billing_model->attributes = $_POST['Billings']; //if($customer_model->validate() && $this->validate()) if($billing_model->validate()) { $customer_model->updateByPk($customer_id, $_POST['Customers']); $billing_model->updateByPk($_POST['billing_id'], $_POST['Billings']); $subject = "Billing profile updated successfully"; $message = "Billing profile has been updated successfully by ".Yii::app()->user->fullname; Yii::app()->user->setFlash('success', "Billing updated Successfully!"); $this->redirect(array("billing/index")); } } $this->render('index', array('personal_info'=> $profile, 'billing_profile'=>$billing, "related_customers"=>$related_customer, "model"=>$billing_model,"customer_model"=>$customer_model)); } }
true
f7fe7fe6db4d34c80f615380b7654626a822b01a
PHP
emirodriguez/search-algorithm-ia
/src/InformedSearcher.php
UTF-8
3,811
3.015625
3
[]
no_license
<?php namespace Search; use Ds\Queue; use Ds\Stack; class InformedSearcher { /** * Search the path of the solution * * @param array $connections * @param array $heuristics * @param string $startNode * @param string $endNode * @param bool $byProfundity * * @return array */ public function searchSolution( array $connections, array $heuristics, string $startNode, string $endNode ): array { $result = []; $solutionNode = $this->searchNode($connections, $heuristics, $startNode, $endNode); $node = $solutionNode; if (!empty($node)) { while (!empty($node->getParent())) { array_push($result, $node->getName()); $node = $node->getParent(); } array_push($result, $startNode); $result = array_reverse($result); } return [ 'result' => $result, 'cost' => $solutionNode->getCost(), ]; } /** * Search the node of the solution * * @param array $connections * @param array $heuristics * @param string $startNode * @param string $endNode * * @return Node|null */ public function searchNode( array $connections, array $heuristics, string $startNode, string $endNode ): ?Node { $startNode = new Node($startNode); $startNode->setCost(0); $visited = []; $borders = new Queue(); $borders->push($startNode); while ($borders->count() > 0) { $borders = $this->orderQueue($borders, $heuristics); /** @var Node $node */ $node = $borders->pop(); array_push($visited, $node); if ($node->getName() === $endNode) { return $node; } $children = []; foreach ($connections[$node->getName()] as $key => $value) { $child = new Node($key); $cost = $value; $child->setCost($node->getCost() + $cost); array_push($children, $child); if (!$child->inNodes($visited)) { $borders->push($child); if ($child->inNodes($borders->toArray())) { /** @var Node $border */ foreach ($borders->toArray() as $border) { if ($border->getName() === $child->getName() && $border->getCost() > $child->getCost()) { $borders = $this->removeFromQueue($borders, $border); $borders->push($child); } } } else { $borders->push($child); } } } $node->setChildren($children); } return null; } private function orderQueue(Queue $queue, array $heuristics): Queue { $items = $queue->toArray(); uasort($items, function (Node $first, Node $second) use ($heuristics) { $hx = $heuristics[$first->getName()]; $gx = $first->getCost(); $fx = $hx + $gx; $hy = $heuristics[$second->getName()]; $gy = $second->getCost(); $fy = $hy + $gy; return $fx > $fy; }); return new Queue($items); } private function removeFromQueue(Queue $queue, Node $node): Queue { $items = $queue->toArray(); $items = array_filter($items, function (Node $n) use ($node) { return ($n->getName() !== $node->getName()); }); return new Queue($items); } }
true
0dd0d7a0c5c470d78c20178fa787bee1d5994169
PHP
gmarv1n/design-patterns-php
/Structural/Flyweight/CarVariation.php
UTF-8
1,371
3.6875
4
[]
no_license
<?php /** * Structural Patterns: Flyweight * CarVariation class * * Класс с повторяющимися свойствами автомобиля * * @author Gregory Yatsukhno <[email protected]> * @version 12.04.2021 */ namespace DesignPatterns\Structural\Flyweight; class CarVariation { // Повторяющимися, в нашем примере, будут // цвет, тип кузова и тип коробки передач public $color; public $bodyType; public $transmissionType; public function __construct($color, $bodyType, $transmissionType) { $this->color = $color; $this->bodyType = $bodyType; $this->transmissionType = $transmissionType; } // Функция дл описания частей автомобиля с поправкой на то, // что вариация - часть целого. Соответственно в виде аргументов // нужно передать владельца и производителя public function describeCarVariant($owner, $manufacturer): void { echo "Owner is: ".$owner."<br>"; echo "Manufacturer is: ".$manufacturer."<br>"; echo "Color is: ".$this->color."<br>"; echo "Body type is: ".$this->bodyType."<br>"; echo "Drive type is: ".$this->transmissionType."<br>"; } }
true
8384382cff20f54bb2a43ca76108697e74210e63
PHP
AlfredQ/sicobim
/sistema/modelo/baseDatos.Class.php
UTF-8
15,505
2.578125
3
[]
no_license
<?php session_start(); abstract class Base { //Conexion para la Base De Datos abstract public function Conexion(); abstract public function Desconexion(); /** * * Gestiona registros en la base de datos haciendo uso de Procediminetos Almacenados en PostgreSQL * @PARAM $SP -> Inidica el Stored Procedure (Procedimineto Almacenado) a utilizar * @PARAM $Destino -> Inidica el sitio (p�gina) a donde resulta ubicado el usuario luego de que se ejecuta la funcion * **/ ///EL RESULTADO LO EVALUA COMO UN BOOLEAN abstract public function EjecutarProcedure($sp); /** * * Ejecuta una vista de PostgreSQL que devuelve los campos necesarios para mostrar por pantalla * @PARAM $VW -> Inidica la vista a invocar * @PARAM $CampoID -> Indica el campo por el que se quiere filtrar * @PARAM $ID -> Indica el valor por el que se esta filtrando * @RETURN $resultado -> Recordset de todo lo que coincide con la condicion anterior * **/ abstract public function EjecutarQuery($vista); /** * * Ejecuta una vista de PostgreSQL que devuelve los campos necesarios para mostrar por pantalla * @PARAM $VW -> Inidica la vista a invocar * @PARAM $CampoID -> Indica el campo por el que se quiere filtrar * @PARAM $ID -> Indica el valor por el que se esta filtrando * @RETURN $resultado -> Recordset de todo lo que coincide con la condicion anterior * **/ abstract public function EjecutarVista($vista); abstract public function EjecutarVistaXCampos($vista, $campos); abstract public function ListarVW($vista, $valor, $campo); abstract public function ListarVWCamposVarios($vista, $campos, $valor, $descripcion,$valorSelected); abstract public function ListarVWVarios($vista, $valor, $campo1, $campo2); /* ESTA FUNCION LISTA POR CAMPOS ESPECIFICOS DE UNA VISTA DE BASE DE DATOS, ADEMAS MUESTRA UNA UNICA DESCRIPCION ** Y EVALUA SI UNA OPCION DEL COMBO BOX FUE SELECCIONADA PARA MOSTRAR EL VALOR QUE EL USUARIO ESCOJIO ** POR EJEMPLO, ESTA FUNCION ES UTILIZADA EN LA CONSULTA DE MOVIMIENTO DE MEDIDORES */ abstract public function ListarVWxCampos($vista, $campos, $valor, $descripcion,$comboAEvaluar); abstract public function ListarVWxId($vista, $campos, $valor, $descripcion, $comoAEvaluar); abstract public function ListarVWSelectedMultiples($listado, $valor, $campo, $selecciones); } include_once("../../../assets/adodb5/adodb.inc.php"); class BaseDatos extends Base{ private $vIdBaseDatos; private $vNomBaseDatos; private $vUsuario; private $vClave; private $vServidor; private $vDsn; private $vDb; private $vEsquema; private $vEstatusBaseDatos; //{Activo: TRUE, Inactivo: FALSE} //CONTRUCTOR public function __construct() { $this->SetIdBaseDatos ( "" ); $this->SetServidor ( "172.51.1.18" ); //Produccion: metcam41.pdvsa.com Desarrollo: metltq82bdd.met.pdvsa.com if ($this->GetServidor () == "172.51.1.18") { $this->SetUsuario ( $_SESSION['stsLoginUsuario_sicobim'] ); $this->SetClave ( $_SESSION['stsClave_sicobim'] ); //echo($_SESSION['stsClave_sicobim']); //echo ($_SESSION['stsLoginUsuario_sicobim']); } $this->SetNomBaseDatos ( "sicobim" ); $this->SetEsquema ( "sch_sicobim" ); $this->SetEstatusBaseDatos ( "true" ); $this->Conexion(); } //FUNCIONES SETTERS Y GETTERS //Setter's public function SetIdBaseDatos($idBaseD) { $this->vIdBaseDatos = $idBaseD; } public function SetEsquema($esquema) { $this->vEsquema = $esquema; } public function SetServidor($server) { $this->vServidor = $server; } public function SetUsuario($user) { $this->vUsuario = $user; } public function SetClave($password) { $this->vClave = $password; } public function SetNomBaseDatos($dbname) { $this->vNomBaseDatos = $dbname; } public function SetDsn($dsn) { $this->vDsn = $dsn; } public function SetDB($bd) { $this->vDb = $bd; echo $db; } public function SetEstatusBaseDatos($statusBD) { $this->vEstatusBaseDatos = $statusBD; } //Getter's public function GetIdBaseDatos() { return $this->vIdBaseDatos; } public function GetServidor() { return $this->vServidor; } public function GetUsuario() { return $this->vUsuario; } public function GetClave() { return $this->vClave; } public function GetNomBaseDatos() { return $this->vNomBaseDatos; } public function GetDsn() { return $this->vDsn; } public function GetDB() { return $this->vDb; } public function GetEstatusBaseDatos() { return $this->vEstatusBaseDatos; } public function GetEsquema() { return $this->vEsquema; } //Conexion para la Base De Datos public function Conexion() { $usuario = $this->GetUsuario(); $clave = $this->GetClave(); $servidor = $this->GetServidor(); $nomBD = $this->GetNomBaseDatos(); $this->SetDsn ( "postgres8://$usuario:$clave@$servidor/$nomBD" );//postgres8!=mysql $this->SetDB ( NewADOConnection ( $this->GetDsn () ) ); if (! $this->GetDB ()) { $this->SetEstatusBaseDatos("FALSE"); //die ( "<b>ERROR FATAL:</b> FALLO LA CONEXION A LA BASE DE DATOS" ); } else { $this->SetEstatusBaseDatos("TRUE"); } $this->GetDB ()->debug = false; //True para ver las sentencias (SQL) del código mientras se ejecutan y FAlSE no las muestra $this->GetDB ()->port = 5432;//postgres5432 mysql 3366 return $this->GetDB (); } public function Desconexion() { if ($this->GetDB ()->IsConnected () == true) { $this->GetDB ()->Close (); } else { echo '<script> alert("ERROR: No se pudo cerrar la Conexion de la Base de Datos"); </script>'; } } /** * * Gestiona registros en la base de datos haciendo uso de Procediminetos Almacenados en PostgreSQL * @PARAM $SP -> Inidica el Stored Procedure (Procedimineto Almacenado) a utilizar * @PARAM $Destino -> Inidica el sitio (p�gina) a donde resulta ubicado el usuario luego de que se ejecuta la funcion * **/ ///EL RESULTADO LO EVALUA COMO UN BOOLEAN public function EjecutarProcedure($sp) { //echo ( "SELECT * FROM " .$this->GetEsquema().'.'.$sp ); //die(ss); $db = $this->Conexion (); //echo "SELECT * FROM $sp "; try { $db->StartTrans (); $resultado = $db->GetOne ( "SELECT * FROM " .$this->GetEsquema().'.'.$sp ); $db->CompleteTrans (); if ($db->HasFailedTrans ()) { $salida = "Fallo en la Transaccion " . $db->ErrorMsg (); } } catch ( Exception $db ) { $salida = "Fallo en la Transaccion " . $db->ErrorMsg (); } if ($resultado == false) { $salida = "Fallo en la Transaccion " . $db->ErrorMsg (); $salida = FALSE; } else { $salida = "Operacion ejecutada con Exito"; $salida = TRUE; //$this->Desconexion (); } return $salida; } /** * * Ejecuta una vista de PostgreSQL que devuelve los campos necesarios para mostrar por pantalla * @PARAM $VW -> Inidica la vista a invocar * @PARAM $CampoID -> Indica el campo por el que se quiere filtrar * @PARAM $ID -> Indica el valor por el que se esta filtrando * @RETURN $resultado -> Recordset de todo lo que coincide con la condicion anterior * **/ public function EjecutarQuery($vista) { //echo ("$vista"); $resultado = $this->GetDB ()->Execute ( $vista ); if ($resultado == false) { die ( "ERROR: Fallo de Ejecucion" . $this->GetDB ()->ErrorMsg () ); } return $resultado; //$this->Desconexion (); } /** * * Ejecuta una vista de PostgreSQL que devuelve los campos necesarios para mostrar por pantalla * @PARAM $VW -> Inidica la vista a invocar * @PARAM $CampoID -> Indica el campo por el que se quiere filtrar * @PARAM $ID -> Indica el valor por el que se esta filtrando * @RETURN $resultado -> Recordset de todo lo que coincide con la condicion anterior * **/ public function EjecutarVista($vista) { //echo "SELECT * FROM " .$this->GetEsquema().'.'.$vista . ";"; $resultado = $this->GetDB ()->Execute ( "SELECT * FROM " .$this->GetEsquema().'.'.$vista . ";" ); //echo "SELECT * FROM " .$this->GetEsquema().'.'.$vista . ";"; if ($resultado == false) { //die("SELECT * FROM $vista malo"); die ( "ERROR: Fallo de Ejecucion" . $this->GetDB ()->ErrorMsg () ); } return $resultado; //$this->Desconexion (); } public function EjecutarVistaXCampos($vista, $campos) { //echo "<script>alert(esta es la vista buena 22 : SELECT $campos FROM ".$vista.")</script>"; $resultado = $this->GetDB ()->Execute ( "SELECT $campos FROM " .$this->GetEsquema().'.'.$vista . ";" ); if ($resultado == false) { //echo "<script>alert(esta es la vista mala 22: SELECT * FROM ".$vista.")</script>"; die ( "ERROR: Fallo de Ejecucion" . $this->GetDB ()->ErrorMsg ()); } //$this->Desconexion (); return $resultado; } public function ListarVW($vista, $valor, $campo) { $db = $this->Conexion (); $resultado = $db->Execute ( "SELECT * FROM " .$this->GetEsquema().'.'.$vista ); if ($resultado->EOF) { echo "<option value='00'>No hay registros en el sistema</option>"; } else { while ( ! $resultado->EOF ) { echo "<option value='" . $resultado->fields [$valor] . "'>" . $resultado->fields [$campo] . "</option>"; $resultado->MoveNext (); } } //$this->Desconexion (); } /*public function ListarVWCamposVarios($vista, $campos, $valor, $descripcion) { $db = $this->Conexion (); //echo "SELECT $campos FROM ".$vista;die; $resultado = $db->Execute ( "SELECT $campos FROM " .$this->GetEsquema().'.'.$vista ); if ($resultado->EOF) { echo "<option value='00'>No hay registros en el sistema</option>"; } else { while ( ! $resultado->EOF ) { echo "<option value='" . $resultado->fields [$valor] . "'>" . $resultado->fields [$descripcion] . "</option>"; $resultado->MoveNext (); } } //$this->Desconexion (); }*/ public function ListarVWCamposVarios($vista, $campos, $valor, $descripcion,$valorSelected) { $db = $this->Conexion (); // $selec=0; //echo "SELECT $campos FROM ".$vista; $resultado = $db->Execute ( "SELECT $campos FROM " .$this->GetEsquema().'.'.$vista ); if ($resultado->EOF) { echo "<option value='00'>No hay registros en el sistema</option>"; } else { if($valorSelected=='') { echo "<option value='' selected=selected> Seleccione</option>"; } while ( ! $resultado->EOF ) { $selected=''; if ($valorSelected == $resultado->fields [$valor] ) $selected='selected'; echo "<option ".$selected." value='" . $resultado->fields [$valor] . "'>" . $resultado->fields [$descripcion] . "</option>"; $resultado->MoveNext (); } } //$this->Desconexion (); } public function ListarVWVarios($vista, $valor, $campo1, $campo2) { $db = $this->Conexion (); //echo "SELECT * FROM $vista"; die; $resultado = $db->Execute ( "SELECT * FROM " .$this->GetEsquema().'.'.$vista ); if ($resultado->EOF) { echo "<option value='00'>No hay registros en el sistema</option>"; } else { while ( ! $resultado->EOF ) { echo "<option value='" . $resultado->fields [$valor] . "'>" . $resultado->fields [$campo1] . " : " . $resultado->fields [$campo2] . "</option>"; $resultado->MoveNext (); } } //$this->Desconexion (); } /* ESTA FUNCION LISTA POR CAMPOS ESPECIFICOS DE UNA VISTA DE BASE DE DATOS, ADEMAS MUESTRA UNA UNICA DESCRIPCION ** Y EVALUA SI UNA OPCION DEL COMBO BOX FUE SELECCIONADA PARA MOSTRAR EL VALOR QUE EL USUARIO ESCOJIO ** POR EJEMPLO, ESTA FUNCION ES UTILIZADA EN LA CONSULTA DE MOVIMIENTO DE MEDIDORES */ /*public function ListarVWxCampos($vista, $campos, $valor, $descripcion, $comboAEvaluar) { $db = $this->Conexion (); //echo "SELECT $campos FROM ".$this->GetEsquema().'.'."$vista"; $selec=0; $resultado = $db->Execute ( "SELECT $campos FROM " . $vista ); if ($resultado->EOF) { echo "<option value='00'>No hay registros en el sistema</option>"; } else { while ( ! $resultado->EOF ) { if($selec==0) { echo "<option value='' selected=selected> Seleccione</option>"; $selec=1; } if ($comboAEvaluar == $resultado->fields [$valor]) { echo "<option value='" . $resultado->fields [$valor] . "' selected>" . $resultado->fields [$descripcion] . "</option>"; } else { echo "<option value='" . $resultado->fields [$valor] . "'>" . $resultado->fields [$descripcion] . "</option>"; } $resultado->MoveNext (); } } $this->Desconexion (); } */ public function ListarVWxCampos($vista, $campos, $valor, $descripcion, $comboAEvaluar) { $db = $this->Conexion (); //echo "SELECT $campos FROM ".$this->GetEsquema().'.'."$vista"; $selec=0; $resultado = $db->Execute ( "SELECT $campos FROM " . $vista ); if ($resultado->EOF) { echo "<option value='00'>No hay registros en el sistema</option>"; } else { while ( ! $resultado->EOF ) { if($selec==0) { echo "<option value='' selected=selected> Seleccione</option>"; $selec=1; } if ($comboAEvaluar == $resultado->fields [$valor]) { echo "<option value='" . $resultado->fields [$valor] . "' selected>" . $resultado->fields [$descripcion] . "</option>"; } else { echo "<option value='" . $resultado->fields [$valor] . "'>" . $resultado->fields [$descripcion] . "</option>"; } $resultado->MoveNext (); } } $this->Desconexion (); } public function ListarVWxId($vista, $campos, $valor, $descripcion, $comoAEvaluar) { $db = $this->Conexion (); $resultado = $db->Execute ( "SELECT $campos FROM ".$this->GetEsquema().'.'."$vista" ); // echo "SELECT $campos FROM $vista"; die; if ($resultado->EOF) { echo "<option value='00'>No hay registros en el sistema</option>"; } else { while ( ! $resultado->EOF ) { if ($comoAEvaluar == $resultado->fields [$valor]) { echo "<option value='" . $resultado->fields [$valor] . "' selected='Selected'>" . $resultado->fields [$descripcion] . "</option>"; $idValor = $resultado->fields [$valor]; } else { echo "<option value='" . $resultado->fields [$valor] . "'>" . $resultado->fields [$descripcion] . "</option>"; } $resultado->MoveNext (); } } //$this->Desconexion (); return $idValor; } public function ListarVWSelectedMultiples($listado, $valor, $campo, $selecciones) { $db = $this->Conexion (); $aux = ""; $i = 1; $resultado = $db->Execute ( "SELECT * FROM " .$this->GetEsquema().'.'.$listado ); $row = $selecciones->RecordCount (); if ($resultado->EOF) { echo "<option value='0'>No hay registros en el sistema</option>"; } else { while ( ! $resultado->EOF ) { $aux = "<option value='" . $resultado->fields [$valor] . "' "; $j = 0; while ( $j < $row ) { if ($resultado->fields [$valor] == $selecciones->fields [$j]) { $aux .= " selected='selected'"; $selecciones->MoveNext (); } $j ++; } $aux .= ">" . $resultado->fields [$campo] . "</option>"; echo $aux; $resultado->MoveNext (); } } //$this->Desconexion (); } } ?>
true
06445c3f5c36f7baed400005aa11f60ae3cd918a
PHP
rahat-hossain/Basic-PHP-Code
/twoDarray.php
UTF-8
850
3.375
3
[]
no_license
<?php // $arr_new = array( // array(25,45,"rahat"), // array(4,3), // array(96,105), // ); // foreach($arr_new as $index_a => $a) // { // foreach($a as $index_b =>$b) // { // echo "[" . $index_a . "]" . "[" . $index_b . "]" . " => " . $b . "<br>"; // } // } // $arr_new = array( // array(25,45,"rahat"), // array(4,3), // array(96,105), // ); // foreach ($arr_new as $key => $value) { // echo "<pre>"; // print_r($arr_new); // } $main_array = array( array(20, 50, "rahat"), 100, array(150, 30, "x"), array(650, 500, "rip"), 66 ); foreach ($main_array as $value) { if (is_array($value)) { foreach ($value as $value_1) { echo $value_1. "<br>"; } } else { echo $value."<br>"; } } ?>
true
f464c133a00759654ff90c9f6a3e07e3e5ed793c
PHP
laraflow/admin-module
/Services/Auth/RegisteredUserService.php
UTF-8
3,983
2.5625
3
[ "MIT" ]
permissive
<?php namespace Modules\Admin\Services\Auth; use Exception; use Illuminate\Auth\Events\Registered; use Illuminate\Support\Facades\Auth; use Modules\Admin\Models\User; use Modules\Admin\Repositories\Eloquent\Rbac\UserRepository; use Modules\Admin\Services\Common\FileUploadService; use Modules\Admin\Supports\Constant; use Modules\Admin\Supports\DefaultValue; use Modules\Admin\Supports\Utility; use Spatie\MediaLibrary\MediaCollections\Exceptions\FileDoesNotExist; use Spatie\MediaLibrary\MediaCollections\Exceptions\FileIsTooBig; class RegisteredUserService { /** * @var UserRepository */ public $userRepository; /** * @var FileUploadService */ public $fileUploadService; /** * RegisteredUserService constructor. * @param UserRepository $userRepository * @param FileUploadService $fileUploadService */ public function __construct(UserRepository $userRepository, FileUploadService $fileUploadService) { $this->userRepository = $userRepository; $this->fileUploadService = $fileUploadService; } /** * @param array $registerFormInputs * @return array * @throws Exception */ public function attemptRegistration(array $registerFormInputs): ?array { \DB::beginTransaction(); //format request object $inputs = $this->formatRegistrationInfo($registerFormInputs); try { //create new user $newUser = $this->userRepository->create($inputs); if ($newUser instanceof User) { if ($this->attachAvatarImage($newUser) && $this->attachDefaultRoles($newUser)) { \DB::commit(); $newUser->refresh(); Auth::login($newUser); return ['status' => true, 'message' => __('auth.register.success'), 'level' => Constant::MSG_TOASTR_SUCCESS, 'title' => 'Authentication']; } else { return ['status' => false, 'message' => __('auth.register.failed'), 'level' => Constant::MSG_TOASTR_WARNING, 'title' => 'Alert!']; } } else { return ['status' => false, 'message' => 'User model creation failed', 'level' => Constant::MSG_TOASTR_ERROR, 'title' => 'Error!']; } } catch (\Exception $exception) { $this->userRepository->handleException($exception); return ['status' => false, 'message' => __($exception->getMessage()), 'level' => Constant::MSG_TOASTR_ERROR, 'title' => 'Error!']; } } /** * @param array $request * @return array * @throws Exception */ private function formatRegistrationInfo(array $request): array { //Hash password return [ 'name' => $request['name'], 'password' => Utility::hashPassword(($request['password'] ?? DefaultValue::PASSWORD)), 'username' => ($request['username'] ?? Utility::generateUsername($request['name'])), 'mobile' => ($request['mobile'] ?? null), 'email' => ($request['email'] ?? null), 'remarks' => 'self-registered', 'enabled' => DefaultValue::ENABLED_OPTION ]; } /** * @param User $user * @return bool * @throws FileDoesNotExist * @throws FileIsTooBig * @throws Exception */ protected function attachAvatarImage(User $user): bool { //add profile image $profileImagePath = $this->fileUploadService->createAvatarImageFromText($user->name); $user->addMedia($profileImagePath)->toMediaCollection('avatars'); return $user->save(); } /** * @param User $user * @return bool */ protected function attachDefaultRoles(User $user): bool { $this->userRepository->setModel($user); return $this->userRepository->manageRoles([DefaultValue::GUEST_ROLE_ID]); } }
true
918128e4cc500521b1db5f38ec176aaa07e35ba2
PHP
techart/tao3
/src/TAO/Fields/Type/HugeMultilink.php
UTF-8
1,730
2.734375
3
[]
no_license
<?php namespace TAO\Fields\Type; class HugeMultilink extends Multilink { protected $datatype = null; public function datatype() { if (is_null($this->datatype)) { if ($code = $this->param('datatype')) { $this->datatype = dt($code); } } return $this->datatype; } protected function getValueFromRequest($request) { $ids = []; foreach (explode('|', $request->input($this->name, '')) as $id) { if ($m = \TAO::regexp('{^\d+$}', trim($id))) { $ids[] = (int)$id; } } return $ids; } public function searchPlaceholder() { return $this->param('search_placeholder', 'Поиск'); } public function apiActionSearch() { $items = []; if ($q = trim(request()->get('q', false))) { $items = $this->searchItems($q); } return ['items' => $items]; } public function apiActionAdditem() { if ($q = trim(request()->get('q', false))) { if ($datatype = $this->datatype()) { try { $add = $this->param('with_add', false); if ($add == '1' || $add == 'true' || $add == 'yes' || $add === true) { $item = $datatype->addByTitle($q); } else { $item = $datatype->loadByTitle($q); } if (!$item) { return "notfound"; } return [ 'id' => $item->id, 'title' => $item->title(), ]; } catch (\Exception $e) { return $e->getMessage(); } } } } public function searchItems($q) { if ($cb = $this->param('search_items')) { if (\TAO\Type::isCallable($cb)) { return \TAO\Callback::instance($cb)->args([$q])->call($this); } } if ($datatype = $this->datatype()) { $rows = []; if (method_exists($datatype, 'quickSearch')) { return $datatype->quickSearch($q); } } return []; } }
true
1d9dd0a6e20bfe4c55b54b4494f0bcfb8c7b97a7
PHP
alexnord/swell
/app/Http/Controllers/Admin/LocationCrudController.php
UTF-8
5,214
2.515625
3
[]
no_license
<?php namespace App\Http\Controllers\Admin; use Backpack\CRUD\app\Http\Controllers\CrudController; // VALIDATION: change the requests to match your own file names if you need form validation use App\Http\Requests\LocationRequest as StoreRequest; use App\Http\Requests\LocationRequest as UpdateRequest; /** * Class LocationCrudController * @package App\Http\Controllers\Admin * @property-read CrudPanel $crud */ class LocationCrudController extends CrudController { public function setup() { /* |-------------------------------------------------------------------------- | CrudPanel Basic Information |-------------------------------------------------------------------------- */ $this->crud->setModel('App\Models\Location'); $this->crud->setRoute(config('backpack.base.route_prefix') . '/location'); $this->crud->setEntityNameStrings('location', 'locations'); /* |-------------------------------------------------------------------------- | CrudPanel Configuration |-------------------------------------------------------------------------- */ // Columns $this->crud->addColumn(['name' => 'active', 'type' => 'boolean', 'label' => 'Active']); $this->crud->addColumn(['name' => 'title', 'type' => 'text', 'label' => 'Name']); $this->crud->addColumn([ 'type' => 'select', 'label' => 'NOAA Station', // Table column heading 'name' => 'noaa_station_id', // the column that contains the ID of that connected entity; 'entity' => 'station', // the method that defines the relationship in your Model 'attribute' => 'title', // foreign key attribute that is shown to user 'model' => 'App\Models\NoaaStation', // foreign key model ]); $this->crud->addColumn([ 'type' => 'select', 'label' => 'Buoy', // Table column heading 'name' => 'buoy_id', // the column that contains the ID of that connected entity; 'entity' => 'buoy', // the method that defines the relationship in your Model 'attribute' => 'title', // foreign key attribute that is shown to user 'model' => 'App\Models\Buoy', // foreign key model ]); // Fields $this->crud->addField(['name' => 'active', 'type' => 'checkbox', 'label' => 'Active']); $this->crud->addField(['name' => 'title', 'type' => 'text', 'label' => 'Name']); $this->crud->addField(['name' => 'slug', 'type' => 'text', 'label' => 'Slug']); $this->crud->addField(['name' => 'lat', 'type' => 'number', 'label' => 'Latitude', 'attributes' => ["step" => "any"]]); $this->crud->addField(['name' => 'lng', 'type' => 'number', 'label' => 'Longitude', 'attributes' => ["step" => "any"]]); $this->crud->addField(['name' => 'timezone', 'type' => 'text', 'label' => 'Timezone']); $this->crud->addField([ 'label' => 'NOAA Station', 'type' => 'select', 'name' => 'noaa_station_id', // the db column for the foreign key 'entity' => 'station', // the method that defines the relationship in your Model 'attribute' => 'title', // foreign key attribute that is shown to user 'model' => 'App\Models\NoaaStation', // optional 'options' => (function ($query) { return $query->orderBy('title', 'ASC')->get(); }), // force the related options to be a custom query, instead of all(); you can use this to filter the results show in the select ]); $this->crud->addField([ 'label' => 'Buoy', 'type' => 'select', 'name' => 'buoy_id', // the db column for the foreign key 'entity' => 'buoy', // the method that defines the relationship in your Model 'attribute' => 'title', // foreign key attribute that is shown to user 'model' => 'App\Models\Buoy', // optional 'options' => (function ($query) { return $query->orderBy('title', 'ASC')->get(); }), // force the related options to be a custom query, instead of all(); you can use this to filter the results show in the select ]); // add asterisk for fields that are required in LocationRequest $this->crud->setRequiredFields(StoreRequest::class, 'create'); $this->crud->setRequiredFields(UpdateRequest::class, 'edit'); } public function store(StoreRequest $request) { // your additional operations before save here $redirect_location = parent::storeCrud($request); // your additional operations after save here // use $this->data['entry'] or $this->crud->entry return $redirect_location; } public function update(UpdateRequest $request) { // your additional operations before save here $redirect_location = parent::updateCrud($request); // your additional operations after save here // use $this->data['entry'] or $this->crud->entry return $redirect_location; } }
true
e4c0de56bbd8fbde3cf4aa383d49fbe54be69767
PHP
ekkinox/kata-books
/features/bootstrap/CatalogContext.php
UTF-8
2,104
2.765625
3
[ "MIT" ]
permissive
<?php use Behat\Behat\Tester\Exception\PendingException; use Behat\Behat\Context\Context; use Ekkinox\KataBooks\Model\Book; use Ekkinox\KataBooks\Model\Catalog; /** * Defines application features from the specific context. */ class CatalogContext implements Context { /** * @var Book */ private $catalog; /** * Initializes context. * * Every scenario gets its own context instance. * You can also pass arbitrary arguments to the * context constructor through behat.yml. */ public function __construct() { $this->catalog = new Catalog(); } /** * @Given there is no product in the catalog */ public function thereIsNoProductInTheCatalog() { PHPUnit_Framework_Assert::assertCount( 0, $this->catalog->getProducts() ); } /** * @When I add a product named :name that costs :price */ public function iAddANamedProductWithACost($name, $price) { $this->catalog->addProduct( (new Book())->setName($name)->setPrice($price) ); } /** * @Then the catalog should contain :productCount products */ public function theCatalogShouldContainProducts($productCount) { PHPUnit_Framework_Assert::assertCount( intval($productCount), $this->catalog->getProducts() ); } /** * @Given there is already a product in the catalog named :name that costs :price */ public function thereIsANamedProductInTheCatalogWithACosts($name, $price) { $this->iAddANamedProductWithACost($name, $price); } /** * @When I remove the product named :arg1 from the catalog */ public function iRemoveTheProductNamedFromTheCatalog($name) { $this->catalog->removeProduct($name); } /** * @Then the catalog should contain a product named :name */ public function theCatalogShouldContainAProductNamed($name) { PHPUnit_Framework_Assert::assertNotNull($this->catalog->getProduct($name)); } }
true
acb583128af9662f8ee795bd22b7f0be072416fe
PHP
dshum/old.yellow
/lemon-tree/admin/src/lib/properties/DatetimeProperty.php
UTF-8
2,665
2.78125
3
[ "MIT" ]
permissive
<?php namespace LemonTree\Properties; use Carbon\Carbon; use LemonTree\ElementInterface; class DatetimeProperty extends BaseProperty { protected static $format = 'Y-m-d H:i:s'; protected $fillNow = false; public function __construct($name) { parent::__construct($name); $this-> addRule('date_format:"'.static::$format.'"', 'Недопустимый формат даты'); return $this; } public static function create($name) { return new self($name); } public function setFillNow($fillNow) { $this->fillNow = $fillNow; return $this; } public function getFillNow() { return $this->fillNow; } public function setElement(ElementInterface $element) { parent::setElement($element); if (is_string($this->value)) { try { $this->value = Carbon::createFromFormat($this->format, $this->value); } catch (\Exception $e) {} } if ( ! $this->value && $this->getFillNow()) { $this->value = Carbon::now(); } if ($this->value) { $this->value = [ 'value' => $this->value->format(static::$format), 'date' => $this->value->toDateString(), 'time' => $this->value->toTimeString(), 'hour' => $this->value->hour, 'minute' => $this->value->minute, 'second' => $this->value->second, 'human' => $this->value->format('d.m.Y, H:i:s') ]; } return $this; } public function searchQuery($query) { $name = $this->getName(); $from = \Input::get($name.'_from'); $to = \Input::get($name.'_to'); if ($from) { try { $from = Carbon::createFromFormat('Y-m-d', $from); $query->where($name, '>=', $from->format('Y-m-d')); } catch (\Exception $e) {} } if ($to) { try { $to = Carbon::createFromFormat('Y-m-d', $to); $query->where($name, '<=', $to->format('Y-m-d')); } catch (\Exception $e) {} } return $query; } public function searching() { $name = $this->getName(); $from = \Input::get($name.'_from'); $to = \Input::get($name.'_to'); return $from || $to ? true : false; } public function getElementSearchView() { $name = $this->getName(); $from = \Input::get($name.'_from'); $to = \Input::get($name.'_to'); try { $from = Carbon::createFromFormat('Y-m-d', $from); } catch (\Exception $e) { $from = null; } try { $to = Carbon::createFromFormat('Y-m-d', $to); } catch (\Exception $e) { $to = null; } $scope = array( 'name' => $this->getName(), 'title' => $this->getTitle(), 'from' => $from, 'to' => $to, ); try { $view = $this->getClassName().'.elementSearch'; return \View::make('admin::properties.'.$view, $scope); } catch (\Exception $e) {} return null; } }
true
9d9fa8c6d9b34c812d691a72b7f943003fbd6042
PHP
rmsaitam/TCC
/api/module/FastFood/Model/ClienteModel.php
UTF-8
2,159
2.890625
3
[]
no_license
<?php namespace FastFood\Model; use Szy\Mvc\Model\AbstractModel; use Szy\Mvc\Model\ModelException; class ClienteModel extends AbstractModel { public function cliente($codigo) { if (empty($codigo)) throw new ModelException('Codigo deve ter um valor inteiro'); $stmt = $this->query("SELECT * FROM cliente WHERE codigo = ?", array($codigo)); $row = $stmt->fetchObject(); unset($row->senha); return $row; } public function cidade($codigo) { if (empty($codigo)) throw new ModelException('Codigo deve ter um valor inteiro'); $stmt = $this->query("SELECT * FROM cidade WHERE codigo = ?", array($codigo)); return $stmt->fetchObject(); } public function contatos($cliente) { if (empty($cliente)) throw new ModelException('Cliente deve ter um valor'); $stmt = $this->query("SELECT * FROM contato WHERE cliente = ?", array($cliente->codigo)); $res = new \ArrayIterator(); while ($row = $stmt->fetchObject()) $res->append($row); return $res->getArrayCopy(); } public function endereco($cliente, $codigoEndereco) { $stmt = $this->query("SELECT * FROM endereco WHERE codigo = ? AND cliente = ?", array($cliente->codigo, $codigoEndereco)); return $stmt->fetchObject(); } public function enderecos($cliente) { if (empty($cliente)) throw new ModelException('Cliente deve ter um valor'); $stmt = $this->query("SELECT * FROM endereco WHERE cliente = ?", array($cliente->codigo)); $res = new \ArrayIterator(); while ($row = $stmt->fetchObject()) { $row->cidade = $this->cidade($row->cidade); $res->append($row); } return $res->getArrayCopy(); } public function verificar($email, $senha) { $stmt = $this->query("SELECT * FROM cliente WHERE email = ? AND senha = ?", array($email, $senha)); if ($stmt->rowCount() < 1) throw new ModelException('E-mail ou senha inválida'); return $stmt->fetchObject(); } }
true
f51f9cde37dcbf2aa0adbe332ec807f2be60d473
PHP
yrizos/data-entity
/tests/src/TypeTest.php
UTF-8
6,204
2.71875
3
[ "MIT" ]
permissive
<?php namespace DataEntityTest; use DataEntity\Type; class TypeTest extends \PHPUnit_Framework_TestCase { public function testRaw() { $type = Type::factory('raw'); $this->assertInstanceOf("DataEntity\\Type\\RawType", $type); $data = [ 1, true, false, 'hello world', $type ]; foreach ($data as $value) { $this->assertTrue($type->validate($value)); $this->assertSame($value, $type->filter($value)); } } public function testString() { $type = Type::factory('string'); $this->assertInstanceOf("DataEntity\\Type\\StringType", $type); $this->assertTrue($type->validate('hello world')); $this->assertFalse($type->validate('')); $this->assertFalse($type->validate(true)); $this->assertFalse($type->validate(false)); $this->assertFalse($type->validate(null)); } public function testInteger() { $type = Type::factory('integer'); $this->assertInstanceOf("DataEntity\\Type\\IntegerType", $type); $this->assertTrue($type->validate(1)); $this->assertTrue($type->validate('-1')); $this->assertFalse($type->validate('hello world')); $this->assertFalse($type->validate(true)); $this->assertFalse($type->validate(false)); $this->assertFalse($type->validate(null)); $this->assertSame(-1, $type->filter('-1')); $this->assertSame(2, $type->filter('2')); } public function testBoolean() { $type = Type::factory('bool'); $this->assertInstanceOf("DataEntity\\Type\\BooleanType", $type); $this->assertTrue($type->validate(true)); $this->assertTrue($type->validate(false)); $this->assertTrue($type->validate('true')); $this->assertTrue($type->validate('false')); $this->assertTrue($type->validate(1)); $this->assertTrue($type->validate(0)); $this->assertFalse($type->validate(null)); $this->assertFalse($type->validate('hello word')); $this->assertSame(true, $type->filter('true')); $this->assertSame(false, $type->filter('false')); $this->assertSame(true, $type->filter(1)); $this->assertSame(false, $type->filter(0)); } public function testArray() { $type = Type::factory('array'); $this->assertInstanceOf("DataEntity\\Type\\ArrayType", $type); $this->assertTrue($type->validate([])); $this->assertTrue($type->validate([1, 2, 3])); $this->assertFalse($type->validate(null)); $this->assertFalse($type->validate('hello word')); $this->assertSame([], $type->filter([])); $this->assertSame([1, 2, 3], $type->filter([1, 2, 3])); } public function testSerialized() { $type = Type::factory('serialized'); $this->assertInstanceOf("DataEntity\\Type\\SerializedType", $type); $data = [ 1, true, false, 'hello world', $type ]; foreach ($data as $value) { $serialized = serialize($value); $this->assertTrue($type->validate($value)); $this->assertSame($serialized, $type->filter($value)); } } public function testEmail() { $type = Type::factory('email'); $this->assertInstanceOf("DataEntity\\Type\\EmailType", $type); $this->assertTrue($type->validate('[email protected]')); $this->assertFalse($type->validate('hello world')); $this->assertSame('[email protected]', $type->filter('[email protected]')); $this->assertFalse($type->filter('hello world')); } public function testDate() { $type = Type::factory('DateTime'); $this->assertInstanceOf("DataEntity\\Type\\DateType", $type); $time = time(); $string = date('Y-m-d'); $datetime = new \DateTime(); $this->assertTrue($type->validate($time)); $this->assertTrue($type->validate($string)); $this->assertTrue($type->validate($datetime)); $this->assertInstanceOf('DateTime', $type->filter($time)); $this->assertInstanceOf('DateTime', $type->filter($string)); $this->assertInstanceOf('DateTime', $type->filter($datetime)); } public function testAlnum() { $type = Type::factory('Alphanumeric'); $this->assertInstanceOf("DataEntity\\Type\\AlnumType", $type); $this->assertTrue($type->validate(1234)); $this->assertTrue($type->validate('abc')); $this->assertTrue($type->validate('abc1234')); $this->assertInternalType('string', $type->filter(1234)); } public function testFloat() { $type = Type::factory('float'); $this->assertInstanceOf("DataEntity\\Type\\FloatType", $type); $this->assertTrue($type->validate(3)); $this->assertTrue($type->validate(3.14)); $this->assertTrue($type->validate('3.14')); $this->assertInternalType('float', $type->filter(3)); $this->assertInternalType('float', $type->filter('3.14')); } public function testIp() { $type = Type::factory('ip'); $this->assertInstanceOf("DataEntity\\Type\\IpType", $type); $this->assertTrue($type->validate('127.0.0.1')); $this->assertFalse($type->validate('Hello World')); } public function testUrl() { $type = Type::factory('url'); $this->assertInstanceOf("DataEntity\\Type\\UrlType", $type); $this->assertTrue($type->validate('www.example.com')); $this->assertTrue($type->validate('example.com')); $this->assertTrue($type->validate('http://www.example.com')); $this->assertTrue($type->validate('https://www.example.com')); $this->assertTrue($type->validate('http://example.com')); $this->assertTrue($type->validate('https://example.com')); $this->assertFalse($type->validate('Hello World')); $this->assertFalse($type->validate('.example.com')); $this->assertFalse($type->validate('http:/www.example.com')); } }
true
219494d0d7db7464ddd2295599c51824b1630328
PHP
yadson18/SRI-Files
/src/Controller/AppController.php
UTF-8
1,455
2.609375
3
[]
no_license
<?php namespace App\Controller; use Simple\Controller\Controller; use Simple\Http\Request; use Simple\View\View; use Simple\Configurator\Configurator; abstract class AppController extends Controller { /** * initialize Method. * * @param * Simple\Http\Request $request - server request. * Simple\View\View $view - current view controller. * @return * null */ public function initialize(Request $request, View $view) { parent::initialize($request, $view); $this->loadComponent('Ajax'); $this->loadComponent('Flash'); $this->loadComponent('Paginator'); $this->loadComponent('Auth'); } /** * alowedMethods Method. * * @param * string $method - method name to check access authorization. * array $methods - methods with authorized access. * @return * boolean */ public function allow(array $methods) { $view = $this->request->getHeader()->view; if (in_array($view, $methods)) { return true; } else if (is_callable([$this->Auth, 'getUser']) && !empty(call_user_func([$this->Auth, 'getUser'])) && is_callable([$this->Auth, 'checkAuthorization']) && call_user_func_array([$this->Auth, 'checkAuthorization'], [$view]) ) { return true; } return false; } public abstract function beforeFilter(); }
true
328f7b06cf3ef11da42bc7ed64bfbbea1deb2a6d
PHP
M-Leggat/Magento2-Gigya-Extension
/Observer/Session/Extend.php
UTF-8
823
2.53125
3
[]
no_license
<?php namespace Gigya\GigyaIM\Observer\Session; use Gigya\GigyaIM\Model\Session\Extend as ExtendModel; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; class Extend implements ObserverInterface { /** * @var ExtendModel */ protected $sessionExtendModel; public function __construct( ExtendModel $sessionExtendModel ) { $this->sessionExtendModel = $sessionExtendModel; } /** * @param Observer $observer * @return void */ public function execute(Observer $observer) { /* @var $request \Magento\Framework\App\RequestInterface */ $request = $observer->getEvent()->getRequest(); if($request->isAjax()) { $this->sessionExtendModel->extendSession(); } } }
true
4e693b4ef811190df3f7cdd46399128487cd66b8
PHP
crafter88/docpro_v2_system
/application/models/Banks_Model.php
UTF-8
2,097
2.515625
3
[]
no_license
<?php class Banks_Model extends CI_Model{ private static $db; function __construct() { parent::__construct(); self::$db = get_instance()->db; } public static function bank_count(){ return count(self::$db->get_where('banks', ['b_company' => 'docpro', 'flag' => '1'])->result()); } public static function get(){ return self::$db->get_where('banks', ['flag' => '1', 'b_company' => 'docpro'])->result(); } public static function add($data){ $last_record_seq = self::$db->query("SELECT * FROM banks WHERE b_company='docpro' ORDER BY CAST(b_seq AS DECIMAL) DESC LIMIT 1")->result(); $last_record_code = self::$db->query("SELECT * FROM banks WHERE b_company='docpro' ORDER BY CAST(b_code AS DECIMAL) DESC LIMIT 1")->result(); $seq = count($last_record_seq) > 0 ? (floatval($last_record_seq[0]->b_seq) + 1).'' : '1'; $code = count($last_record_code) > 0 ? (floatval($last_record_code[0]->b_code) + 1).'' : '1'; $data['b_seq'] = $seq; $data['b_code'] = $code; self::$db->insert('banks', $data); } public static function edit($data, $id){ self::$db->query("UPDATE banks b SET b.b_code='' WHERE b_id IN (SELECT b_id FROM(SELECT b.b_id FROM banks b WHERE b.b_company='docpro' AND b.b_code='".$data['b_code']."') t) AND b.flag='1'"); self::$db->where('b_id', $id)->update('banks', $data); } public static function update($data, $id){ self::$db->query("UPDATE banks b SET b.b_code='' WHERE b_id IN (SELECT b_id FROM(SELECT b.b_id FROM banks b WHERE b.b_company='docpro' AND b.b_code='".$data['b_code']."' AND b.b_id != '".$id."') t) AND b.flag='1'"); self::$db->where('b_id', $id)->update('banks', ['flag' => '0']); $last_record_seq = self::$db->query("SELECT * FROM banks WHERE b_company='docpro' ORDER BY CAST(b_seq AS DECIMAL) DESC LIMIT 1")->result(); $seq = count($last_record_seq) > 0 ? (floatval($last_record_seq[0]->b_seq) + 1).'' : '1'; $data['b_seq'] = $seq; self::$db->insert('banks', $data); } }
true
4d9a16c144c1b70fcaaba278dcd2185c8912e5f1
PHP
mupimenov/wibi
/core/manager.php
UTF-8
2,939
2.515625
3
[]
no_license
<?php /* * manager.php * * Copyright 2010 Mikhail Pimenov <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ class Manager { protected static $actions = array(); protected static $interrupt = null; public static function set_interrupt($int) { self::$interrupt = $int; } public static function add_action($a) { self::$actions[] = $a; } public static function manage() { $a = null; // отобрать валидный экшн for ($i=0; $i<count(self::$actions); $i++) { self::$actions[$i]->check(); if (!self::$actions[$i]->is_failed()) { $a = self::$actions[$i]; break; } } // проверка: есть ли action $f = "do_it"; if ($a == null) { $a = new PageAction(); $f = "do_default"; } // здесь обрабатываются основные действия $b = new Box(array($a, $f)); $content = $b->render_to_variable(); // если выполенение прервано if (!is_null(self::$interrupt)) { call_user_func(self::$interrupt); return; } // вывод предложения залогиниться $b = new Box(array("UserAction", "render_user_state")); $user = $b->render_to_variable(); // наполнение сайдбара $b = new Box( array("RssAction", "render_available_rss_feeds"), array("PageAction", "render_locked_pages"), array("PageAction", "render_recent_pages"), array("TagAction", "render_all_tags"), array("BlockAction", "render_all_blocks")); $sidebar = $b->render_to_variable(); // вывод лога $b = new Box(array("Logger", "render_log")); $log = $b->render_to_variable(); // собственно шаблон header("Content-Type: text/html; charset=UTF-8"); include "entity/tpl/layout.tpl"; } } ?>
true
33fd76d5f36596c86671f700e2900ae5a86150ea
PHP
ProfeC/galleries.profec.net
/views/list.php
UTF-8
1,191
2.78125
3
[ "MIT" ]
permissive
<?php foreach($galleryArray as $gallery){ echo "\t<section id=\"" . $gallery . "\" class=\"galleryList row\">\n\t\t<div class=\"small-12 columns\"><header><h3 class=\"subheader\">" . $gallery . "</h3></header> \n"; echo "\t\t\t<ul class=\"small-block-grid-3\">"; // Get the list of albums in each gallery found $dirArray = $this->model->getAlbumList($gallery); foreach($dirArray as $directory){ $imageThumbnail = $this->image->getThumbnail(GALLERY_ROOT . $gallery ."/" . $directory, 0, $galleryListImageWidth, $galleryListImageHeight); $imageLink = "index.php?g=" . base64_encode($gallery ."/" . $directory) . "&t=" . base64_encode($directory); // this should be from the gallery model, not model model. // $galleryDescription = $this->model->getDescription(GALLERY_ROOT . $gallery ."/" . $directory); echo "<li><div class=\"panel radius text-center\"><a href=\"" . $imageLink . "\" class=\"th\"><img src=\"" . $imageThumbnail . "\" alt=\"\" class=\"text-center\" /></a><h5 class=\"subheader\"><a href=\"" . $imageLink . "\">$directory</a></h5>" /*. $galleryDescription*/ . "</div></li>\n"; }; echo "\t\t</ul></section>\n\t"; } ?>
true
0414a509787bb3216535c5ec1defbb8fc2a44ac6
PHP
lalalili/vote
/database/seeds/TitleTableSeeder.php
UTF-8
1,137
2.53125
3
[]
no_license
<?php use Illuminate\Database\Seeder; use App\Models\Title; class TitleTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('titles')->truncate(); $titles = [ [ 'name' => '銷售經理', ], [ 'name' => '銷售副理' ], [ 'name' => '銷售顧問' ], [ 'name' => '銷售主任' ], [ 'name' => '服務廠長' ], [ 'name' => '行政組長' ], [ 'name' => '服務專員' ], [ 'name' => '行政專員' ], [ 'name' => '零件專員' ], [ 'name' => '引擎組長' ], [ 'name' => '技師' ] ]; foreach ($titles as $title) { Title::create($title); } } }
true
33ac79d205e959714d1643af836b1371e51a77b8
PHP
ZachWatkins/agrilife-learn-epubs
/src/class-customfields.php
UTF-8
709
2.5625
3
[]
no_license
<?php /** * The file that loads and handles custom fields * * @link https://github.com/AgriLife/agrilife-learn-epubs/blob/master/src/class-customfields.php * @since 1.0.0 * @package agrilife-learn-epubs * @subpackage agrilife-learn-epubs/src */ namespace Agrilife_Learn_Epubs; /** * The custom fields class * * @since 1.0.0 * @return void */ class CustomFields { /** * Initialize the class * * @since 1.0.0 * @return void */ public function __construct() { // Add page template custom fields. if ( class_exists( 'acf' ) ) { require_once ALEPB_DIR_PATH . 'fields/publication-fields.php'; require_once ALEPB_DIR_PATH . 'fields/author-fields.php'; } } }
true
7ba1a887726a0f4e47492ebb3d1cbbb308dbcd90
PHP
NguyenHaiHa1992/sangovietphat
/protected/modules/dev/DevModule.php
UTF-8
1,960
2.640625
3
[]
no_license
<?php class DevModule extends CWebModule { public $password; public $ipFilters; public function init() { // this method is called when the module is being created // you may place code here to customize the module or the application Yii::app()->setComponents(array( 'user'=>array( 'class'=>'CWebUser', 'stateKeyPrefix'=>'dev', 'loginUrl'=>Yii::app()->createUrl($this->getId().'/default/login'), ), ), false); // import the module-level models and components $this->setImport(array( 'dev.models.*', 'dev.components.*', )); //Configure layout path of module screen Yii::app()->theme='dev'; $this->viewPath = Yii::app ()->theme->basePath.'/views'; //Disable load jquery.js Yii::app()->clientScript->scriptMap['jquery.js'] = false; } public function beforeControllerAction($controller, $action) { if(parent::beforeControllerAction($controller, $action)) { // this method is called before any module controller action is performed // you may place customized code here $route=$controller->id.'/'.$action->id; if(!$this->allowIp(Yii::app()->request->userHostAddress) && $route!=='default/error') throw new CHttpException(403,"You are not allowed to access this page."); $publicPages=array( 'default/login', 'default/error', ); if($this->password!==false && Yii::app()->user->isGuest && !in_array($route,$publicPages)) Yii::app()->user->loginRequired(); else return true; } else return false; } /** * Checks to see if the user IP is allowed by {@link ipFilters}. * @param string $ip the user IP * @return boolean whether the user IP is allowed by {@link ipFilters}. */ protected function allowIp($ip) { if(empty($this->ipFilters)) return true; foreach($this->ipFilters as $filter) { if($filter==='*' || $filter===$ip || (($pos=strpos($filter,'*'))!==false && !strncmp($ip,$filter,$pos))) return true; } return false; } }
true
4eb1a5fedb1cee1113ff2b0a0f639c4319f43597
PHP
tommy-urban-media/lachvegas
/wp-content/themes/lachvegas.de/template-import-news.php
UTF-8
3,678
2.71875
3
[]
no_license
<?php /** * Template Name: Import News */ get_header(); function isLocal() { return in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')); } function splitLine($str, $delimiter = ';') { return explode($delimiter, $str); } function savePost($arr) { return wp_insert_post($arr); } $filepath = dirname(__FILE__) . '/_KURZMELDUNGEN_CSV.csv'; $file = fopen($filepath, 'r'); $data = array(); $postIDs = array(); while (($line = fgetcsv($file)) !== FALSE) { if (is_array($line) && count($line) === 1) { if (strlen($line[0]) >= 10) { $data[] = $line[0]; } } } fclose($file); $newsArgs = array( 'post_status' => 'any', 'post_type' => 'news', 'posts_per_page' => 100 ); $newsQuery = new WP_Query($newsArgs); $news = array(); $count_new = 0; for ($i=1; $i<count($data)-1; $i++) { $d = splitLine($data[$i]); $categories = array_values(explode('.', $d[4])); $tags = array_values(explode('.', $d[5])); $persons = array_values(explode('.', $d[6])); $imported = false; while ($newsQuery->have_posts()) { $newsQuery->the_post(); setup_postdata($post); $id = $post->ID; $import_date = get_post_meta($id, 'import_date', true); $import_hash = get_post_meta($id, 'import_hash', true); if (!empty($import_date) && !empty($import_hash)) { $title_hash = wp_hash($d[2]); if ($import_hash === $title_hash) { $imported = true; $d[0] = $id; } } } $date = $d[3]; if (empty($date)) { $date = date('Y-m-d 06:00:00'); $year = rand(2018, 2019); $month = rand(1, 12); $day = rand(1, 30); if ($month == 1 && $day >= 28) { $day = rand(1, 28); } $datetime = mktime(0,0,0, $month, $day, $year); $date = date('Y-m-d', $datetime); $post_data['post_date'] = $date; //var_dump($post_data['post_date']); } // the post is new => save it as a new news post if (!empty($d[2])) { $post_data = array( 'ID' => $d[0], 'post_date' => $date, 'post_title' => $d[2], 'post_type' => $d[7], 'tags_input' => $tags, 'post_status' => 'publish' ); if (isset($_REQUEST['import_news']) && !empty($_REQUEST['import_news'])) { $savedID = savePost($post_data); $hash = wp_hash($d[2]); wp_set_object_terms( $savedID, $categories, 'category' ); wp_set_object_terms( $savedID, $persons, 'people' ); update_post_meta($savedID, 'post_date', date('Y-m-d H:i:s')); update_post_meta($savedID, 'import_date', date('Y-m-d H:i:s')); update_post_meta($savedID, 'import_hash', $hash); } if (is_numeric($d[0])) { update_post_meta($d[0], 'import_update', date('Y-m-d H:i:s')); } } if (!$imported) { $post_data['is_new'] = true; $count_new++; } else { $post_data['is_new'] = false; } $news[] = $post_data; } /* $fpath = dirname( __FILE__ ) . '_postids.csv'; $f = fopen($fpath, 'w'); foreach ($postIDs as $postID) { fputcsv($f, $postID); } fclose($f); */ ?> <div class="content"> <div class="content__area"> <div class="content__area--wide"> <h3>NEWS</h3> <p>insgesamt: <?= count($news) ?></p> <p>neu: <?= $count_new ?></p> <br><br><br> <form class="form" action="" method="post"> <input type="submit" name="import_news" value="Import News" /> </form> <br><br><br> <table class="table table-striped"> <tr> <th>ID</th> <th>Date</th> <th>Title</th> <th>Is New</th> </tr> <?php foreach($news as $entry): ?> <tr> <td><?= $entry['ID'] ?></td> <td><?= $entry['post_date'] ?></td> <td><?= $entry['post_title'] ?></td> <td><?= $entry['is_new'] ? 'ja' : 'nein' ?></td> </tr> <?php endforeach ?> </table> </div> </div> </div> <?php get_footer(); ?>
true
fff38b2774cbda44a1d6e67848ee8c5274baf414
PHP
Kshevchenko94/myway
/components/Storage.php
UTF-8
2,145
2.640625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\components; use yii\base\Component; use app\components\interfaces\StorageInterface; use yii\helpers\FileHelper; use yii\web\UploadedFile; use Yii; use Intervention\Image\ImageManager; class Storage extends Component implements StorageInterface { private $fileName; /** * @param UploadedFile $file * @return mixed */ public function saveUploadedFile(UploadedFile $file) { $path = $this->preprePath($file); if($path && $file->saveAs($path)) { return $this->fileName; } } public function deleteUploadedFile($url) { if($url){ $url = Yii::getAlias('@app').'/web/img/uploads/'.$url; if(file_exists($url)) { if(unlink($url)) { return true; } }else{ return false; } }else{ return false; } } protected function preprePath(UploadedFile $file) { $this->fileName = $this->getFileName($file); $path = $this->getStoragePath().$this->fileName; $path = FileHelper::normalizePath($path); if(FileHelper::createDirectory(dirname($path))) { return $path; } } protected function getStoragePath() { return Yii::getAlias(Yii::$app->params['storagePath']); } protected function getFileName(UploadedFile $file) { //$this->resizePicture($file->tempName); $hash = sha1_file($file->tempName); $name = substr_replace($hash, '/',2,0); $name = substr_replace($name, '/',5,0); return $name.'.'.$file->extension; } protected function resizePicture($tempName) { $manager = new ImageManager(['driver'=>'imagick']); $image = $manager->make($tempName); $image->resize(Yii::$app->params['postPicture']['maxWidth'],Yii::$app->params['postPicture']['maxHeight'],function($constraint){ $constraint->aspectRatio(); $constraint->upSize(); })->save($tempName, 90); } }
true
4a137c36fbede3a50f0c31d1d10ee40987e458cd
PHP
nathanooley/new-novo
/php/upload-page-preview.php
UTF-8
1,465
2.546875
3
[]
no_license
<?php $uploadDir = 'novi/pages/'; $result = array(); if (isset($_POST["dir"]) && isset($_POST["path"])){ $path = $_POST["path"]; $projectName = $_POST["dir"]; $baseName = basename($path); $path_info = pathinfo($baseName); $targetName = preg_replace("/\s+/", "-", mb_convert_case($path_info["filename"], MB_CASE_LOWER, "UTF-8")); $ext = "." . $path_info["extension"]; if(!in_array($ext, array('.jpeg', '.jpg', '.png'))) { http_response_code("406"); echo "The wrong file format is selected. Only . jpg, .png formats are supported."; exit(); } if (!file_exists("../" . $projectName . "novi")){ mkdir("../" . $projectName . "novi"); } if (!file_exists("../" . $projectName . $uploadDir)){ mkdir("../" . $projectName . $uploadDir); } $tmpName = "../" . $projectName . $uploadDir . $targetName . $ext; $i = 0; while (true) { if (file_exists($tmpName)){ $tmpName = "../" . $projectName . $uploadDir . $targetName . "-" . (++$i) . $ext; }else{ break; } } if(copy("../" . $projectName . $path, iconv("utf-8", "cp1251", $tmpName))){ if ($i > 0){ $result['url'] = $uploadDir . $targetName . "-" . $i . $ext; }else{ $result['url'] = $uploadDir . $targetName . $ext; } }; } echo json_encode($result);
true
0b908425fd4c23d2ae08b230e56114765019f497
PHP
puddinglover/voteApp
/app/ajax/createCookieUser.php
UTF-8
708
2.890625
3
[]
no_license
<?php require 'db_connect.php'; // AJAX call for creating a user with a cookie id. Returns true if completed. $postdata = file_get_contents("php://input"); $request = json_decode($postdata); try { if(!isset($request->cookieID)){ throw new Exception('NO COOKIE ID', 123); } if(gettype($request->cookieID) !== "string") { throw new Exception('Not correct type', 123); } $cookieID = $request->cookieID; $sql = "INSERT INTO user (cookie) VALUES (:cookieID)"; $stmt = $pdo->prepare($sql); $result = $stmt->execute(array(':cookieID' => $cookieID)); echo json_encode($result); } catch (Exception $e) { header('HTTP/1.0 400 Bad error'); echo json_encode($e->getMessage()); }
true
2d8ba5a67dd73c2cea244dd1a03309b4f87f5072
PHP
rafachacon/intercom_test
/src/Controller/ApiController.php
UTF-8
9,890
2.53125
3
[]
no_license
<?php namespace App\Controller; use App\Entity\Phone; use App\Service\PhoneHelper; use DateTime; use FOS\RestBundle\Controller\AbstractFOSRestController; use FOS\RestBundle\Controller\Annotations as Rest; use JMS\Serializer\SerializerInterface; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Swagger\Annotations as SWG; /** * Class ApiController * * @Route("/api") */ class ApiController extends AbstractFOSRestController { /** * @var SerializerInterface */ private $serializer; /** * @var PhoneHelper $phoneService */ private $phoneHelper; /** * ApiController constructor. * @param SerializerInterface $serializer * @param PhoneHelper $phoneHelper */ public function __construct( SerializerInterface $serializer, PhoneHelper $phoneHelper ) { $this->serializer = $serializer; $this->phoneHelper = $phoneHelper; } /** * @Rest\Post("/v1/verifications.{_format}", name="phones_get_code", defaults={"_format":"json"}) * * @SWG\Response( * response=200, * description="Gets code and verificationId given a phone number." * ) * * @SWG\Response( * response=500, * description="An error has occurred trying to get the code." * ) * * * @SWG\Parameter( * name="phone", * in="body", * type="string", * description="The phone number", * schema={} * ) * * @SWG\Parameter( * name="verificationId", * in="body", * type="string", * description="The verirication Id", * schema={} * ) * * @SWG\Tag(name="Codes") * @param Request $request * @return Response */ public function getCodeAction(Request $request) { $em = $this->getDoctrine()->getManager(); $data = []; $message = ''; try { $responseCode = Response::HTTP_OK; $error = false; $phone = $request->get('phone'); $phoneCollection = $em->getRepository('App:Phone')->findBy( [ 'phone' => $phone, ], ['id' => 'ASC'] ); if (empty($phoneCollection)) { $responseCode = Response::HTTP_NOT_FOUND; $error = true; $message = "No code found."; } else { $phoneObject = $phoneCollection[0]; $data = [ 'verificationId' => $phoneObject->getId(), 'code' => $phoneObject->getCode() ]; } } catch (Exception $e) { $responseCode = Response::HTTP_INTERNAL_SERVER_ERROR; $error = true; $message = 'An error has occurred: ' . $e->getMessage(); } $response = [ 'code' => $responseCode, 'error' => $error, 'data' => $error ? $message : $data, ]; return new Response( $this->serializer->serialize($response, "json"), $responseCode, [ 'Access-Control-Allow-Origin' => '*' ] ); } /** * @Rest\Post("/v1/verifications/add.{_format}", name="phones_add_phone", defaults={"_format":"json"}) * * @SWG\Response( * response=200, * description="Adds a phone and creates a code for it." * ) * * @SWG\Response( * response=500, * description="An error has occurred trying to add the phone." * ) * * * @SWG\Parameter( * name="phone", * in="body", * type="string", * description="The phone number", * schema={} * ) * * * @SWG\Tag(name="Codes") * @param Request $request * @return Response */ public function addPhone(Request $request) { $em = $this->getDoctrine()->getManager(); $data = []; $message = ''; try { $responseCode = Response::HTTP_OK; $error = false; $phone = $request->get('phone', null); $phoneExists = $this->phoneHelper->exists($phone); $isValid = $this->phoneHelper->validate($phone); if ($phone != null && !$phoneExists && $isValid) { $dateAdd = new DateTime(); $code = $this->phoneHelper->generateCode($phone, $dateAdd->getTimestamp()); $phoneObject = new Phone(); $phoneObject->setPhone($phone); $phoneObject->setDateAdd($dateAdd); $phoneObject->setStatus(Phone::STATUS_PENDING); $phoneObject->setCode($code); $em->persist($phoneObject); $em->flush(); $data = [ 'verificationId' => $phoneObject->getId(), 'code' => $code ]; // todo: send an SMS to the phone. // Here's where an SMS would be sent. } else { $responseCode = Response::HTTP_INTERNAL_SERVER_ERROR; $error = true; $message = "The phone '{$phone}' is not valid."; } } catch (Exception $e) { $responseCode = Response::HTTP_INTERNAL_SERVER_ERROR; $error = true; $message = 'An error has occurred: ' . $e->getMessage(); } $response = [ 'code' => $responseCode, 'error' => $error, 'data' => $error ? $message : $data, ]; return new Response( $this->serializer->serialize($response, "json"), $responseCode, [ 'Access-Control-Allow-Origin' => '*' ] ); } /** * @Rest\Post("/v1/verifications/verify.{_format}", name="phones_verify", defaults={"_format":"json"}) * * @SWG\Response( * response=200, * description="Verifies a phone given the verification Id and the code." * ) * * @SWG\Response( * response=500, * description="An error has occurred trying to verify the code." * ) * * * @SWG\Parameter( * name="verificationId", * in="body", * type="string", * description="The verification Id generated when the phone was added.", * schema={} * ) * * @SWG\Parameter( * name="code", * in="body", * type="string", * description="The code", * schema={} * ) * * * @SWG\Tag(name="Codes") * @param Request $request * @return Response */ public function verify(Request $request) { $em = $this->getDoctrine()->getManager(); $data = []; $message = ''; try { $responseCode = Response::HTTP_OK; $error = false; $verificationId = $request->get('verificationId', null); $code = $request->get('code', null); $phoneRepo = $em->getRepository('App:Phone'); $phoneCollection = $phoneRepo->findBy( [ 'id' => $verificationId, 'code' => $code ] ); // The phone must exist. if (!empty($phoneCollection)) { /** @var Phone $phoneObject */ $phoneObject = $phoneCollection[0]; // The phone must be in status "pending". $status = $phoneObject->getStatus(); if ($status == Phone::STATUS_PENDING) { // Check expiration. $expired = $this->phoneHelper->expired($phoneObject); $phoneObject->setDateCheck(new DateTime()); if (!$expired) { $codeBuild = $this->phoneHelper->generateCode($phoneObject->getPhone(), $phoneObject->getDateAdd()->getTimestamp()); if ($code === $codeBuild) { $phoneObject->setStatus(Phone::STATUS_VERIFIED); } else { $phoneObject->setStatus(Phone::STATUS_REJECTED); } } else { $phoneObject->setStatus(Phone::STATUS_EXPIRED); } $em->persist($phoneObject); $em->flush(); $data = [ 'phone' => $phoneObject->getPhone(), 'status' => $phoneObject->getStatus() ]; } else { $responseCode = Response::HTTP_INTERNAL_SERVER_ERROR; $error = true; $message = 'No such a phone.'; } } else { $responseCode = Response::HTTP_INTERNAL_SERVER_ERROR; $error = true; $message = 'The code is not valid.'; } } catch (Exception $e) { $responseCode = Response::HTTP_INTERNAL_SERVER_ERROR; $error = true; $message = 'An error has occurred: ' . $e->getMessage(); } $response = [ 'code' => $responseCode, 'error' => $error, 'data' => $error ? $message : $data, ]; return new Response( $this->serializer->serialize($response, "json"), $responseCode, [ 'Access-Control-Allow-Origin' => '*' ] ); } }
true
72a73cc54d5badd3e4d841e893d9d75dc7b9644b
PHP
emartin-cfe/meeting_minutes
/deleteNote.php
UTF-8
1,386
2.640625
3
[]
no_license
<?php session_start(); if (!$_SESSION['signed_in']) { header("Location: sign_in.html"); exit; } ?> <?php $link = mysql_connect('127.0.0.1', 'task_tracker', 'task_tracker'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('scheduling') or die(mysql_error()); $meetingID = mysql_real_escape_string($_GET['meetingID']); $noteID = mysql_real_escape_string($_GET['noteID']); # Check to see if this note is new - if it is not, give an error screen $query = "SELECT new FROM MeetingNote WHERE noteID LIKE '$noteID' AND meetingID LIKE '$meetingID'"; $dbHandle = mysql_query($query) or die(mysql_error()); $row = mysql_fetch_array($dbHandle); $new = $row['new']; if ($new != 'new') { print "You can only delete new notes! Click <a href='displayTasks.php?meetingID=$meetingID'>here</a> to return to the main menu"; exit; } # If all is well, delete the AssignedEmployees links, then the note itself $query = "DELETE FROM AssignedEmployees " . "WHERE noteID LIKE '$noteID'"; $dbHandle = mysql_query($query) or die(mysql_error()); # If all is well, delete the note $query = "DELETE FROM MeetingNote " . "WHERE noteID LIKE '$noteID' AND meetingID LIKE '$meetingID'"; $dbHandle = mysql_query($query) or die(mysql_error()); header("Location: displayTasks.php?meetingID=$meetingID"); exit(); ?>
true
8c14f1fce6251edb84a1f4e02af16526e16b69d3
PHP
duongnt99/NewRegis
/Models/Admin/ShowListSubjectModel.php
UTF-8
663
2.546875
3
[]
no_license
<?php trait ShowListSubject{ public function fetchListSubject(){ $conn = Connection::getInstance(); $query = $conn->query("SELECT *,subject.id as idsb FROM `subject` inner join (select id from kithi where Status=1) kithi on subject.idkithi = kithi.id"); return $query->fetchAll(); } public function deleteSubject($id) { $conn = Connection::getInstance(); $query = $conn->prepare("DELETE from listsubject where idmonhoc=:id"); $query->execute(array("id" => $id)); $query1 = $conn->prepare("DELETE from subject where id=:id"); $query1->execute(array("id" => $id)); } } ?>
true
e6ac52d904461c2085c2553bea1dca3981e310b0
PHP
johan-Rm/Symfony-4-src-folder-Johanrm
/src/Entity/Person.php
UTF-8
14,536
2.515625
3
[]
no_license
<?php declare(strict_types=1); namespace App\Entity; use ApiPlatform\Core\Annotation\ApiProperty; use ApiPlatform\Core\Annotation\ApiResource; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use App\Entity\Traits\IdentifiableTrait; use App\Entity\Traits\ThingTrait; use App\Entity\Traits\TimestampableTrait; use App\Entity\Traits\AdministrableTrait; use Symfony\Component\Serializer\Annotation\Groups; use ApiPlatform\Core\Annotation\ApiSubresource; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter; use ApiPlatform\Core\Annotation\ApiFilter; /** * A person (alive, dead, undead, or fictional). * * @see http://schema.org/Person Documentation on Schema.org * * @ORM\Entity * @ApiResource(iri="http://schema.org/Person", * attributes={ * "normalization_context"={"groups"={"thing", "person"}} * }, * collectionOperations={ * "get"={ * "method"="GET" * }, * "post" * }, * itemOperations={ * "get"={ * "method"="GET" * } * } * ) * @ApiFilter(SearchFilter::class, properties={ "firstname": "exact", "lastname": "exact", "email": "exact" }) * @ORM\HasLifecycleCallbacks() */ class Person { use IdentifiableTrait , ThingTrait , TimestampableTrait , AdministrableTrait ; /** * @var string * * @ORM\Column(name="firstname", type="string", length=255, nullable=true, options={"comment":"Firstname"}) * * @Assert\NotBlank( * message="Enter a first name please" * ) * @Groups("person") */ private $firstname; /** * @var string * * @ORM\Column(name="lastname", type="string", length=255, options={"comment":"Lastname"}) * @Assert\NotBlank( * message="Enter a name please" * ) * @Groups("person") */ private $lastname; /** * @ORM\ManyToOne(targetEntity="Gender", inversedBy="persons") * @ORM\JoinColumn(name="gender_id", referencedColumnName="id", nullable=true) * * @ Assert\NotBlank(message="Enter a gender please") * @Groups("person") */ private $gender; /** * @var \DateTime * * @ORM\Column(name="birthday", type="date" , options={"comment":"Birthday"}, nullable=true) * @Groups("person") */ private $birthday; /** * @var string * * @ORM\Column(name="place_of_birth", type="string", length=255, options={"comment":"Place of birth"}, nullable=true) * @Groups("person") */ private $placeOfBirth; /** * @var string * * @ORM\Column(name="phone", type="string", length=255, options={"comment":"Phone"}, nullable=true) * * @Assert\Expression( * "this.getEmail() || this.getPhone()", * message="Please, enter email or phone" * ) * * @ Assert\Regex( * pattern="/^(0)[0-9]{9}$/", * match=true, * message="This phone number is invalid" * ) */ private $phone; /** * @var string * * @ORM\Column(name="email", type="string", length=255, options={"comment":"Email"}, nullable=true) * * * @Assert\Email( * message = "This email is invalid" * ) */ private $email; /** * @ORM\ManyToMany(targetEntity="Address", inversedBy="persons", cascade= {"persist"}) * @ORM\JoinTable( * name="persons_addresses", * joinColumns={ * @ORM\JoinColumn(name="person_id", referencedColumnName="id") * }, * inverseJoinColumns={ * @ORM\JoinColumn(name="address_id", referencedColumnName="id") * } * ) **/ private $addresses; /** * @ORM\ManyToMany(targetEntity="Accommodation", inversedBy="persons", cascade= {"persist"}) * @ORM\JoinTable( * name="persons_accommodations", * joinColumns={ * @ORM\JoinColumn(name="person_id", referencedColumnName="id") * }, * inverseJoinColumns={ * @ORM\JoinColumn(name="accommodation_id", referencedColumnName="id") * } * ) **/ private $teams; /** * @ORM\OneToMany(targetEntity="Event", mappedBy="person") */ private $events; /** * @ORM\OneToMany(targetEntity="Accommodation", mappedBy="person") */ private $accommodations; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $origin; /** * @ORM\Column(type="json", nullable=true) */ private $customer_traffic = []; /** * Many Pdfs * @ORM\ManyToMany(targetEntity="\App\Entity\DocumentObject", inversedBy="pdfsPersons", cascade={"persist"}) * @ORM\JoinTable(name="persons_pdfs") * * @Groups("person") * @ApiSubresource */ private $pdfs; /** * @ORM\ManyToOne(targetEntity="\App\Entity\PersonPosition") * @ORM\JoinColumn(name="position_id", referencedColumnName="id") * * @Groups("person") * @ ApiSubresource */ private $position; /** * @var string * * @ORM\Column(type="string", length=255, nullable=true) * @Groups("person") */ private $informations; /** * @ORM\ManyToOne(targetEntity="\App\Entity\PersonNature") * @ORM\JoinColumn(name="nature_id", referencedColumnName="id") * * @Groups("person") * @ApiSubresource */ private $prospect; /** * Constructor */ public function __construct() { $this->addresses = new ArrayCollection(); $this->events = new ArrayCollection(); $this->pdfs = new ArrayCollection(); $this->teams = new ArrayCollection(); } public function __toString() { return $this->getFullName(); } /** * @return string */ public function getFirstname() { return $this->firstname; } /** * @param string $firstname */ public function setFirstname($firstname) { $this->firstname = $firstname; } /** * @return string */ public function getLastname() { return $this->lastname; } /** * @param string $informations */ public function setInformations($informations) { $this->informations = $informations; } /** * @return string */ public function getInformations() { return $this->informations; } /** * @param string $position */ public function setPosition($position) { $this->position = $position; } /** * @return string */ public function getPosition() { return $this->position; } /** * @param string $lastname */ public function setLastname($lastname) { $this->lastname = $lastname; } public function getFullName() { return trim($this->getFirstName().' '.$this->getLastName()); } public function setFullName($fullName) { $names = explode(' ', $fullName); $firstName = array_shift($names); $lastName = implode(' ', $names); $this->setFirstName($firstName); $this->setLastName($lastName); } /** * @return string */ public function getGender() { return $this->gender; } /** * @param string $gender */ public function setGender($gender) { $this->gender = $gender; } /** * @return \DateTime */ public function getBirthday() { return $this->birthday; } /** * @param \DateTime $birthday */ public function setBirthday($birthday) { $this->birthday = $birthday; } /** * @return string */ public function getPlaceOfBirth() { return $this->placeOfBirth; } /** * @param string $placeOfBirth */ public function setPlaceOfBirth($placeOfBirth) { $this->placeOfBirth = $placeOfBirth; } /** * @return string */ public function getPhone() { return $this->phone; } /** * @param string $phone */ public function setPhone($phone) { $this->phone = $phone; } /** * @return string */ public function getEmail() { return $this->email; } /** * @param string $email */ public function setEmail($email) { $this->email = $email; } /** * Set comment * * @param string $comment * * @return Appointment */ public function setComment($comment) { $this->comment = $comment; return $this; } /** * Get comment * * @return string */ public function getComment() { return $this->comment; } /** * Add address * * @param \AppBundle\Entity\Address $address * * @return Person */ public function addAddress($address) { if ($this->addresses->contains($address)) { return; } $this->addresses->add($address); } /** * Remove address * * @param \AppBundle\Entity\Address $address */ public function removeAddress($address) { if (!$this->addresses->contains($address)) { return; } $this->addresses->removeElement($address); } /** * Get addresses * * @return \Doctrine\Common\Collections\Collection */ public function getAddresses() { return $this->addresses; } /** * Add accommodations * * @param \App\Entity\Accommodation $accommodation * * @return Person */ public function addAccommodation($accommodation) { $this->accommodations[] = $accommodation; } /** * Remove accommodations * * @param \App\Entity\Accommodation $accommodation */ public function removeAccommodation($accommodation) { $this->accommodations->removeElement($accommodation); } /** * Get accommodations * * @return \Doctrine\Common\Collections\Collection */ public function getAccommodations() { return $this->accommodations; } /** * Add Event * * @param \App\Entity\Event $event * * @return Person */ public function addEvent($event) { $this->events[] = $event; } /** * Remove appointment * * @param \App\Entity\Event $event */ public function removeEvent($event) { $this->events->removeElement($event); } /** * Get appointments * * @return \Doctrine\Common\Collections\Collection */ public function getEvents() { return $this->events; } public function getOrigin(): ?string { return $this->origin; } public function setOrigin(?string $origin): self { $this->origin = $origin; return $this; } public function getCustomerTraffic(): ?array { return $this->customer_traffic; } public function setCustomerTraffic(?array $customer_traffic): self { $this->customer_traffic = $customer_traffic; return $this; } /** * Get pdfs * * @return Collection|Accommodation[] */ public function getPdfs(): Collection { return $this->pdfs; } /** * Set the value of Pdfs * * @param mixed pdfs * * @return self */ public function setPdfs($pdfs) { $this->pdfs = $pdfs; return $this; } /** * Add pdf * * @param \App\Entity\DocumentObject $pdf * * @return Accommodation */ public function addPdf(\App\Entity\DocumentObject $pdf) { if ($this->pdfs->contains($pdf)) { return; } $this->pdfs->add($pdf); $pdf->addPdfsPerson($this); return $this; } /** * Remove pdf * * @param \AppBundle\Entity\DocumentObject $pdf * * @return Accommodation */ public function removePdf(\App\Entity\DocumentObject $pdf): self { if ($this->pdfs->contains($pdf)) { $this->pdfs->removeElement($pdf); } return $this; } /** * Add accommodation * * @param \AppBundle\Entity\Accommodation $accommodation * * @return Person */ public function addTeam($accommodation) { if ($this->teams->contains($accommodation)) { return; } $this->teams->add($accommodation); } /** * Remove accommodation * * @param \AppBundle\Entity\Accommodation $accommodation */ public function removeTeam($accommodation) { if (!$this->teams->contains($accommodation)) { return; } $this->teams->removeElement($accommodation); } /** * Get teams * * @return \Doctrine\Common\Collections\Collection */ public function getTeams() { return $this->teams; } /** * Set the value of prospect * * @param mixed prospect * * @return self */ public function setProspect($prospect) { $this->prospect = $prospect; return $this; } /** * Get the value of prospect * * @return mixed */ public function getProspect() { return $this->prospect; } /** * Set the value of Addresses * * @param mixed addresses * * @return self */ public function setAddresses($addresses) { $this->addresses = $addresses; return $this; } /** * Set the value of Teams * * @param mixed teams * * @return self */ public function setTeams($teams) { $this->teams = $teams; return $this; } /** * Set the value of Events * * @param mixed events * * @return self */ public function setEvents($events) { $this->events = $events; return $this; } /** * Set the value of Accommodations * * @param mixed accommodations * * @return self */ public function setAccommodations($accommodations) { $this->accommodations = $accommodations; return $this; } }
true
8a157b7ab1043c7f1870e0e3b071edd03d561350
PHP
chrispittersl/VIP
/php/conexao.php
UTF-8
282
2.671875
3
[]
no_license
<?php try{ $pdo = new PDO("mysql:host=localhost;dbname=vip","root","",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); }catch(PDOException $e){ echo $e->getMessage(); } ?>
true
6359766cf2d0fce3799547a0faf9e8e4ed2f0479
PHP
daran9/n96localization-via-context
/Server/setup_data.php
UTF-8
1,554
3.1875
3
[ "MIT" ]
permissive
<?php /* Summary : This script gets the required POST variables, decodes them and insert them into the database. * Required POST variable : WLANDATA * Required POST variable : BLDG * Required POST variable : FLOOR * Required POST variable : SECTION * Return : */ //TODO: BLDG, FLOOR and SECTION information should also be transported in JSON format. //Collect POST data $WLAN_DATA = $_POST['WLANDATA']; $BLDG = $_POST['BLDG']; $FLOOR = $_POST['FLOOR']; $SECTION = $_POST['SECTION']; //Decode data in JSON notation to associative array containing BSSID and RSSI values $WlanArray = json_decode(stripslashes($WLAN_DATA),true); /* //Store values to a file $filename = "files/data.txt"; $file = fopen($filename,"a"); fwrite($file, $WlanArray[0]['BSSID']." ".$WlanArray[1]['BSSID']." ".$WlanArray[2]['BSSID']." ".$WlanArray[3]['BSSID']." ". $WlanArray[0]['RSSI']." ".$WlanArray[1]['RSSI']." ".$WlanArray[2]['RSSI']." ".$WlanArray[3]['RSSI']." ". $BLDG." ".$FLOOR." ".$SECTION."\n"); fwrite($file, $BLDG." ".$FLOOR." ".$SECTION."\n"); fclose($file); echo $filename; */ //Connect to database and store values //include the database funtions include 'db_sql.php'; //insert the collected POST data values into the database tables by calling the insert function in db_sql.php insertData($WlanArray[0]['BSSID'],$WlanArray[1]['BSSID'],$WlanArray[2]['BSSID'],$WlanArray[3]['BSSID'], $WlanArray[0]['RSSI'],$WlanArray[1]['RSSI'],$WlanArray[2]['RSSI'],$WlanArray[3]['RSSI'], $BLDG,$FLOOR,$SECTION); //Close the Connection closeDB(); ?>
true
985d1a8071bc0d772bb9567eecc747f235c8d437
PHP
SunderShadow/php-dotenv
/src/Parser.php
UTF-8
2,515
3.03125
3
[]
no_license
<?php namespace Sunder\Dotenv; use Sunder\Dotenv\Exceptions\CorruptedFileException; use Sunder\Dotenv\Exceptions\UndefinedFileException; class Parser { /** * Array of string lines * @var string[] */ private array $buffer; /** * Current line * @var string */ private string $line; /** * Current line num * @var int */ private int $lineNum = 0; /** * @throws UndefinedFileException */ public function __construct(private string $filepath) { if (!file_exists($this->filepath)) { throw new UndefinedFileException($this->filepath); } } /** * @throws UndefinedFileException * @throws CorruptedFileException */ public function parse(): \Generator { $this->readFile(); $bufferSize = count($this->buffer); for ($this->lineNum = 0; $this->lineNum < $bufferSize; $this->lineNum++) { $this->extractLine(); $this->prepareLine(); if (!$this->lineEmpty()) { $this->removeCommentIfExists(); $this->disassembleLine($key, $value); yield $key => $value; } } } private function extractLine(): void { $this->line = $this->buffer[$this->lineNum]; } private function prepareLine(): void { $this->line = trim($this->line); } private function lineEmpty(): bool { return !strlen($this->line) || $this->line[0] === '#'; } private function removeCommentIfExists(): void { if ($commentPos = $this->lineHasComment()) { $this->removeComment($commentPos); } } private function removeComment(int $commentPos): void { $this->line = rtrim(substr($this->line, 0, $commentPos)); } private function lineHasComment(): int|false { return strpos($this->line, '#'); } /** * @throws CorruptedFileException */ private function disassembleLine(&$key, &$value): void { $vars = explode('=', $this->line); if (!isset($vars[1]) || count($vars) > 2) { throw new CorruptedFileException($this->filepath, $this->lineNum); } $key = $vars[0]; $value = $vars[1]; } /** * @throws UndefinedFileException */ private function readFile(): void { $this->buffer = explode(PHP_EOL, file_get_contents($this->filepath)); } }
true
546ee2f7b023c4804169b75236e9374ad5c6bfdc
PHP
suporte-avdesign/discal
/app/Services/Web/ClawsServices.php
UTF-8
10,774
2.921875
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: avdesign * Date: 08/12/19 * Time: 10:05 */ namespace App\Services\Web; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use Symfony\Component\DomCrawler\Crawler; use App\Services\Web\Traits\ClawsTrait; class ClawsServices { use ClawsTrait; private $url; private $config; public function __construct() { $this->config = typeJson($this->getConfig()); } /** * Retorna os posts referente ao menu. * Box/Dicas * * @param $menu * @param $url * @return null|$content */ public function getClaws($slug, $menu, $url) { try { $client = new Client; $response = $client->get($url); $html = $response->getBody()->getContents(); $evaluate = new Crawler($html); $crawler = $this->outerHtml($evaluate, $menu, $slug); if (!$crawler) { return null; } $content[$menu] = $this->filterClaws($crawler, $slug, $menu); return $content; } catch (ClientException $e) { return null; } } /** * Retorna o html desidratado. * Box/Dicas * * @param $crawler * @param $menu * @param $slug * @return null|Crawler */ private function outerHtml($crawler, $menu, $slug) { $eva = $this->config->$slug->$menu->evaluate; $ele = $this->config->$slug->$menu->element; $count = $crawler->evaluate("count($eva)"); if ((int)$count[0] == 0) { return null; } $html = $crawler->filter($ele)->outerHtml(); $crawler = new Crawler($html); return $crawler; } /** * Filtra a url e verifica se não quebrou o html. * Verifica a url amigavel * * @param $crawler * @param $menu * @param $slug * @return mixed */ private function filterClaws($crawler, $slug, $menu) { $config = typeJson($this->config->$slug->$menu); $claws = $crawler->filter($config->element)->each(function (Crawler $crawler) use($config, $slug) { return $crawler->filter($config->parent)->each(function (Crawler $crawler) use($config, $slug) { try { $title = implode(' ', $config->title); $title = $crawler->filter($title)->text(); } catch( \InvalidArgumentException $e) { $title = ''; } try { $url = implode(' ', $config->link); $url = $crawler->filter($url)->attr('href'); $seg = explode('/', $url); //Posição do array[...] $segment = $this->config->$slug->details->segment; //Altera Slug $slug = $this->changeSlug($slug); $link = route('details-claws', ['slug' => $slug, 'segment' => $seg[$segment]]); } catch( \InvalidArgumentException $e) { $link = ''; } try { $date = implode(' ', $config->date); $date = $crawler->filter($date)->text(); } catch( \InvalidArgumentException $e) { $date = ''; } try { $image = implode(' ', $config->image); $image = $crawler->filter($image)->attr('src'); } catch( \InvalidArgumentException $e) { $image = ''; } try { $description = implode(' ', $config->description); $description = $crawler->filter($description)->text(); } catch( \InvalidArgumentException $e) { $description = ''; } return [ 'author' => $config->author, 'title' => $title, 'link' => $link, 'date' => $date, 'image' => $image, 'description' => $description ]; }); }); return $claws[0]; } /** * Retorna o conteudo em html * * @param $slug * @param $url * @return null|$content */ public function getDetails($slug, $url) { try { $config = $this->config->$slug->details; $client = new Client; $response = $client->get($url); $html = $response->getBody()->getContents(); $crawler = new Crawler($html); $content['tags'] = $this->detailsTags($crawler, $slug); $crawler = $this->detailsHtml($crawler, $slug); if (!$crawler) { return null; } /** Header **/ $content['author'] = $config->author; try { $title = implode(' ', $config->title); $content['title'] = $crawler->filter($title)->text(); } catch( \InvalidArgumentException $e) { $content['title'] = ''; } try { $image = implode(' ', $config->image); $content['image'] = $crawler->filter($image)->attr('src'); } catch( \InvalidArgumentException $e) { $content['image'] = ''; } try { $date = implode(' ', $config->date); $content['date'] = $crawler->filter($date)->text(); } catch( \InvalidArgumentException $e) { $content['date'] = ''; } //Remover nodes $html = $this->removeDetails($crawler, $slug); //Replace attributes $replace = $config->replace; if ($replace) { $i=0; foreach ($replace as $key => $value) { $html = $this->replaceDetails($key, $value, $html); $i++; } $content['html'] = $html; } return $content; } catch (ClientException $e) { return null; } } /** * Retorna as tags da págna. * Subistitui a url * * @param $crawler * @param $slug * @return null|Crawler */ private function detailsTags($crawler, $slug) { $config = $this->config->$slug->details; $count = $crawler->filter($config->tags->parent)->count(); if(!$count) { return null; } $tags = $crawler->filter($config->tags->parent)->each(function (Crawler $crawler) use($config) { return $crawler->filter('a')->each(function (Crawler $crawler) use($config) { //Replace attributes $replace = $config->tags->replace; if ($replace) { foreach ($replace as $key => $value) { return [ 'link' => str_replace($key, $value, $crawler->link()->getUri()), 'text' => ucfirst($crawler->text()) ]; } } }); }); return collect($tags[0])->shuffle(); } /** * Retorna o html do conteúdo principal. * * @param $crawler * @param $slug * @return null|Crawler */ private function detailsHtml($crawler, $slug) { $config = $this->config->$slug->details; $count = $crawler->filter($config->content)->count(); if(!$count) { return null; } $html = $crawler->filter($config->content)->html(); $crawler = new Crawler($html); return $crawler; } /** * Remove html element * * @param $crawler * @param $slug * @param $ele * @return html */ private function removeDetails($crawler, $slug) { $config = $this->config->$slug->details; //remove script $cs = $crawler->filter($config->parent. ' script')->count(); if ($cs) { $crawler = $this->removeElement($crawler, $config->parent. ' script'); } //remove form $cf = $crawler->filter($config->parent. ' form')->count(); if ($cf) { $crawler = $this->removeElement($crawler, $config->parent. ' form'); } $elements = $config->remove; if ($elements) { foreach ($elements as $item) { $ele = $crawler->filter("{$config->parent} {$item}")->count(); if ($ele) { $crawler = $this->removeElement($crawler, "{$config->parent} {$item}"); } } } //remove other $other = $crawler->filter($config->other)->count(); if ($other) { return $crawler->filter($config->other)->html(); } return $crawler->filter($config->parent)->html(); /* $html = $crawler->filter($config->parent)->html(); $crawler = new Crawler($html); return $crawler; */ } /** * Remove elementos específicos. * * @param $crawler * @param $ele * @return mixed */ private function removeElement($crawler, $element) { $crawler->filter($element)->each(function (Crawler $crawler) { foreach ($crawler as $node) { $node->parentNode->removeChild($node); } }); return $crawler; } /** * Substituir tags do html * * @param $crawler * @param $key * @param $value * @return mixed */ private function replaceDetails($key, $value, $html) { return str_replace($key, $value, $html); } /** SEM USU * @param $crawler */ private function createHtml($crawler) { //é assim que você começa get domDocument //$domDocument = $crawler->getNode(0)->parentNode; /* //creating div $form = $domDocument->createElement('form'); $form->setAttribute('method', 'post'); $form->setAttribute('id', 'form-claws'); $input = $domDocument->createElement('input'); $input->setAttribute('type', 'text'); $input->setAttribute('id', 'email-claws'); $input->setAttribute('name', 'email-claws'); */ //adicionando div após a tag h4 $ele = $crawler->filter('.the-content')->getNode(0); $ele->parentNode->insertBefore( $crawler, $ele->nextSibling); dd($crawler); } }
true
c18a0b84053af12e8936f338722c65eba77b13b5
PHP
PatBass/yafabhi
/2_plan_team/include/class.RemoteApi.php
UTF-8
10,846
2.71875
3
[]
no_license
<?php /* * This class provides Remote Api methods * * @author Yuriy Bakhtin * @name RemoteApi * @version 0.1 * @package 2-plan * @link http://2-plan.com * @license http://opensource.org/licenses/gpl-license.php GNU General Public License v3 or later */ class RemoteApi extends TableBase { private $accesskey = ""; private $project = null; private $user_permissions = array(); /* * Constructor * Initialize the event log */ public function __construct($request, $set_project = true) { $this->table_name = 'projekte'; $this->mylog = new mylog; $this->setUserPermissions($request->getParam('name')); if($set_project) { $this->setAccessKey($request->getParam('accesskey')); $this->setProject(); } } /* * remove all unsupported symbols from access key * * @param string $accesskey access key * @set string $accesskey clear access key */ private function setAccessKey($accesskey) { $this->accesskey = preg_replace("/[^a-z0-9]/", "", $accesskey); } /* * get project info from DB by accesskey * * @param * @return bool $result true if project exists */ private function setProject() { if($project = mysql_fetch_object(mysql_query("SELECT * FROM ".$this->getTableName()." WHERE accesskey='{$this->accesskey}'"))) { $this->project = $project; return true; } else { Response::error("Project doesn't exist"); return false; } } /* * set user permissions * * @param string $login user name(for root) or email * @set array $user_permissions */ public function setUserPermissions($login) { $role = mysql_fetch_assoc(mysql_query("SELECT ra.role FROM ".$this->getTablePrefix()."user u LEFT JOIN ".$this->getTablePrefix()."roles_assigned ra ON u.ID=ra.user WHERE (u.name='$login' AND u.ID=1) OR u.email='$login'")); if($roles = mysql_fetch_assoc(mysql_query("SELECT projects, tasks, milestones, messages, files, user, timetracker, admin, api FROM ".$this->getTablePrefix()."roles WHERE ID = '{$role["role"]}'"))) { foreach($roles as $name => $permissions) { $roles[$name] = unserialize($permissions); } } else { $roles = array(); } $this->user_permissions = $roles; } /* * get user permissions * * @set array $user_permissions */ public function getUserPermissions($name = "") { return $name!="" ? $this->user_permissions[$name] : $this->user_permissions; } /* * check access for the role and actions * * @param string $role role name * @param strings $action many action names * @set array $user_permissions */ public function access($role/*, $action1, $action2, ..., $actionN */) { $actions = func_get_args(); unset($actions[0]); $permission = true; foreach($actions as $action) { $permission &= $this->user_permissions[$role][$action]; } if(!$permission) Response::error("No Permissions"); } /* * verify existing of the workpackage * * @param int $uuid uuid * @param int $workpackage_id Workpackage ID * @return int workpackage ID */ public function existWorkpackage($uuid, $workpackage_id) { $uuid = (int) $uuid; $workpackage_id = (int) $workpackage_id; $workpackage = mysql_fetch_assoc(mysql_query("SELECT ID FROM ".$this->getTablePrefix()."workpackage WHERE (uuid='$uuid' OR ID='$workpackage_id') AND project='{$this->project->ID}' LIMIT 1")); if(!$workpackage) Response::error("Workpackage doesn't exist"); else return (int) $workpackage["ID"]; } /* * verify existing of the task * * @param int $task_id Task ID */ public function existTask($task_id) { $task_id = (int) $task_id; $task = mysql_fetch_assoc(mysql_query("SELECT ID FROM ".$this->getTablePrefix()."tasks WHERE ID='$task_id' AND project='{$this->projectID()}'")); if(!$task) Response::error("Task doesn't exist"); } /* * get project * * @return array $project */ public function project() { $project = (array) $this->project; unset($project["ID"]); unset($project["accesskey"]); unset($project["uuid"]); $probj = new project(); $project["actual"] = $this->projectActual(); $project["completed"] = $probj->getProgress($this->projectID())."%"; return $project; } /* * get project ID * * @return int $project */ public function projectID() { return (int) $this->project->ID; } /* * update uuid of the project * * @param int $uuid * @return bool result */ public function projectUpdateUuid($uuid) { $uuid = (int) $uuid; $result = mysql_query("UPDATE ".$this->getTableName()." SET uuid='$uuid' WHERE ID='{$this->projectID()}'"); return (bool) $result; } /* * get all users of the project * * @param int $limit max limit of the return users * @return array $users */ public function projectUsers($limit = 0) { $limit = (int) $limit; $users = array(); if($limit>0) $sql_limit = " LIMIT $limit"; $users_q = mysql_query("SELECT user FROM ".$this->getTablePrefix()."projekte_assigned WHERE projekt='{$this->projectID()}'$sql_limit"); while($user = mysql_fetch_assoc($users_q)) { $user = mysql_fetch_assoc(mysql_query("SELECT * FROM ".$this->getTablePrefix()."user WHERE ID='{$user["user"]}'")); unset($user["pass"]); $users[] = $user; } return $users; } /* * get all workpackages of the project * * @param int $status workpackage status (0 = Finished, 1 = Active, 2 = All) * @return array $workpackages */ public function projectWorkpackages($status) { $status = (int) $status; $workpackages = array(); if($status==0 || $status==1) $sql_where = " AND status='$status'"; $workpackages_q = mysql_query("SELECT * FROM ".$this->getTablePrefix()."workpackage WHERE project='{$this->project->ID}'$sql_where"); while($workpackage = mysql_fetch_assoc($workpackages_q)) { $workpackage["actual"] = $this->workpackageActual($workpackage["ID"]); $workpackage["efforttocomplete"] = $this->workpackageEffort($workpackage["ID"]); $workpackages[] = $workpackage; } return $workpackages; } /* * get all tasks of the project * * @param int $project_id Project ID * @return array $tasks */ public function projectTasks() { $tasks = array(); $tasks_q = mysql_query("SELECT * FROM ".$this->getTablePrefix()."tasks WHERE project='{$this->projectID()}'"); while($task = mysql_fetch_assoc($tasks_q)) { $task["actual"] = $this->taskActual(array($task["ID"])); $tasks[] = $task; } return $tasks; } /* * Time booked on all tasks for the project * * @return float $time */ private function projectActual() { $tasks = $this->projectTasksIDs(); return $this->taskActual($tasks); } /* * all tasks IDs of the project * * @param int $project_id Project ID * @return array $tasks_ids */ private function projectTasksIDs() { $tasks_q = mysql_query("SELECT ID FROM ".$this->getTablePrefix()."tasks WHERE project='{$this->projectID()}'"); $tasks = array(); while($task = mysql_fetch_assoc($tasks_q)) $tasks[] = $task["ID"]; return $tasks; } /* * get milestone ID by uuid * * @param int $uuid uuid * @return int $id ID of the milestone */ public function milestoneIDByUuid($uuid) { $uuid = mysql_real_escape_string($uuid); $milestone = mysql_fetch_assoc(mysql_query("SELECT ID FROM ".$this->getTablePrefix()."milestones WHERE uuid='$uuid'")); return (int) $milestone["ID"]; } /* * get workpackage ID by uuid * * @param int $uuid uuid * @return int $id ID of the workpackage */ public function workpackageIDByUuid($uuid) { $uuid = mysql_real_escape_string($uuid); $workpackage = mysql_fetch_assoc(mysql_query("SELECT ID FROM ".$this->getTablePrefix()."workpackage WHERE uuid='$uuid'")); return (int) $workpackage["ID"]; } /* * get all tasks of the workpackage * * @param int $workpackage_id Workpackage ID * @return array $tasks */ public function workpackageTasks($workpackage_id) { $workpackage_id = (int) $workpackage_id; $tasks = array(); $tasks_q = mysql_query("SELECT * FROM ".$this->getTablePrefix()."tasks WHERE workpackage='$workpackage_id'"); while($task = mysql_fetch_assoc($tasks_q)) { $task["actual"] = $this->taskActual(array($task["ID"])); $tasks[] = $task; } return $tasks; } /* * Time booked on all tasks for the workpackage * * @param int $workpackage_id Workpackage ID * @return float $time */ private function workpackageActual($workpackage_id) { $tasks = $this->workpackageTasksIDs($workpackage_id); return $this->taskActual($tasks); } /* * get efforttocomplete on all tasks for the workpackage * * @param int $workpackage_id Workpackage ID * @return float $time */ private function workpackageEffort($workpackage_id) { $tasks = $this->workpackageTasksIDs($workpackage_id); return $this->taskEffort($tasks); } /* * all tasks IDs of the workpackage * * @param int $workpackage_id Workpackage ID * @return array $tasks_ids */ private function workpackageTasksIDs($workpackage_id) { $tasks_q = mysql_query("SELECT ID FROM ".$this->getTablePrefix()."tasks WHERE workpackage='$workpackage_id'"); $tasks = array(); while($task = mysql_fetch_assoc($tasks_q)) $tasks[] = $task["ID"]; return $tasks; } /* * assign milestone to the workpackage * * @param int $workpackage_id Workpackage ID * @param int $workpackage_id Workpackage ID * @return bool $result */ public function workpackageAssignMilestone($workpackage_id, $milestone_id) { $result = mysql_query("UPDATE ".$this->getTablePrefix()."workpackage SET milestone='$milestone_id' WHERE ID='$workpackage_id'"); return (bool) $result; } /* * Time booked on all the tasks * * @param int $task_ids Tasks IDs * @return float $time */ private function taskActual($task_ids) { if(count($task_ids)>0) $time = mysql_fetch_assoc(mysql_query("SELECT SUM(hours) as actual FROM ".$this->getTablePrefix()."timetracker WHERE task IN ('".join("','",$task_ids)."')")); return (string) number_format($time["actual"],2,".",""); } /* * get efforttocomplete on all the tasks * * @param int $task_ids Tasks IDs * @return float $time */ private function taskEffort($task_ids) { if(count($task_ids)>0) $time = mysql_fetch_assoc(mysql_query("SELECT SUM(efforttocomplete) as effort FROM ".$this->getTablePrefix()."tasks WHERE ID IN ('".join("','",$task_ids)."')")); return (string) number_format($time["effort"],2,".",""); } /* * get timetrackers for the task * * @param int $task_ids Tasks IDs * @return array $timetrackers */ public function timetrackerTask($task_id) { $task_id = (int) $task_id; $timetrackers = array(); $timetrackers_q = mysql_query("SELECT t.*, u.name as user_name FROM ".$this->getTablePrefix()."timetracker t LEFT JOIN ".$this->getTablePrefix()."user u ON t.user=u.ID WHERE task='".$task_id."'"); while($timetracker = mysql_fetch_assoc($timetrackers_q)){ $timetrackers[] = $timetracker; } return $timetrackers; } } ?>
true
65b69fa0bac50e287b611317b18c61280c4b37d5
PHP
roccotripaldi/wordpress-cribbage
/class.wp-cribbage.php
UTF-8
1,509
2.765625
3
[]
no_license
<?php class WP_Cribbage { function __construct() { add_action( 'init', array( $this, 'create_main_route' ) ); add_action( 'init', array( $this, 'maybe_flush_rewrites' ), 999 ); add_action( 'template_include', array( $this, 'maybe_serve_template' ), 99 ); } /** * Creates rewrites based on our app's url base - yoursite.com/play-cribbage */ function create_main_route() { add_rewrite_rule( '^app-route/?$','index.php?cribbage=/','top' ); add_rewrite_rule( '^app-route(.*)?','index.php?cribbage=$matches[1]','top' ); global $wp; $wp->add_query_var( 'cribbage' ); } /** * Flush rewrites when plugin is first loaded, and whenever the version changes * Note: `flush_rewrite_rules()` should be used sparingly */ function maybe_flush_rewrites() { $version = get_option( 'wp-cribbage_version', null ); if ( empty( $version ) || $version !== WP_CRIBBAGE_VERSION ) { flush_rewrite_rules(); update_option( 'wp_react_plugin_version', WP_CRIBBAGE_VERSION ); } } /** * If we are within our app route, register any js and css, and serve our main template */ function maybe_serve_template( $template ) { if ( empty( $GLOBALS['wp']->query_vars['cribbage'] ) ) return $template; wp_register_script( 'wp_cribbage', WP_CRIBBAGE_PATH . 'client/build/bundle.min.js' ); wp_register_style( 'wp_cribbage', WP_CRIBBAGE_PATH . 'client/css/app.min.css' ); $wp_cribbage_template = WP_CRIBBAGE_DIR . '/app.php'; return $wp_cribbage_template; } } new WP_Cribbage();
true
e9dce58106a4376b43d8986e585aa02c763ded94
PHP
chris-at-github/datamints-works
/Classes/Domain/Model/Container.php
UTF-8
2,690
2.71875
3
[]
no_license
<?php namespace Datamints\DatamintsWorks\Domain\Model; /*** * * This file is part of the "Datamints Works" Extension for TYPO3 CMS. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * (c) 2017 Christian Pschorr <[email protected]>, datamints GmbH * ***/ /** * Container */ class Container extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { /** * title * * @var string * @validate NotEmpty */ protected $title = ''; /** * card * * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Datamints\DatamintsWorks\Domain\Model\Card> */ protected $card = null; /** * __construct */ public function __construct() { //Do not remove the next line: It would break the functionality $this->initStorageObjects(); } /** * Initializes all ObjectStorage properties * Do not modify this method! * It will be rewritten on each save in the extension builder * You may modify the constructor of this class instead * * @return void */ protected function initStorageObjects() { $this->card = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); } /** * Returns the title * * @return string $title */ public function getTitle() { return $this->title; } /** * Sets the title * * @param string $title * @return void */ public function setTitle($title) { $this->title = $title; } /** * Adds a Card * * @param \Datamints\DatamintsWorks\Domain\Model\Card $card * @return void */ public function addCard(\Datamints\DatamintsWorks\Domain\Model\Card $card) { $this->card->attach($card); } /** * Removes a Card * * @param \Datamints\DatamintsWorks\Domain\Model\Card $cardToRemove The Card to be removed * @return void */ public function removeCard(\Datamints\DatamintsWorks\Domain\Model\Card $cardToRemove) { $this->card->detach($cardToRemove); } /** * Returns the card * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Datamints\DatamintsWorks\Domain\Model\Card> $card */ public function getCard() { return $this->card; } /** * Sets the card * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Datamints\DatamintsWorks\Domain\Model\Card> $card * @return void */ public function setCard(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $card) { $this->card = $card; } }
true
6ff73ec49eb1c9ac2ac59d89dbfdaffbb1a0cecc
PHP
myCMS/myCMS
/engine/classes/page/StaticContent.php
UTF-8
2,100
3.109375
3
[]
no_license
<?php /** * Used for define static content * * @package Engine * @subpackage Page * @see EngineCore * @author AlexK * @version 1.0 */ class StaticContent { /** * Constructor of class StaticContent */ public function __construct() { } /** * Return current year * * @param nothing * @throws no throws * @return current year */ public function getCopyright(){ $result = date("Y"); if ($result == COPYRIGHT_START_YEAR){ return $result; } else { return COPYRIGHT_START_YEAR."&ndash;".$result; } } /** * Return list of russian month names * * @param nothing * @throws no throws * @return list of russian month names */ public function getAllMonthesRu(){ return array("01" => "Январь", "02" => "Февраль", "03" => "Март", "04" => "Апрель", "05" => "Май", "06" => "Июнь", "07" => "Июль", "08" => "Август", "09" => "Сентябрь", "10" => "Октябрь", "11" => "Ноябрь", "12" => "Декабрь" ); } /** * Return list of english month names * * @param nothing * @throws no throws * @return list of english month names */ public function getAllMonthesEn(){ return array("01" => "Jan", "02" => "Feb", "03" => "Mar", "04" => "Apr", "05" => "May", "06" => "Jun", "07" => "Jul", "08" => "Aug", "09" => "Sep", "10" => "Okt", "11" => "Nov", "12" => "Dec" ); } } ?>
true
73d7611cc6d702be259232491729a279b2e71ad6
PHP
DenverBYF/php_algorithm
/Offer.php
UTF-8
24,376
3.796875
4
[]
no_license
<?php /** * Created by PhpStorm. * User: denverb * Date: 18/2/11 * Time: 上午10:27 * 剑指offer的PHP实现 */ /* * 在一个二维数组中,每一行都按照从左到右递增的顺序排序, * 每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 */ function Find($target, $array) { $columns = count($array[0]); //列数 $line = count($array); //行数 $tmp = $array[$line - 1][$columns - 1]; if ($target < $array[0][0] or $target > $array[$line - 1][$columns - 1]) { return false; } $cStart = 0; $lStart = $line - 1; while ($cStart < $columns and $lStart > -1){ $tmp = $array[$lStart][$cStart]; if ($tmp > $target) { $lStart = $lStart - 1; } elseif ($tmp < $target) { $cStart = $cStart + 1; } else { return true; } } return false; } /* * 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 * */ function replaceSpace($str) { return str_replace(' ', '%20', $str); } /* * 输入一个链表,从尾到头打印链表每个节点的值。 * */ /*class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } }*/ function printListFromTailToHead($head) { // $ret = []; if (empty($head)) { return $ret; } while (!empty($head)) { $ret[] = $head->val; $head = $head->next; } return array_reverse($ret); } /* * 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 * */ /*class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } }*/ function reConstructBinaryTree($pre, $vin) { // return buildTree($pre, $vin, 0, count($pre) - 1, 0, count($vin) - 1); } function buildTree($pre, $vin, $pStart, $pEnd, $vStart, $vEnd) { if ($pStart > $pEnd || $vStart > $vEnd) { return ; } $root = new TreeNode($pre[$pStart]); $rootIndex = array_keys($vin, $root->val)[0]; //跟节点在中序遍历中的位置 $leftLen = $rootIndex - $vStart; //左子树长度 $root->left = buildTree($pre, $vin, $pStart+ 1, $pStart + $leftLen, $vStart, $rootIndex - 1); //构建左子树 $root->right = buildTree($pre, $vin, $pStart + $leftLen + 1, $pEnd, $rootIndex + 1, $vEnd); //构建右子树 return $root; } /* * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 * */ $arr1 = []; $arr2 = []; function mypush($node) { // write code here global $arr1, $arr2; array_push($arr1, $node); } function mypop() { // write code here global $arr1, $arr2; if (!empty($arr2)) { return array_pop($arr2); } else { while (!empty($arr1)) { array_push($arr2, array_pop($arr1)); } return array_pop($arr2); } } /* * 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 * 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 * 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 * NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 * */ function minNumberInRotateArray($rotateArray) { // write code here $low = 0; $high = count($rotateArray) - 1; while ($low < $high) { $mid = intval(($low + $high) / 2); if ($high - $low == 1) { return $rotateArray[$high]; } if ($rotateArray[$mid] >= $rotateArray[$low]) { $low = $mid; } elseif ($rotateArray[$mid] <= $rotateArray[$high]) { $high = $mid; } } return 0; } /* * 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39 * */ function Fibonacci($n) { $ret = []; $ret[0] = 0; $ret[1] = 1; for ($i = 2; $i < $n + 1 ; $i++) { $ret[] = $ret[$i - 1] + $ret[$i - 2]; } return $ret[$n]; } /* * 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 * */ function jumpFloor($number) { return Fib($number); } function Fib($n) { $ret = []; $ret[0] = 0; $ret[1] = 1; $ret[2] = 2; for ($i = 3; $i < $n + 1; $i++) { $ret[] = $ret[$i - 1] + $ret[$i - 2]; } return $ret[$n]; } /* * 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 * */ function jumpFloorII($number) { if ($number == 0) { return 0; } if ($number == 1) { return 1; } if ($number > 1) { return 2*jumpFloorII($number - 1); } } /* * 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? * */ function rectCover($number) { // write code here return Fib2($number); } function Fib2($number) { $ret = []; $ret[0] = 0; $ret[1] = 1; $ret[2] = 2; for ($i = 3; $i < $number + 1; $i++) { $ret[] = $ret[$i - 1] + $ret[$i - 2]; } return $ret[$number]; } /* * 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 * */ function NumberOf1($n) { // write code here $count = 0; if($n < 0){ // 处理负数 $n = $n&0x7FFFFFFF; ++$count; } while($n != 0){ $count++; $n = $n & ($n-1); } return $count; } /* * 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 * */ function Power($base, $exponent) { // write code here return pow($base, $exponent); } /* * 输入一个整数数组,实现一个函数来调整该数组中数字的顺序, * 使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分, * 并保证奇数和奇数,偶数和偶数之间的相对位置不变。 * */ function reOrderArray($array) { // write code here $a1 = []; $a2 = []; foreach ($array as $item) { if ($item % 2 == 0) { $a1[] = $item; } else { $a2[] = $item; } } return array_merge($a2, $a1); } /* * 输入一个链表,输出该链表中倒数第k个结点。 * 注:两个指针进行遍历,第一个到达k时,第二个开始。 * */ /*class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } }*/ function FindKthToTail($head, $k) { // write code here if ($k == 0) { return []; } $c = 0; $node1 = $head; $node2 = $head; while (!empty($node1->next)) { $c += 1; $node1 = $node1->next; if ($c >= $k) { $node2 = $node2->next; } } if ($k > $c + 1) { return []; } return $node2; } /* * 输入一个链表,反转链表后,输出链表的所有元素。 * */ /*class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } }*/ function ReverseList($pHead) { // write code here $pre = null; $next = null; $node = $pHead; while (!empty($node)) { $next = $node->next; $node->next = $pre; $pre = $node; $node = $next; } return $pre; } /* * 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 * */ /*class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } }*/ function Merge($pHead1, $pHead2) { // write code here if (empty($pHead1)) { return $pHead2; } if (empty($pHead2)) { return $pHead1; } if ($pHead1->val < $pHead2->val) { $head = $pHead1; $head->next = Merge($pHead1->next, $pHead2); } else { $head = $pHead2; $head->next = Merge($pHead1, $pHead2->next); } return $head; } /* * 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) * */ /*class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } }*/ function HasSubtree($pRoot1, $pRoot2) { // write code here if (empty($pRoot2) or empty($pRoot1)) { return false; } return (judge($pRoot1, $pRoot2) or judge($pRoot1->left, $pRoot2) or judge($pRoot1->right, $pRoot2)); } function judge($pRoot1, $pRoot2) { if (empty($pRoot2)) { return true; } if (empty($pRoot1)) { return false; } if ($pRoot1->val !== $pRoot2->val) { return false; } return (judge($pRoot1->left, $pRoot2->left) and judge($pRoot1->right, $pRoot2->right)); } /* * 操作给定的二叉树,将其变换为源二叉树的镜像 * */ /*class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } }*/ function Mirror(&$root) { // write code here $stack = []; $stack[] = $root; while (!empty($stack)) { $node = array_pop($stack); $tmp = $node->left; $node->left = $node->right; $node->right = $tmp; if (!empty($node->left)) { $stack[] = $node->left; } if (!empty($node->right)) { $stack[] = $node->right; } } } /* * 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, * 例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 * 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. * */ function printMatrix($matrix) { // write code here $row = count($matrix); $column = count($matrix[0]); $lu = 0; $ru = $column - 1; $ld = 0; $rd = $row - 1; $ret = []; while (($lu < $ru) && ($ld < $rd)) { for ($i = $lu; $i < $ru; $i++) { $ret[] = $matrix[$lu][$i]; } for ($i = $lu; $i < $rd; $i++) { $ret[] = $matrix[$i][$ru]; } for ($i = $ru; $i > $lu; $i--) { $ret[] = $matrix[$rd][$i]; } for ($i = $rd; $i > $lu; $i--) { $ret[] = $matrix[$i][$lu]; } $lu++; $ru--; $rd--; $ld++; } if ($lu == $ru and $ld < $rd) { //剩一列 for ($i = $lu; $i <= $rd; $i++) { $ret[] = $matrix[$i][$lu]; } } if ($lu < $ru and $rd == $ld) { //剩一行 for ($i = $lu; $i <= $ru; $i++) { $ret[] = $matrix[$lu][$i]; } } if ($lu == $ru and $rd == $ld ){ $ret[] = $matrix[$lu][$ld]; } return $ret; } /* * 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 * */ $stack = []; function mypush2($node) { global $stack; // write code here array_push($stack, $node); } function mypop2() { global $stack; // write code here return array_pop($stack); } function mytop() { global $stack; // write code here return $stack[count($stack) - 1]; } function mymin() { global $stack; // write code here return min($stack); } /* * 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。 * 假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列, * 但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的) * */ function IsPopOrder($pushV, $popV) { // write code here $stack = []; $len = count($pushV); $j = $i = 0; //$i控制输入栈, $j控制输出栈 while ($j < $len) { while (empty($stack) || $stack[count($stack) - 1] != $popV[$j]) { if ($i > $len - 1) { break; } $stack[] = array_shift($pushV); $i ++; } if ($stack[count($stack) - 1] != $popV[$j]) { break; } array_pop($stack); $j ++; } if ($j != $len || !empty($stack)) { return false; } else { return true; } } /* * 从上往下打印出二叉树的每个节点,同层节点从左至右打印。 * */ /*class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } }*/ function PrintFromTopToBottom($root) { // write code here $stack = []; //利用队列进行层序遍历 $stack[] = $root; $ret = []; while (!empty($stack)) { $node = array_shift($stack); $ret[] = $node->val; if (!empty($node->left)) { $stack[] = $node->left; } if (!empty($node->right)) { $stack[] = $node->right; } } return $ret; } /* * 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。 * 如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。 * */ function VerifySquenceOfBST($sequence) { // write code here if (empty($sequence)) { return false; } return judge1($sequence, 0, count($sequence) - 1); } function judge1($root, $start, $end) { $count = 0; if ($end - $start <= 1) { return true; } for ($i = 0; $i < $end; $i ++) { if ($root[$i] > $root[$end]) { break; } $count += 1; } for ($j = $count; $j < $end; $j ++) { if ($root[$j] < $root[$end]) { return false; } } $left = true; $right = true; if ($count > 0){ $left = judge1($root, $start, $count - 1); } if ($count < count($root) - 1) { $right = judge1($root, $count, $end - 1); } return ($left && $right); } /* * 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。 * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 * */ class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } } function FindPath($root, $expectNumber) { if($expectNumber == 0 || empty($root) || $root->val > $expectNumber) { return []; } $stack = []; $pathRet = []; getPath($pathRet, $stack, $root, $expectNumber); return $pathRet; } function getPath(&$pathRet, &$stack, $root, $expectNumber) { if (empty($root->left) && empty($root->right)) { $isLeaf = true; } $stack[] = $root->val; if ($root->val === $expectNumber && isset($isLeaf)) { $pathRet[] = $stack; } if (!empty($root->left)) { getPath($pathRet, $stack, $root->left, $expectNumber - $root->val); } if (!empty($root->right)) { getPath($pathRet, $stack, $root->right, $expectNumber - $root->val); } array_pop($stack); } /* * 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点, * 另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。 * (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) * */ class RandomListNode{ var $label; var $next = NULL; var $random = NULL; function __construct($x){ $this->label = $x; } } function MyClone($pHead) { // write code here if (empty($pHead)) { return null; } $pNode = $pHead; $nextNode = $pNode->next; //复制 while (!empty($pNode)) { $tmp = new RandomListNode($pNode->label); $tmp->next = $nextNode; $pNode->next = $tmp; $pNode = $tmp->next; if (!empty($pNode)) { $nextNode = $pNode->next; } } //random指针复制 $pNode = $pHead; while (!empty($pNode)) { if (!empty($pNode->random)) { $pNode->next->random = $pNode->random; } else { $pNode->next->random = null; } $pNode = $pNode->next->next; } //拆分 $pNode = $pHead; $cloneHead= $pHead->next; $cloneNode = $cloneHead; while (!empty($pNode)) { $pNode->next = $cloneNode->next; $pNode = $pNode->next; if (!empty($pNode)) { $cloneNode->next = $pNode->next; $cloneNode = $cloneNode->next; } } return $cloneHead; } /* * 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。 * */ /*class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } }*/ function Convert($pRootOfTree) { // write code here $headNode = convertNode($pRootOfTree, null); while (!empty($headNode) && !empty($headNode->left)) { $headNode = $headNode->left; } return $headNode; } function convertNode($root, $lastNode) { if (empty($root)) return null; if (!empty($root->left)) { $lastNode = convertNode($root->left, $lastNode); } $root->left = $lastNode; if (!empty($lastNode)) { $lastNode->right = $root; } $lastNode = $root; if (!empty($root->right)) { $lastNode = convertNode($root->right, $lastNode); } return $lastNode; } /* * 输入一个字符串,按字典序打印出该字符串中字符的所有排列。 * 例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 * */ function Permutation($str) { // write code here if (empty($str)) { return []; } $ret = []; $len = count($str); getPermutation($ret, $str, 0, $len); return $ret; } function getPermutation(&$ret, $str, $index, $len) { if ($len == $index) { $ret[] = $str; return ; } for ($i = $index; $i < $len; ++ $i) { if ($i != $index && $str[$i] == $str[$index]) continue; $tmp = $str[$i]; $str[$i] = $str[$index]; $str[$index] = $tmp; getPermutation($ret, $str, $index + 1, $len); $tmp = $str[$i]; $str[$i] = $str[$index]; $str[$index] = $tmp; } } /* * 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。 * */ function GetLeastNumbers_Solution($input, $k) { // write code here if ($k > count($input)) { return []; } sort($input); return array_slice($input,0 , $k); } /* * 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 * 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。 * */ function MoreThanHalfNum_Solution($numbers) { // write code here $t = intval(count($numbers)/2); $count = array_count_values($numbers); foreach ($count as $key => $value) { if ($value > $t) { return $key; } } return 0; } /* * HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和, * 当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢? * 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住?(子向量的长度至少是1) * */ function FindGreatestSumOfSubArray($array) { // write code here $tmp = $array[0]; $max = $array[0]; for ($i = 1; $i < count($array); $i++) { if ($tmp > 0) { $tmp += $array[$i]; } else { $tmp = $array[$i]; } if ($tmp > $max) { $max = $tmp; } } return $max; } /* * 求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数? * 为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次, * 但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。 * */ function NumberOf1Between1AndN_Solution($n) { // write code here $ret = 0; $base = 1; $round = $n; while ($round > 0) { $weight = $round % 10; $round = intval($round/10); $ret += $round * $base; if ($weight == 1) { $ret += ($n % $base) + 1; } else if ($weight > 1) { $ret += $base; } $base *= 10; } return $ret; } /* * 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 * 例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。 * */ function PrintMinNumber($numbers) { // write code here for ($i = 0; $i < count($numbers) - 1; $i++) { $flag = true; for ($j = $i + 1; $j < count($numbers); $j++) { if (parpre($numbers[$i], $numbers[$j])) { $flag = false; $tmp = $numbers[$i]; $numbers[$i] = $numbers[$j]; $numbers[$j] = $tmp; } } if ($flag) { break; } } return implode("", $numbers); } function parpre($num1, $num2) { $n1 = (string)$num1 . (string)$num2; $n2 = (string)$num2 . (string)$num1; return intval($n1) > intval($n2); } /* * 把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 * 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 * */ function GetUglyNumber_Solution($index) { // write code here $ret = []; $ret[] = 1; if ($index < 1) { return 0; } $j = $k = $l =0; for ($i = 1; $i < $index; $i++) { $ret[$i] = min(min($ret[$j]*2, $ret[$k]*3), $ret[$l]*5); if ($ret[$i] == $ret[$j]*2) { $j +=1; } if ($ret[$i] == $ret[$k]*3) { $k +=1; } if ($ret[$i] == $ret[$l]*5) { $l +=1; } } return $ret[$index - 1]; } /* * 在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置 * */ function FirstNotRepeatingChar($str) { // write code here if (strlen($str) == 0) { return -1; } $str = str_split($str); $count = array_count_values($str); foreach ($count as $key => $value) { if ($value == 1) { return array_search($key, $str); } } } /* * 输入两个链表,找出它们的第一个公共结点。 * */ /*class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } }*/ function FindFirstCommonNode($pHead1, $pHead2) { // write code here $count1 = $count2 = 0; $p1 = $pHead1; $p2 = $pHead2; while (!empty($pHead1)) { $count1 += 1; $pHead1 = $pHead1->next; } while (!empty($pHead2)) { $count2 += 1; $pHead2 = $pHead2->next; } if ($count1 > $count2) { $t = $count1 - $count2; $pLong = $p1; $pShort = $p2; } else { $t = $count2 - $count1; $pLong = $p2; $pShort = $p1; } for ($i = 0; $i < $t; $i++) { $pLong = $pLong->next; } while (!empty($pLong) and !empty($pShort)) { if ($pLong === $pShort) { return $pLong; } $pLong = $pLong->next; $pShort = $pShort->next; } return false; } /* * 统计一个数字在排序数组中出现的次数。 * */ function GetNumberOfK($data, $k) { // write code here $data = array_count_values($data); if (!in_array($k, array_keys($data))) { return 0; } else { return $data[$k]; } } /* * 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 * */ /*class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } }*/ function TreeDepth($pRoot) { // write code here if (empty($pRoot)) { return 0; } $left = TreeDepth($pRoot->left); $right = TreeDepth($pRoot->right); $depth = $left > $right?$left:$right; return 1 + $depth; } /* * 输入一棵二叉树,判断该二叉树是否是平衡二叉树。 * */ /*class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } }*/ function IsBalanced_Solution($pRoot) { // write code here if (empty($pRoot)) { return true; } $left = depth($pRoot->left); $right = depth($pRoot->right); if (max($left,$right) - min($left,$right) > 1) { return false; } return IsBalanced_Solution($pRoot->left) && IsBalanced_Solution($pRoot->right); } function depth($root) { if (empty($root)) { return 0; } $left = depth($root->left); $right = depth($root->right); $depth = $left > $right?$left:$right; return 1 + $depth; } /* * 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。 * */ function FindNumsAppearOnce($array) { // write code here // return list, 比如[a,b],其中ab是出现一次的两个数字 $array = array_count_values($array); asort($array); $key = array_keys($array); return array_slice($key, 0, 2); }
true
76a02a5623bb7209d270073b404f3652b457076b
PHP
halaei/telegram-bot
/tests/FileUpload/InputFileTest.php
UTF-8
1,150
2.796875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace Telegram\Bot\Tests\FileUpload; use PHPUnit\Framework\TestCase; use Telegram\Bot\FileUpload\FileId; use Telegram\Bot\FileUpload\HttpUrl; use Telegram\Bot\FileUpload\InputFile; use Telegram\Bot\FileUpload\InputStream; class InputFileTest extends TestCase { public function test_input_stream_open() { $file = new InputStream('This is test.'); $stream = $file->open(); $this->assertMatchesRegularExpression('/^([0-9a-zA-Z]{16})$/', $stream->getMetadata('uri')); $this->assertEquals('This is test.', $stream->getContents()); } public function test_input_file_open() { $path = __DIR__ . '/test.txt'; $file = new InputFile($path); $stream = $file->open(); $this->assertEquals($path, $stream->getMetadata('uri')); $this->assertEquals('This is test!', $stream->getContents()); } public function test_file_id_open() { $this->assertEquals(123, (new FileId(123))->open()); } public function test_http_url_open() { $this->assertEquals('http://google.com', (new HttpUrl('http://google.com'))->open()); } }
true
a73aa3be02289a1851e9eb2a47610ef938af4866
PHP
DivanteLtd/pimcore-enrichment-progress
/src/Controller/EnrichmentController.php
UTF-8
1,646
2.515625
3
[]
no_license
<?php /** * @date       23.07.2021 * @author Jakub Płaskonka <[email protected]> * @copyright   Copyright (c) 2021 DIVANTE (http://divante.com/) */ declare(strict_types=1); namespace EnrichmentProgressBundle\Controller; use EnrichmentProgressBundle\EnrichmentProgress\EnrichmentProgressService; use Pimcore\Bundle\AdminBundle\Controller\AdminController; use Pimcore\Bundle\AdminBundle\HttpFoundation\JsonResponse; use Pimcore\Model\DataObject; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; /** * Class EnrichmentController * * @package Divante\EnrichmentBundle\Controller * @Route("/enrichment") */ class EnrichmentController extends AdminController { /** * @var EnrichmentService */ private $service; /** * @param EnrichmentProgressService $service */ public function __construct(EnrichmentProgressService $service) { $this->service = $service; } /** * @param string $id * * @return JsonResponse * @Route("/progress/{id}", requirements={"id": "[1-9][0-9]*"}) * @Method({"GET"}) */ public function progressAction(string $id): JsonResponse { $object = DataObject::getById($id); if (!$object) { return $this->adminJson([ 'completed' => 0, 'total' => 0, ]); } $progress = $this->service->getEnrichmentProgress($object); return $this->adminJson([ 'completed' => $progress->getCompleted(), 'total' => $progress->getTotal(), ]); } }
true
517e4ecb8edef24a3be1d9e0501f3b1d22683ff7
PHP
davidz1113/backend_tienda
/producto.php
UTF-8
1,464
2.890625
3
[]
no_license
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ require '../backend_tienda/conexion.php'; class Producto{ function __construct() { } public static function obtenerTodosProductos(){ $consulta = 'select * from producto'; try { $sentencia = Database::getInstance()->getDb()->prepare($consulta); $sentencia->execute(); return $sentencia->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $ex) { return false; } } public static function insertarActualizarProducto($arrayObjs) { $sql = "insert into producto(idproducto,unidades) values "; //rECORREMOS EL ARRAY Y SE ARMA LA CONSULTA INSERT POR CADA OBJETO foreach ($arrayObjs as $obj) { $sql = $sql . "(" . $obj["idproducto"] . "," . $obj["unidades"] . "),"; } //aL FINAL SUBSTRAEMOS LA CADENA LA ULTIMA COMA Y LE AGREGAMOS UN PUNTO Y COMA AL FINAL $sql = substr($sql, 0, -1) . " ON DUPLICATE KEY UPDATE unidades=VALUES(unidades);"; //echo $sql; //return; try { $sentencia = Database::getInstance()->getDb()->prepare($sql); return $sentencia->execute(); } catch (Exception $ex) { return false; } } }
true
19a2c63a118086a7096a2f150f17a167fbf90ba7
PHP
rkarkut/slack-api-package
/src/lib/Oauth.php
UTF-8
1,096
2.8125
3
[]
no_license
<?php namespace Rkarkut\Slack\lib; use Guzzle\Http\Client as GuzzleClient; class Oauth extends Slack { /** * Getting access to an application. * * * @param $clientId * @param $clientSecret * @param $code * @param $redirectUrl * * @return object * @throws \Exception */ public function access($clientId, $clientSecret, $code, $redirectUrl) { $params = array( 'client_id' => $clientId, 'client_secret' => $clientSecret, 'code' => $code, 'redirect_uri' => $redirectUrl ); $client = new GuzzleClient($this->url); $request = $client->post('/api/oauth.access', null, $params); $response = $request->send(); $status = $response->getStatusCode(); if ($status !== 200) { throw new \Exception('Api not working!'); } $result = (object) json_decode($response->getBody(true)); if ($result->ok !== true) { throw new \Exception('Access denied.'); } return $result; } }
true
453f2c7dd279415d2fb501b3e5a486133eb020dc
PHP
szaboferee/esprimaPHP
/src/Node/Statement/WithStatement.php
UTF-8
629
2.96875
3
[]
no_license
<?php namespace EsprimaPhp\Node\Statement; use EsprimaPhp\Node\Statement; use EsprimaPhp\Parser\Syntax; class WithStatement extends Statement { /** * @var string */ public $type = Syntax::WITH_STATEMENT; /** * @var Expression */ public $object; /** * @var Statement; */ public $body; /** * @param EsprimaPHP $esprima * @param Expression $object * @param Statement $body */ public function finish($esprima, $object, $body) { $this->object = $object; $this->body = $body; return $this->finishNode($esprima); } }
true
c29e5ecf2d983c698d908d22a8505fafee79e57f
PHP
alban30/PHP
/TD6/controller/ControllerTrajet.php
UTF-8
3,321
2.5625
3
[]
no_license
<?php require_once (File::build_path(array("model", "ModelTrajet.php"))); // chargement du modèle class ControllerTrajet { protected static $object = "trajet"; public static function readAll() { $tab_t = ModelTrajet::selectAll(); //appel au modèle pour gerer la BD $pagetitle = "Liste de trajets"; $controller = "trajet"; $view = "list"; require (File::build_path(array("view", "view.php"))); //"redirige" vers la vue } public static function read() { $t = Modeltrajet::select($_GET['id']); //appel au modèle pour gerer la BD if(!$t) { $pagetitle = "Erreur"; $controller = "trajet"; $view = "error"; } else { $pagetitle = "Affichage d'un trajet"; $controller = "trajet"; $view = "detail"; } require (File::build_path(array("view", "view.php"))); //"redirige" vers la vue } public static function create() { $t = new ModelTrajet(); $modifier = "required"; $target_action = "created"; if(!$t) { $pagetitle = "Erreur"; $view = "error"; } else { $pagetitle = "Création d'un trajet"; $view = "update"; } require (File::build_path(array("view", "view.php"))); //"redirige" vers la vue } public static function created() { ModelTrajet::save(array("id" => $_POST['id'], "depart" => $_POST['depart'], "arrivee" => $_POST['arrivee'], "date" => $_POST['date'], "nbplaces" => $_POST['nbplaces'], "prix" => $_POST['prix'], "conducteur_login" => $_POST['conducteur_login'])); $tab_t = ModelTrajet::selectAll(); $pagetitle = "Trajet créé"; $view = "created"; require (File::build_path(array("view", "view.php"))); //"redirige" vers la vue } public static function update() { $t = Modeltrajet::select($_GET['id']); $modifier = "readonly"; $target_action = "updated"; if(!$t) { $pagetitle = "Erreur"; $view = "error"; } else { $pagetitle = "Modification d'un trajet"; $view = "update"; } require (File::build_path(array("view", "view.php"))); //"redirige" vers la vues } public static function updated() { ModelTrajet::update(array("id" => $_POST['id'], "depart" => $_POST['depart'], "arrivee" => $_POST['arrivee'], "date" => $_POST['date'], "nbplaces" => $_POST['nbplaces'], "prix" => $_POST['prix'], "conducteur_login" => $_POST['conducteur_login'])); $tab_t = Modeltrajet::selectAll(); $pagetitle = "Trajet modifié"; $view = "updated"; require (File::build_path(array("view", "view.php"))); //"redirige" vers la vue } public static function delete() { $id = $_GET['id']; ModelTrajet::delete($id); $tab_t = ModelTrajet::selectAll(); if(!$id) { $pagetitle = "Erreur"; $view = "error"; } else { $pagetitle = "Suppression d'un trajet"; $view = "deleted"; } require (File::build_path(array("view", "view.php"))); //"redirige" vers la vues } } ?>
true
b961e363ef5804159b246027140f4338e1faef77
PHP
borishaw/itn-quotegen
/scripts/update_fcl_price_table.php
UTF-8
819
2.53125
3
[]
no_license
<?php /*require '../vendor/autoload.php'; DB::$user = 'root'; DB::$password = 'root'; DB::$dbName = 'itn_quote_gen'; use League\Csv\Reader; $csv = Reader::createFromPath('fcl_price_table.csv'); $result = $csv->fetchAll(); foreach ($result as $row) { $city = $row[0]; $province = $row[1]; $country = $row[2]; $net = $row[3]; $zone = $row[4]; $margin = $row[5]; $sold = $row[6]; $per = $row[7]; try { DB::insertUpdate('fcl_price_table', [ 'city' => $city, 'province' => $province, 'country' => $country, 'net' => $net, 'zone' => $zone, 'margin' => $margin, 'sold' => $sold, 'per' => $per ]); } catch (Exception $e) { print $e->getMessage(); } }*/
true
51d70ff9b7bc99be74a04cbf7bb198bb13777426
PHP
amansingh95/online_exam
/exam_timer.php
UTF-8
2,058
2.71875
3
[ "MIT" ]
permissive
<?php session_start(); if($_SESSION['std']!="") { ?> <?php /*//A: RECORDS TODAY'S Date And Time echo "month".$month =date('m'); echo "days".$days =date('d') ; echo "hour".$hours =date('H') ; echo "minute".$min =date('i') ; echo "second".$sec =date('s') ; if($sec==10){echo "govinda";} $today = time(); //B: RECORDS Date And Time OF YOUR EVENT $event = mktime(0,0,0,4,13,2017); //C: COMPUTES THE DAYS UNTIL THE EVENT. $countdown = round(($event - $today)/86400); //D: DISPLAYS COUNTDOWN UNTIL EVENT echo "$countown days until Christmas";*/ ?> <?php /*?> //10 day timer // insert into db include("admin_connection.php"); $time_now = date("Y-m-d H:i:s"); //+10 days = 864000 seconds $new_time = strtotime($time_now)+864000; $new_timestamp = date("Y-m-D H:i:s", $new_time); mysql_query("insert into end_time (time) values ($new_timestamp)"); <?php */?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>EXAM</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script language="JavaScript"> TargetDate ="4/16/2017 3:00 AM"; BackColor = "palegreen"; ForeColor = "navy"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%H%% Hours, %%M%% Minutes, %%S%% Seconds."; FinishMessage = "Time Over!"; </script> <script language="JavaScript" src="//scripts.hashemian.com/js/countdown.js"></script> <style type="text/css"> <!-- .style1 { font-size: 16px; font-weight: bold; background-color: #FFFFFF; color: #591434; } .style2 { color: #FFFFFF; font-weight: bold; } .style3 {color: #FFFFFF} .style4 {font-size: xx-large} .style6 { font-size: xx-large; font-weight: bold; color: #591434; } .style8 { font-size: 14px; font-style: italic; color: #000000; } --> </style> </head> <body bgcolor="#FFFFCC" > </body> </html> <?php } else{ header("location:home.php"); } ?>
true
02423975680c33f3579bae27932db24eafe5de40
PHP
kristiankeep/decibel-framework
/stream/DHttpStream.php
UTF-8
836
2.875
3
[ "MIT" ]
permissive
<?php // // Copyright (c) 2008-2016 Decibel Technology Limited. // namespace app\decibel\stream; /** * A stream to which data can be written over HTTP. * * @author Timothy de Paris */ interface DHttpStream extends DWritableStream { /** * Flushes the content of the stream to the client. * * @return void */ public function flush(); /** * Sets the value of a header to be sent to the client. * * @param string $header Name of the header. * @param string $value Header value. * * @return void */ public function setHeader($header, $value = null); /** * Sets the value of a header to be sent to the client. * * @param array $headers array of $header => $value tuples * */ public function setHeaders(array $headers); }
true
a3bca224e6c48e27a9de5edd342861ed0df6a2f8
PHP
eabatalov/educational-gaming-platform
/website/protected/models/entities/UserSkill.php
UTF-8
1,403
3.359375
3
[]
no_license
<?php /** * Storage information about level of particular user skill * * @author eugene */ class UserSkill { /* * @throws InvalidArgumentException */ function __construct($userId, $skillId, $value) { $this->setUserId($userId); $this->setSkillId($skillId); $this->setValue($value); } public function getUserId() { return $this->userId; } public function getSkillId() { return $this->skillId; } public function getValue() { return $this->value; } public function setUserId($userId) { self::validateUserId($userId); $this->userId = $userId; } public function setSkillId($skillId) { self::validateSkillId($skillId); $this->skillId = $skillId; } public function setValue($value) { TU::throwIfNot(is_int($value), TU::INVALID_ARGUMENT_EXCEPTION, "value must be integer"); $this->value = $value; } public static function validateUserId($userId) { TU::throwIfNot(is_numeric($userId), TU::INVALID_ARGUMENT_EXCEPTION, "user id must be integer"); } public static function validateSkillId($skillId) { TU::throwIfNot(is_numeric($skillId), TU::INVALID_ARGUMENT_EXCEPTION, "skill id must be integer"); } //Numeric private $userId; //Numeric private $skillId; //Int private $value; }
true
21ac2db0b9be261643098e4815171aa919b12d6b
PHP
tipsypastels/relibrary
/ratings.php
UTF-8
945
2.625
3
[]
no_license
<?php include('header.php') ?> <?php if (empty($_GET)) { redirect_to('index'); exit(); } $ratings = BookRating::where($_GET); $book = null; if (isset($_GET['book_id'])) { $book = Book::find(['id' => $_GET['book_id']]); } ?> <main> <h1 class="title">Ratings</h1> <?php if ($book && signed_in()): ?> <?php render_partial('rate', ['book' => $book]); ?> <?php endif; ?> <section id="page-buttons"> <a href="index.php" class="btn block"> Back Home </a> <?php if ($book): ?> <a href="<?php echo $book->link() ?>" class="btn block"> Back to Book </a> <?php endif; ?> </section> <?php if ($ratings): ?> <?php foreach($ratings as $rating) { render_partial('rating', ['rating' => $rating]); } ?> <?php else: ?> No ratings found for the given parameters. <?php endif; ?> </main> <?php include('footer.php') ?>
true
dd39a72d2ce764a7af0f5508d6c894240b587acb
PHP
andparsons/mage-app-start
/app/code/Magento/VisualMerchandiser/Model/Sorting/SortInterface.php
UTF-8
551
2.515625
3
[]
no_license
<?php namespace Magento\VisualMerchandiser\Model\Sorting; /** * Interface SortInterface * @package Magento\VisualMerchandiser\Model\Sorting * @api * @since 100.0.2 */ interface SortInterface { /** * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection * @return \Magento\Catalog\Model\ResourceModel\Product\Collection */ public function sort( \Magento\Catalog\Model\ResourceModel\Product\Collection $collection ); /** * @return string */ public function getLabel(); }
true
50252e8b3b69660105c15daabdfb33797fcbcae7
PHP
web-vision/magento-high-speed-import
/fw/Cemes/Helper/Timer.inc.php
UTF-8
2,345
3.25
3
[]
no_license
<?php if (!$GLOBALS['CEMES']['ACTIVE']) die('Framework ist nicht aktiv'); /* * Singleton-Klasse * * @package Cemes-Framework * @version 1.0.0 * @author Tim Werdin * * Cemes_Config liest diverse Config dateien und kann sie auch beschreiben */ class Cemes_Helper_Timer { /** * is timer already running? if not hold the start time * * @var boolean */ private $_running = false; /** * saves the elapsed time * * @var float */ private $_elapsed = 0.; /** * function to start the timer * * @return void */ public function start() { if($this->_running !== false) { trigger_error('Timer has already been started', E_USER_NOTICE); return false; } else $this->_running = microtime(true); } /** * function to stop the timer * * @return void */ public function stop() { if($this->_running === false) { trigger_error('Timer has already been stopped/paused or has not been started', E_USER_NOTICE); return false; } else { $this->_elapsed += microtime(true) - $this->_running; $this->_running = false; } } /** * reset the timer * * @return void */ public function reset() { $this->_elapsed = 0.; } /** * function to get the summed time in human readable format * * @value int * @return int|float */ public function get() { // stop timer if it is still running if($this->_running !== false) { trigger_error('Forcing timer to stop', E_USER_NOTICE); $this->stop(); } list($s, $ms) = explode('.', $this->_elapsed); $time = '0.'.$ms; if($s != 0) { $m = (int)($s / 60); $time = $s.'.'.$ms; } if($m != 0) { $s -= $m * 60; $h = (int)($m / 60); $time = $m.':'.$s.'.'.$ms; } if($h != 0) { $m -= $h * 60; $time = $h.':'.$m.':'.$s.'.'.$ms; } return $time; } /** * The elapsed time in milliseconds. * * @return float */ public function getElapsed() { return $this->_elapsed; } }
true
dd7530877d5c30972a2b1c82662447c3bd19281e
PHP
softscripts/WWEX-SpeedShip
/Rate/Options/MynewServiceStructRateServiceOptions.php
UTF-8
8,773
2.671875
3
[]
no_license
<?php /** * File for class MynewServiceStructRateServiceOptions * @author Soft Scripts Team <[email protected]> * @version 20140325-01 * @date 2014-03-29 */ /** * This class stands for MynewServiceStructRateServiceOptions originally named RateServiceOptions * Meta informations extracted from the WSDL * - from schema : http://app6.wwex.com:8080/s3fWebService/services/SpeedShip2Service?wsdl * @author Soft Scripts Team <[email protected]> * @version 20140325-01 * @date 2014-03-29 */ class MynewServiceStructRateServiceOptions extends MynewServiceWsdlClass { /** * The additionalParameters * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var MynewServiceStructAdditionalParameters */ public $additionalParameters; /** * The carbonNeutralIndicator * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var string */ public $carbonNeutralIndicator; /** * The codIndicator * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var string */ public $codIndicator; /** * The confirmDeliveryIndicator * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var string */ public $confirmDeliveryIndicator; /** * The deliveryOnSatIndicator * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var string */ public $deliveryOnSatIndicator; /** * The handlingChargeIndicator * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var string */ public $handlingChargeIndicator; /** * The returnLabelIndicator * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var string */ public $returnLabelIndicator; /** * The schedulePickupIndicator * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var string */ public $schedulePickupIndicator; /** * The shipmentType * Meta informations extracted from the WSDL * - minOccurs : 0 * - nillable : true * @var string */ public $shipmentType; /** * Constructor method for RateServiceOptions * @see parent::__construct() * @param MynewServiceStructAdditionalParameters $_additionalParameters * @param string $_carbonNeutralIndicator * @param string $_codIndicator * @param string $_confirmDeliveryIndicator * @param string $_deliveryOnSatIndicator * @param string $_handlingChargeIndicator * @param string $_returnLabelIndicator * @param string $_schedulePickupIndicator * @param string $_shipmentType * @return MynewServiceStructRateServiceOptions */ public function __construct($_additionalParameters = NULL,$_carbonNeutralIndicator = NULL,$_codIndicator = NULL,$_confirmDeliveryIndicator = NULL,$_deliveryOnSatIndicator = NULL,$_handlingChargeIndicator = NULL,$_returnLabelIndicator = NULL,$_schedulePickupIndicator = NULL,$_shipmentType = NULL) { parent::__construct(array('additionalParameters'=>$_additionalParameters,'carbonNeutralIndicator'=>$_carbonNeutralIndicator,'codIndicator'=>$_codIndicator,'confirmDeliveryIndicator'=>$_confirmDeliveryIndicator,'deliveryOnSatIndicator'=>$_deliveryOnSatIndicator,'handlingChargeIndicator'=>$_handlingChargeIndicator,'returnLabelIndicator'=>$_returnLabelIndicator,'schedulePickupIndicator'=>$_schedulePickupIndicator,'shipmentType'=>$_shipmentType),false); } /** * Get additionalParameters value * @return MynewServiceStructAdditionalParameters|null */ public function getAdditionalParameters() { return $this->additionalParameters; } /** * Set additionalParameters value * @param MynewServiceStructAdditionalParameters $_additionalParameters the additionalParameters * @return MynewServiceStructAdditionalParameters */ public function setAdditionalParameters($_additionalParameters) { return ($this->additionalParameters = $_additionalParameters); } /** * Get carbonNeutralIndicator value * @return string|null */ public function getCarbonNeutralIndicator() { return $this->carbonNeutralIndicator; } /** * Set carbonNeutralIndicator value * @param string $_carbonNeutralIndicator the carbonNeutralIndicator * @return string */ public function setCarbonNeutralIndicator($_carbonNeutralIndicator) { return ($this->carbonNeutralIndicator = $_carbonNeutralIndicator); } /** * Get codIndicator value * @return string|null */ public function getCodIndicator() { return $this->codIndicator; } /** * Set codIndicator value * @param string $_codIndicator the codIndicator * @return string */ public function setCodIndicator($_codIndicator) { return ($this->codIndicator = $_codIndicator); } /** * Get confirmDeliveryIndicator value * @return string|null */ public function getConfirmDeliveryIndicator() { return $this->confirmDeliveryIndicator; } /** * Set confirmDeliveryIndicator value * @param string $_confirmDeliveryIndicator the confirmDeliveryIndicator * @return string */ public function setConfirmDeliveryIndicator($_confirmDeliveryIndicator) { return ($this->confirmDeliveryIndicator = $_confirmDeliveryIndicator); } /** * Get deliveryOnSatIndicator value * @return string|null */ public function getDeliveryOnSatIndicator() { return $this->deliveryOnSatIndicator; } /** * Set deliveryOnSatIndicator value * @param string $_deliveryOnSatIndicator the deliveryOnSatIndicator * @return string */ public function setDeliveryOnSatIndicator($_deliveryOnSatIndicator) { return ($this->deliveryOnSatIndicator = $_deliveryOnSatIndicator); } /** * Get handlingChargeIndicator value * @return string|null */ public function getHandlingChargeIndicator() { return $this->handlingChargeIndicator; } /** * Set handlingChargeIndicator value * @param string $_handlingChargeIndicator the handlingChargeIndicator * @return string */ public function setHandlingChargeIndicator($_handlingChargeIndicator) { return ($this->handlingChargeIndicator = $_handlingChargeIndicator); } /** * Get returnLabelIndicator value * @return string|null */ public function getReturnLabelIndicator() { return $this->returnLabelIndicator; } /** * Set returnLabelIndicator value * @param string $_returnLabelIndicator the returnLabelIndicator * @return string */ public function setReturnLabelIndicator($_returnLabelIndicator) { return ($this->returnLabelIndicator = $_returnLabelIndicator); } /** * Get schedulePickupIndicator value * @return string|null */ public function getSchedulePickupIndicator() { return $this->schedulePickupIndicator; } /** * Set schedulePickupIndicator value * @param string $_schedulePickupIndicator the schedulePickupIndicator * @return string */ public function setSchedulePickupIndicator($_schedulePickupIndicator) { return ($this->schedulePickupIndicator = $_schedulePickupIndicator); } /** * Get shipmentType value * @return string|null */ public function getShipmentType() { return $this->shipmentType; } /** * Set shipmentType value * @param string $_shipmentType the shipmentType * @return string */ public function setShipmentType($_shipmentType) { return ($this->shipmentType = $_shipmentType); } /** * Method called when an object has been exported with var_export() functions * It allows to return an object instantiated with the values * @see MynewServiceWsdlClass::__set_state() * @uses MynewServiceWsdlClass::__set_state() * @param array $_array the exported values * @return MynewServiceStructRateServiceOptions */ public static function __set_state(array $_array,$_className = __CLASS__) { return parent::__set_state($_array,$_className); } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } }
true
617a497ff7baee1cbfff599d5e4eb13685c86f82
PHP
BradCrumb/ze-swagger-codegen
/src/V30/Hydrator/CallbackHydrator.php
UTF-8
1,206
2.625
3
[]
no_license
<?php namespace Swagger\V30\Hydrator; use Swagger\V30\Schema\Callback; use Zend\Hydrator\HydratorInterface; use Swagger\V30\Schema\PathItem; class CallbackHydrator implements HydratorInterface { /** * @var PathItemHydrator */ protected $pathItemHydrator; /** * Constructor * --- * @param PathItemHydrator $pathItemHydrator */ public function __construct(PathItemHydrator $pathItemHydrator) { $this->pathItemHydrator = $pathItemHydrator; } /** * @inheritDoc * * @param Callback $object * * @return Callback */ public function hydrate(array $data, $object) { foreach ($data as $name => $pathItem) { $object->setExpression($name, $this->pathItemHydrator->hydrate($pathItem, new PathItem())); } return $object; } /** * @inheritDoc * * @param Callback $object * * @return array */ public function extract($object) { $data = []; foreach ($object->getExpressions() as $name => $pathItem) { $data[$name] = $this->pathItemHydrator->extract($pathItem); } return $data; } }
true
52d4dc3fbe2b301ff27f2ba43b3d30e40be79fde
PHP
shayleydon/deputy
/Role.php
UTF-8
770
3.421875
3
[]
no_license
<?php namespace Deputy; /** * Role is a class representation of a role. */ class Role { private $id; private $name; private $parentId; public function __construct(int $id, string $name, int $parentId) { $this->id = $id; $this->name = $name; $this->parentId = $parentId; } /** * Returns the role id. * * @return int */ public function getId() { return $this->id; } /** * Returns the role name. * * @return string */ public function getName() { return $this->name; } /** * Returns the parent role id. * * @return int */ public function getParentId() { return $this->parentId; } }
true
91508b6175bfafd46c6ef0a168f15c73a551118d
PHP
pedrosland/zf2-console-test
/module/Transactions/src/Transactions/Data/CurrencyWebservice.php
UTF-8
930
3.296875
3
[]
no_license
<?php namespace Transactions\Data; use Zend\Math\Rand; /** * Dummy web service returning random exchange rates * */ class CurrencyWebservice { /** * Returns exchange rate for currency * * Note: Normally, exchange rates would be between currency A and currency B * but sticking with the API, I'll assume we are always converting to GBP * (which we are). * * @param $currency string 3-character currency code eg GBP * @return float Exchange rate * @throws \InvalidArgumentException */ public function getExchangeRate($currency) { $allowedCurrencies = ['GBP', 'USD', 'EUR']; if(!in_array($currency, $allowedCurrencies)){ throw new \InvalidArgumentException("Please enter a valid currency."); } // Get random number between 0.5 and 1 to make it remotely realistic return Rand::getInteger(500, 1000)/1000; } }
true
f66c901a2ebe97a068808c63b28e73d1cf72505f
PHP
jesequihuae/residencitasitsa
/php/helper.class.php
UTF-8
6,899
2.703125
3
[]
no_license
<?php class helper { private $conection; function __construct() { $this->abrirConexion(); } function abrirConexion(){ try{ /*$handler = new PDO('mysql:host=127.0.0.1;dbname=residenciasitsa','root',''); //Localhost $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);*/ $handler = new PDO('mysql:host=185.201.11.65;dbname=u276604013_dbres','u276604013_itsa','jesus_321'); //Localhost $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo $e->getMessage(); } $this->conection = $handler; } function obtenerAlumnos(){ $sql = " SELECT idAlumno AS id, CONCAT(vNombre,' ',vApellidoPaterno,' ',vApellidoMaterno,' ',vNumeroControl) AS descripcion FROM alumnos "; $alumnos = $this->conection->prepare($sql); $alumnos->execute(); $respuesta = $alumnos->fetchAll(); return $respuesta; } function obtenerAlumnosPorCarrera($idCarrera){ $sql = " SELECT idAlumno AS id, CONCAT(vNombre,' ',vApellidoPaterno,' ',vApellidoMaterno,' ',vNumeroControl) AS descripcion FROM alumnos WHERE idCarrera = '$idCarrera' "; $alumnos = $this->conection->prepare($sql); $alumnos->execute(); $respuesta = $alumnos->fetchAll(); return $respuesta; } public function getCarreras(){ $sql = "SELECT idCarrera AS id, vCarrera AS descripcion FROM carreras WHERE bActivo = 1 "; $carreras = $this->conection->prepare($sql); $carreras->execute(); return $carreras->fetchAll(); } function guardarMensaje($idAlumno,$msg,$titulo,$bActive,$idMensaje){ if($idMensaje == 0){ $sql = " INSERT INTO mensajesporalumno ( idAlumno, vMensaje, vTitulo, bActive ) VALUES( $idAlumno, '".$msg."', '".$titulo."', $bActive ) "; }else{ $sql = " UPDATE mensajesporalumno SET vMensaje = '".$msg."', vTitulo = '".$titulo."' WHERE idMensaje = $idMensaje "; } $mensajes = $this->conection->prepare($sql); return $mensajes->execute(); } function getMensajes($inicio,$rowMax,$activo,$idAlumno){ $sql = " SELECT a.idMensaje, a.vMensaje, CONCAT(b.vNombre,' ',b.vApellidoPaterno,' ',b.vApellidoPaterno) AS vNombre, a.bActive FROM mensajesporalumno AS a INNER JOIN alumnos b ON(a.idAlumno = b.idAlumno) WHERE CASE WHEN $activo = -1 THEN a.bActive = a.bActive ELSE a.bActive = $activo END AND CASE WHEN $idAlumno = 0 THEN a.idAlumno = a.idAlumno ELSE a.idAlumno = $idAlumno END ORDER BY a.idMensaje DESC LIMIT $inicio,$rowMax "; $mensajes = $this->conection->prepare($sql); $mensajes->execute(); return $mensajes->fetchAll(); } function obtenerNumeroDeMensajes($activo,$idAlumno){ $sql = " SELECT COUNT(1) FROM mensajesporalumno WHERE CASE WHEN $activo = -1 THEN bActive = bActive ELSE bActive = $activo END AND CASE WHEN $idAlumno = 0 THEN idAlumno = idAlumno ELSE idAlumno = $idAlumno END "; $numeroMensajes = $this->conection->prepare($sql); $numeroMensajes->execute(); return $numeroMensajes->fetchColumn(); } function DesactivarActivar($idMensaje,$bit){ $sql = " UPDATE mensajesporalumno SET bActive = $bit WHERE idMensaje = $idMensaje "; $desactivar = $this->conection->prepare($sql); if($desactivar->execute()){ return 1; }else{ return 0; } } function obtenerInformacionMensaje($idMensaje){ $sql = " SELECT a.idMensaje, a.vMensaje, a.idAlumno, a.vTitulo, b.idCarrera FROM mensajesporalumno AS a INNER JOIN alumnos b ON(a.idAlumno = b.idAlumno) WHERE idMensaje = $idMensaje "; $info = $this->conection->prepare($sql); $info->execute(); return $info->fetchAll(); } } $operacion = @$_POST["operacion"]; switch ($operacion) { case 1: $helper = new helper(); $idCarrera = $_POST["idCarrera"]; $alumnos = $helper->obtenerAlumnosPorCarrera($idCarrera); echo "<option value='0'>Selecciona uno</option>"; foreach ($alumnos AS $k) { echo "<option value=".$k["id"].">".$k["descripcion"]."</option>"; } break; case 2: $helper = new helper(); $idMensaje = $_POST["idMensaje"]; $idAlumno = $_POST["idAlumno"]; $msg = $_POST["mensaje"]; $titulo = $_POST["titulo"]; $bActive = $_POST["bActive"]; echo $helper->guardarMensaje($idAlumno,$msg,$titulo,$bActive,$idMensaje); break; case 3: $helper = new helper(); $mensajes = $helper->getMensajes($_POST["inicio"],$_POST["fin"],$_POST["activo"],$_POST["idAlumno"]); $tabla = "<thead>"; $tabla .= "<tr>"; $tabla .= "<th class='center'>Id mensaje</th>"; $tabla .= "<th class='center'>Mensajes</th>"; $tabla .= "<th class='center'>Nombre</th>"; $tabla .= "<th class='center'>Activo</th>"; $tabla .= "<th class='center'>Editar</th>"; $tabla .= "<th class='center'>Desactivar</th>"; $tabla .= "<tr>"; $tabla .= "</thead>"; foreach ($mensajes as $m) { $tabla .= "<tr>"; $tabla .= "<td class='center'>".$m["idMensaje"]."</td>"; $tabla .= "<td class='center'>".$m["vMensaje"]."</td>"; $tabla .= "<td class='center'>".$m["vNombre"]."</td>"; if($m["bActive"] == 1){ $tabla .= "<td class='center'><input type='checkbox' checked disabled /></td>"; }else{ $tabla .= "<td class='center'><input type='checkbox' disabled /></td>"; } $tabla .= "<td class='center'><button class='btn btn-warning' onclick='editar(".$m["idMensaje"].")'>Editar</button></td>"; if($m["bActive"] == 1){ $tabla .= "<td class='center'><button class='btn btn-danger' onclick='DesactivarActivar(".$m["idMensaje"].",0)'>Desactivar</button></td>"; }else{ $tabla .= "<td class='center'><button class='btn btn-success' onclick='DesactivarActivar(".$m["idMensaje"].",1)'>Activar</button></td>"; } $tabla .= "</tr>"; } $paginador = $helper->obtenerNumeroDeMensajes($_POST["activo"],$_POST["idAlumno"]); $respuesta = "<ul class='pagination'>"; $j = 1; for($i = 0;$i < $paginador; $i+=7){ $respuesta .= "<li><a onclick='cargarAlumnos(".$i.",7,-1,0)'>".$j."</a></li>"; $j++; } $respuesta .= "</ul>"; $res = array("mensajes" => $tabla , "paginador" => $respuesta); echo json_encode($res); break; case 4: $helper = new helper(); echo $helper->DesactivarActivar($_POST["idMensaje"],$_POST["activo"]); break; case 5: $helper = new helper(); echo json_encode($helper->obtenerInformacionMensaje($_POST["idMensaje"])); break; default: break; } ?>
true
8c37d82c1738a642e8c66b3c6edf112138d60e1c
PHP
iakbarp/bukuangkatan
/edit.php
UTF-8
8,348
2.71875
3
[ "Apache-2.0" ]
permissive
<?php include("header.php"); // memanggil file header.php include("koneksi.php"); // memanggil file koneksi.php untuk koneksi ke database error_reporting(0); ?> <div class="container"> <div class="content"> <h2>Data Mahasiswa &raquo; Edit Data</h2> <hr /> <?php $nim = $_GET['nim']; // assigment nim dengan nilai nim yang akan diedit $sql = mysqli_query($koneksi, "SELECT * FROM mahasiswa WHERE nim='$nim'"); // query untuk memilih entri data dengan nilai nim terpilih if(mysqli_num_rows($sql) == 0){ header("Location: index.php"); }else{ $row = mysqli_fetch_assoc($sql); } if(isset($_POST['save'])){ // jika tombol 'Simpan' dengan properti name="save" pada baris 162 ditekan $nim = $_POST['nim']; $nama = $_POST['nama']; $foto = $_POST['foto']; $jenis_kelamin = $_POST['jenis_kelamin']; $tempat_lahir = $_POST['tempat_lahir']; $tanggal_lahir = $_POST['tanggal_lahir']; $alamat_asal = $_POST['alamat_asal']; $alamat_sekarang = $_POST['alamat_sekarang']; $no_telepon = $_POST['no_telepon']; $prodi = $_POST['prodi']; $update = mysqli_query($koneksi, "UPDATE mahasiswa SET nama='$nama', foto='$foto', jenis_kelamin='$jenis_kelamin', tempat_lahir='$tempat_lahir', tanggal_lahir='$tanggal_lahir', alamat_asal='$alamat_asal', alamat_sekarang='$alamat_sekarang', no_telepon='$no_telepon', prodi='$prodi' WHERE nim='$nim'") or die(mysqli_error()); // query untuk mengupdate nilai entri dalam database if($update){ // jika query update berhasil dieksekusi header("Location: edit.php?nim=".$nim."&pesan=sukses"); // tambahkan pesan=sukses pada url }else{ // jika query update gagal dieksekusi echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>Data gagal disimpan, silahkan coba lagi.</div>'; // maka tampilkan 'Data gagal disimpan, silahkan coba lagi.' } } if(isset($_GET['pesan']) == 'sukses'){ // jika terdapat pesan=sukses sebagai bagian dari berhasilnya query update dieksekusi echo '<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>Data berhasil disimpan. <a href="data.php"><- Kembali</a></div>'; // maka tampilkan 'Data berhasil disimpan.' } ?> <!-- bagian ini merupakan bagian form untuk mengupdate data yang akan dimasukkan ke database --> <form class="form-horizontal" action="" method="post"> <div class="form-group"> <label class="col-sm-3 control-label">nim</label> <div class="col-sm-2"> <input type="text" name="nim" value="<?php echo $row ['nim']; ?>" class="form-control" placeholder="nim" required> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Nama</label> <div class="col-sm-4"> <input type="text" name="nama" value="<?php echo $row ['nama']; ?>" class="form-control" placeholder="Nama" required> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Foto Sekarang</label> <div class="col-sm-2"> <?php echo '<img src="img/' . $row['foto'] . '" style="width: 86px; height:115px">'; ?> </div> <div class="col-sm-3"> <b>Ganti Foto (3x4 cm) :</b> <input type="file" name="foto" required> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Jenis Kelamin</label> <div class="col-sm-2"> <select name="jenis_kelamin" class="form-control" required> <option value=""> - Jenis Kelamin - </option> <option value="Laki-Laki">Laki-Laki</option> <option value="Perempuan">Perempuan</option> </select> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Tempat Lahir</label> <div class="col-sm-4"> <input type="text" name="tempat_lahir" value="<?php echo $row ['tempat_lahir']; ?>" class="form-control" placeholder="Tempat Lahir" required> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Tanggal Lahir</label> <div class="col-sm-4"> <input type="text" name="tanggal_lahir" value="<?php echo $row ['tanggal_lahir']; ?>" class="input-group datepicker form-control" date="" data-date-format="dd-mm-yyyy" placeholder="dd-mm-yyyy" required> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Alamat Asal</label> <div class="col-sm-3"> <textarea name="alamat_asal" class="form-control" placeholder="Alamat Asal"><?php echo $row ['alamat_asal']; ?></textarea> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Alamat Sekarang</label> <div class="col-sm-3"> <textarea name="alamat_sekarang" class="form-control" placeholder="Alamat Sekarang"><?php echo $row ['alamat_sekarang']; ?></textarea> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">No Telepon</label> <div class="col-sm-3"> <input type="text" name="no_telepon" value="<?php echo $row ['no_telepon']; ?>" class="form-control" placeholder="No Telepon" required> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Prodi</label> <div class="col-sm-2"> <select name="prodi" class="form-control" required> <option value=""> - Prodi Terbaru - </option> <option value="D3 Manajemen Informatika">D3 Manajemen Informatika</option> <option value="S1 Teknik Informatika">S1 Teknik Informatika</option> <option value="S1 Sistem Informasi">S1 Sistem Informasi</option> <option value="S1 Pendidikan Teknologi Informasi">S1 Pendidikan Teknologi Informasi</option> </select> </div> <div class="col-sm-3"> <b>Prodi Sekarang :</b> <span class="label label-success"><?php echo $row['prodi']; ?></span> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">&nbsp;</label> <div class="col-sm-6"> <input type="submit" name="save" class="btn btn-sm btn-primary" value="Simpan" data-toggle="tooltip" title="Simpan Data Mahasiswa"> <a href="data.php" class="btn btn-sm btn-danger" data-toggle="tooltip" title="Batal">Batal</a> </div> </div> </form> </div> <!-- /.content --> </div> <!-- /.container --> <?php include("footer.php"); // memanggil file footer.php ?>
true
965ee5a2bf9ba4e440d82d8de935b8c2afe7651a
PHP
evgKoval/exchanger
/app/Http/Controllers/Api/V1/CurrenciesRatesController.php
UTF-8
1,799
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Api\V1; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Interfaces\CurrencyInterface; use App\Coinbase; class CurrenciesRatesController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $coinbase = new Coinbase(); // $rates = []; // $rates[] = $coinbase->getPrice('BTC', 'UAH'); // $rates[] = $coinbase->getPrice('ETH', 'UAH'); // $rates[] = $coinbase->getPrice('BCH', 'UAH'); // $rates[] = $coinbase->getPrice('LTC', 'UAH'); return $coinbase->user(); //return $rates; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $coinbase = new Coinbase(); return $coinbase->buy($request->all()); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
true
115317a27fc7fda3619020f6df06d123cdaf5419
PHP
prodigyworks/Trianik
/session-image-upload.php
UTF-8
488
2.515625
3
[]
no_license
<?php require_once(__DIR__ . "/pgcore-db.php"); require_once(__DIR__ . "/businessobjects/ImageClass.php"); try { SessionControllerClass::getDB()->beginTransaction(); $image = new ImageClass(); $image->setDescription("User Profile"); $image->uploadFromFile("file", 16000, 16000); $image->setSessionid(session_id()); $image->insertRecord(); SessionControllerClass::getDB()->commit(); } catch (Exception $e) { SessionControllerClass::getDB()->rollBack(); } ?>
true
b3ad15670204e0309b6f87a685cb34631bb550ba
PHP
mpiton/cours-php
/vendredi/test.php
UTF-8
858
2.734375
3
[]
no_license
<?php require("outils.php"); require("header.php"); // VARIABLES // VARIABLES $tableau = $_FILES['fichier']; $name = $tableau['name']; $type = $tableau['type']; $tmp_name = $tableau['tmp_name']; $size = $tableau['size']; $destinationfinale = $destination . "/" . $name; echo "<form action=\"\" method='post'enctype=\"multipart/form-data\">"; echo "<input type='file' name='fichier'>"; echo "<input type='submit' value='Valider'>"; echo "</form>"; $destination = 'upload'; $existe = file_exists($destination); if ($existe) { echo "La destination existe"; } else { echo "il va falloir créer un repertoire upload<br>"; $creationRepertoire = mkdir($destination); if ($creationRepertoire) { echo "repertoire crée !"; } else { echo "on a un problème !"; } } uploadMonFichier($tableau); require("footer.php"); ?>
true
c57fa56f9b5096fc9e5bc6a8e6d9fd0e218fa939
PHP
JoshuaW5/COMP3512_ASG2
/includes/SubjectDB.php
UTF-8
1,104
2.75
3
[]
no_license
<?php ini_set('error_reporting', E_ALL); ini_set('display_errors', 'On'); include_once 'includes/AbstractDB.php'; class SubjectDB extends AbstractDB{ protected $baseSQL = "SELECT SubjectID, SubjectName FROM Subjects"; private $connection = null; protected $keyFieldName = "SubjectID"; public function __construct($connection) { parent::__construct($connection); } protected function getSelect(){return $this->baseSQL;} protected function getKeyFieldName(){return $this->keyFieldName;} public function getByPaintingID ($id) { $sql = "SELECT DISTINCT SubjectName, SubjectID FROM Subjects JOIN PaintingSubjects USING (SubjectID) WHERE PaintingID = ?"; if (count($id) > 1) { $sql = "SELECT DISTINCT SubjectName, SubjectID FROM Subjects JOIN PaintingSubjects USING (SubjectID) WHERE PaintingID IN ("; for ($i=1; $i <= count($id); $i++) { $sql .= " ? "; if ($i != count($id)) { $sql .= ","; } } $sql .= ")"; } $result = DBHelper::runQuery($this->getConnection(), $sql, $id); return $result; } }
true
8b029674029f7349b4dec509bcbb2740c6fb5e80
PHP
fanzhaogui/PHP_More_Testing
/code_test/pattern/2_factory/2_3_abstract_factory/SQLiteFactory.php
UTF-8
300
2.640625
3
[]
no_license
<?php /** * User: Andy * Date: 2020/3/24 * Time: 0:01 */ class SQLiteFactory implements Factory { public function createUser() { echo "sqlite create user at " . __FUNCTION__ . '<br>'; } public function createArticle() { echo "sqlite create article at " . __FUNCTION__ . '<br>'; } }
true
d7382d9b1fe0bd090a69fc38498202c11604ca1a
PHP
BialekM/training
/Eagles/SarosTest/Konwerter języków PHP-Java/wycinara.php
UTF-8
485
3.390625
3
[]
no_license
<?php class test { function znajdz1 ($wyraz) { $wyraz = $wyraz; $regex = "/System\.out\.println\(\".*\"\);/"; $wynik = preg_match($regex, $wyraz, $zmienna); return $zmienna[0]; } function wytnijZmienna ($string) { $regex = "/\".*\"/"; $wynik = preg_match($regex, $string, $zmienna); return $zmienna[0]; } } $t1 = new test(); echo $t1->wytnijZmienna($t1->znajdz1('System.out.println("z upa");'));
true
7b5fcdcbfbc37d0ab96eccb14126b3b3f67c2a68
PHP
tapiau/php-playground
/fourier/src/FFT.php
UTF-8
667
2.875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: zibi * Date: 2018-03-13 * Time: 12:42 */ class FFT { public $sampleList = null; public $weightList = []; public function __construct($sampleList) { $this->sampleList = $sampleList; } public function calcWeight($freq) { $modConst = $freq*2*M_PI; return array_reduce( $this->sampleList->sampleList, function($state,$item) use ($modConst) { return [ 'sum'=> $state['sum']+cos($modConst*$state['count']/$this->sampleList->sampleRate)*$item, 'count'=>$state['count']+1 ]; }, [ 'sum'=>0, 'count'=>0 ] )['sum']; } public function normalizeWeightList() { } }
true
c34357a9858781bf4ae27cb3790ac33c531899eb
PHP
ahmedAlraimi/Tasarim
/Term Project/1 Full Project/Design_Pattern/models/ManagementProfile.php
UTF-8
586
2.875
3
[]
no_license
<?php namespace models; class ManagementProfile { private $position; private $address; private $phone_number; public function setPosition($position){ $this->position = $position; } public function setAddress($address){ $this->address = $address; } public function setPhoneNumber($phone_number){ $this->phone_number = $phone_number; } public function preview(){ $profile = array( 'position' => $this->position, 'address' => $this->address, 'phone_number' => $this->phone_number ); return $profile; } } ?>
true
5fece835b6b7dc2e363dad94a89a13c713e51dde
PHP
denst/38076DGF
/www/application/classes/helper/password.php
UTF-8
522
3.140625
3
[]
no_license
<?php defined('SYSPATH') or die('No direct access allowed.'); class Helper_Password { public static function generate_password($length = 8) { $password = ""; $possible = "123456789abcdefghjkmnpqrstuvwxyz123456789"; for ($i = 0; $i < $length; $i++) { // pick a random character from the possible ones $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); $password .= $char; } return $password; } }
true
49d98f556d493188537172032c6240dda330f03e
PHP
dsisconeto/Capsula-do-Tempo
/PHP - Informativo Carajás/src/core/model/ModelCompanyDepartment.php
UTF-8
2,056
2.734375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: dejair * Date: 03/04/16 * Time: 17:20 */ class ModelCompanyDepartment extends dbConnection { private $companyDepartmentId; private $companyIdFk; private $companyDepartmentName; private $companyDepartmentDateInsert; private $companyDepartmentDateUpdate; /** * @return mixed */ public function getCompanyDepartmentId() { return $this->companyDepartmentId; } /** * @param mixed $companyDepartmentId */ public function setCompanyDepartmentId($companyDepartmentId) { $this->companyDepartmentId = $companyDepartmentId; } /** * @return mixed */ public function getCompanyIdFk() { return $this->companyIdFk; } /** * @param mixed $companyIdFk */ public function setCompanyIdFk($companyIdFk) { $this->companyIdFk = $companyIdFk; } /** * @return mixed */ public function getCompanyDepartmentName() { return $this->companyDepartmentName; } /** * @param mixed $companyDepartmentName */ public function setCompanyDepartmentName($companyDepartmentName) { $this->companyDepartmentName = $companyDepartmentName; } /** * @return mixed */ public function getCompanyDepartmentDateInsert() { return $this->companyDepartmentDateInsert; } /** * @param mixed $companyDepartmentDateInsert */ public function setCompanyDepartmentDateInsert($companyDepartmentDateInsert) { $this->companyDepartmentDateInsert = $companyDepartmentDateInsert; } /** * @return mixed */ public function getCompanyDepartmentDateUpdate() { return $this->companyDepartmentDateUpdate; } /** * @param mixed $companyDepartmentDateUpdate */ public function setCompanyDepartmentDateUpdate($companyDepartmentDateUpdate) { $this->companyDepartmentDateUpdate = $companyDepartmentDateUpdate; } }
true
24efc5f7c53299b1b0b5da1fa27f90a3fda15cda
PHP
liangpig1/worddestructor
/WordDestructor/Lib/Model/WordlistModel.class.php
UTF-8
1,001
2.609375
3
[]
no_license
<?php class WordlistModel extends Model { public function getListById($listId) { return $this->where("id=".$listId)->find(); } public function getListByName($name) { return $this->where("name='".$name."'")->find(); } public function getListsByUser($userId) { return $this->where("userId=".$userId)->select(); } public function getAllLists() { return $this->select(); } public function removeWordList($listId) { return $this->where("id=".$listId)->delete(); } public function removeWordListByUser($userId) { return $this->where("userId=".$userId)->delete(); } //new Empty WordList public function addWordList($listData) { $listData["progress"] = 0; return $this->add($listData); } public function updateWordList($listInfo) { return $this->save($listInfo); } } ?>
true
fbf77b9d309f21fe1a74be01e2de6d87ed3a910a
PHP
borry262921984/genaku
/demo4.php
UTF-8
2,313
3.5
4
[]
no_license
<?php //本例子采用作为实例标签 //载入xml $_sxe = simplexml_load_file('test.xml'); // 1) 读一级标签的值 // 就算version自动列成数组,但简单输出方法没有指定索引号,所以以第一个打印 echo '1 -> '; echo $_sxe->version; echo "\n\n"; // 2) 如果加上索引号则可以指定打印目标(前提是存在的数组索引号) echo '2 -> '; echo $_sxe->version[2]; echo "\n\n"; // 3) 如果有多个version标签$_sxe->version其实是一个数组 echo '3 -> '; print_r($_sxe->version); echo "\n\n"; // 4) 遍历数组(一级)标签 echo '4 -> '; foreach ($_sxe->version as $v){ echo '['.$v.']'; } echo "\n\n"; // 5) 访问二级数组的标签 //如果要访问二级标签,必须一层一层指明 echo '5 -> '; echo $_sxe->user[1]->name; echo "\n\n"; // 6) 遍历所有的二级标签的name值 echo '6 -> '; foreach ($_sxe->user as $_user){ echo '['.$_user->name.']'; } echo "\n\n"; // 7) 输出第二个user里的author的性别<author sex="女">谁谁谁</author> //attributes()函数能获取SimpleXML元素的属性 //如果元素里面有多个属性,则以属性名称来指向属性内容(虽然不显示数字索引,但默认生成) //元素指针也会生成数字索引,顺序则按照属性在元素内的先后顺序生成 //例1:<span sex='女' E_sex='woman'> 生成数组是[0]->女 [1]->woman //例2:<span E_sex='woman' sex='女'> 生成数组是[0]->woman [1]->女 echo '7 -> '; print_r($_sxe->user[1]->author->attributes()); echo "\t"; echo $_sxe->user[1]->author->attributes()['E_sex']; echo "\n\t"; echo $_sxe->user[1]->author->attributes()[1]; echo "\n\n"; // 8) 使用xpath来获取xml节点操作 //获取version标签的值 echo '8 -> '; $_version = $_sxe -> xpath('/root'); //由于转换后属于SimpleXML数组,所以需要通过json来编译成普通数组才能正常操作 $jsonStr = json_encode($_version); $jsonArray = json_decode($jsonStr,true); print_r($jsonArray[0]); echo '这是最高级的数组元素:'.$jsonArray[0]['user'][2]['author']; ?>
true
b0d7a6921f814c24cf1ab274b291f5bc15271d29
PHP
wuluo/KMB
/kohana/modules/misc/classes/Base62.php
UTF-8
798
3.28125
3
[]
no_license
<?php /** * Base62 将整型转为62进制数字(有大数问题) * @author Sundj * @since 2014.04.07 */ class Base62 { const BASE = 62; static $baseChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; public function encode($number) { $output = ''; do { $reminder = $number % Base62::BASE; $output = Base62::$baseChars[$reminder] . $output; $number = ($number - $reminder) / Base62::BASE; } while($number > 0); return $output; } public function decode($input) { $length = strlen($input); $number = 0; $baseChars = array_flip(str_split(Base62::$baseChars)); for($i = 0; $i < $length; ++$i) { $number += $baseChars[$input[$i]] * pow(Base62::BASE, $length - $i - 1); } return number_format($number, 0, '', ''); } }
true
a59ead04ca3c143d574dfdb58a6ef5e0959b0fe3
PHP
DyoungDsea/frenxy
/webcontrol/clean.php
UTF-8
1,401
2.71875
3
[]
no_license
<?php @session_start(); require("config.php"); function clean($value){ GLOBAL $conn; $value=trim($value); $value=htmlspecialchars($value); $value=strip_tags($value); $value = $conn->real_escape_string($value); return $value; } @$idc = clean($_SESSION['userid']); function formatDate($data){ return date("d M, Y", strtotime($data)); } function formatDateTime($data){ return date("d M Y, h:i:sa", strtotime($data)); } function fetchAssoc($data){ return $data->fetch_assoc(); } function formatTime($data){ return date("H:i", strtotime($data)); } function runQuery($statement){ GLOBAL $conn; return $conn->query($statement); } function addToDate($now, $howManyDays){ $date = $now; $date = strtotime($date); $date = strtotime($howManyDays.' day', $date); //strtotime("+7 day", $date); return date('Y-m-d h:i:s', $date); } function datePlusOneHour(){ $now = gmdate("Y-m-d H:i:s"); $date = date('Y-m-d H:i:s',strtotime("+1 hour",strtotime($now))); return $date; } function limitText($text,$limit){ if(str_word_count($text, 0)>$limit){ $word = str_word_count($text,2); $pos=array_keys($word); $text=substr($text,0,$pos[$limit]). '...'; } return $text; } $_SESSION['current_page'] = $_SERVER['REQUEST_URI']; //get the current url link
true
b6b47103d5c848189584461d16e392a1ee4e12e7
PHP
halvaroz/restaurant
/library/FlashBag.class.php
UTF-8
750
2.921875
3
[]
no_license
<?php class FlashBag{ public function __construct(){ if(session_status() == PHP_SESSION_NONE){ session_start(); } if(array_key_exists('flash-bag', $_SESSION) == false){ $_SESSION['flash-bag'] = array(); } } public function add($message){ array_push($_SESSION['flash-bag'], $message); } public function fetchMessage(){ return array_shift($_SESSION['flash-bag']); } public function fetchMessages(){ $messages = $_SESSION['flash-bag']; $_SESSION['flash-bag'] = array(); return $messages; } public function hasMessages(){ return empty($_SESSION['flash-bag']) == false; } }
true
dd8788cfc40b454d4b26198467b5b693b119a9ac
PHP
sydorenkovd/nemo.api
/src/Response/GuideAircraft.php
UTF-8
4,238
2.65625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: sydorenkovd * Date: 08.06.17 * Time: 12:19 */ namespace Nemo\Library\Response; use Nemo\Library\Core\BaseHelper; use Nemo\Library\Core\Logo; class GuideAircraft { private $id; private $name; private $nameEn; private $manufacture; private $originCountries; private $distanceType; private $fuselageType; private $capacity; private $cruiseSpeed; private $isTurbineAirctaft; private $isHomeAirctaft; private $image; private $map_image; private $base; public function __construct() { $this->image = new Logo(); $this->map_image = new Logo(); $this->base = new BaseHelper(); } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getName() { return $this->name; } /** * @param mixed $name */ public function setName($name) { $this->name = $name; } /** * @return mixed */ public function getNameEn() { return $this->nameEn; } /** * @param mixed $nameEn */ public function setNameEn($nameEn) { $this->nameEn = $nameEn; } /** * @return mixed */ public function getManufacture() { return $this->manufacture; } /** * @param mixed $manufacture */ public function setManufacture($manufacture) { $this->manufacture = $manufacture; } /** * @return mixed */ public function getOriginCountries() { return $this->base->getIterator($this->originCountries); } /** * @param mixed $originCountries */ public function setOriginCountries($originCountries) { $this->originCountries = $this->base->getIterator($originCountries); } /** * @return mixed */ public function getDistanceType() { return $this->distanceType; } /** * @param mixed $distanceType */ public function setDistanceType($distanceType) { $this->distanceType = $distanceType; } /** * @return mixed */ public function getFuselageType() { return $this->fuselageType; } /** * @param mixed $fuselageType */ public function setFuselageType($fuselageType) { $this->fuselageType = $fuselageType; } /** * @return mixed */ public function getCapacity() { return $this->capacity; } /** * @param mixed $capacity */ public function setCapacity($capacity) { $this->capacity = $capacity; } /** * @return mixed */ public function getCruiseSpeed() { return $this->cruiseSpeed; } /** * @param mixed $cruiseSpeed */ public function setCruiseSpeed($cruiseSpeed) { $this->cruiseSpeed = $cruiseSpeed; } /** * @return mixed */ public function getIsTurbineAirctaft() { return $this->isTurbineAirctaft; } /** * @param mixed $isTurbineAirctaft */ public function setIsTurbineAirctaft($isTurbineAirctaft) { $this->isTurbineAirctaft = $isTurbineAirctaft; } /** * @return mixed */ public function getIsHomeAirctaft() { return $this->isHomeAirctaft; } /** * @param mixed $isHomeAirctaft */ public function setIsHomeAirctaft($isHomeAirctaft) { $this->isHomeAirctaft = $isHomeAirctaft; } /** * @return mixed */ public function getImage() { return $this->image; } /** * @param mixed $image */ public function setImage($image) { $this->image = $image; } /** * @return mixed */ public function getMapImage() { return $this->map_image; } /** * @param mixed $map_image */ public function setMapImage($map_image) { $this->map_image = $map_image; } }
true
e2ea9610a70dc13d5695e34731b2727b2001f049
PHP
menkveld/parallel
/yii/modules/person/controllers/DefaultController.php
UTF-8
2,980
2.609375
3
[]
no_license
<?php class DefaultController extends PpController { // Overide the model property of the Controller base class // Once this is done, the generic loadModel method can be used. protected $_model = "Person"; /** * Generic CRUD Functionality * * create - Generic entity create action * update - Generic entity update action * delete - Generic entity delete action * */ public function actions() { return array( 'update' => array( 'class' => 'parallel\yii\actions\EntityUpdateAction', 'model' => 'Person', 'childModels' => array( 'parallel\yii\models\Addresses\Address' => 'addressItems', 'parallel\yii\models\ContactDetails\ContactDetail' => 'contactDetailItems', // Child Model Name => Detail Item Behavior Name (see Company) ), ), 'create' => array( 'class' => 'parallel\yii\actions\EntityUpdateAction', 'model' => 'Person', 'childModels' => array( 'parallel\yii\models\Addresses\Address' => 'addressItems', 'parallel\yii\models\ContactDetails\ContactDetail' => 'contactDetailItems', // Child Model Name => Detail Item Behavior Name (see Company) ), ), 'delete' => array( 'class' => 'parallel\yii\actions\EntityDeleteAction', 'model' => 'Person', ), 'ajaxAddContactDetail' => array( 'class' => 'parallel\yii\widgets\ContactDetails\AddContactDetailItemAction', 'bridgeModel' => 'PersonContactDetail', ), 'suburbOptions' => array( 'class' => 'parallel\yii\zii\widgets\jui\AutoCompleteAction', 'model' => 'parallel\yii\models\Addresses\AddressSuburb', 'attributes' => array( 'label' => 'label', 'postal_code' => 'postal_code', 'province_state' => 'province_state_label' ), 'order' => 'label', 'searchType' => parallel\yii\zii\widgets\jui\AutoCompleteAction::SEARCH_FIRST_CHARS ), ); } /** * Lists all models. */ public function actionIndex() { $this->actionList(); } /** * Manages all models. */ public function actionList() { if(\Yii::app()->user->checkAccess('Person.view')) { $model=new Person('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Person'])) $model->attributes=$_GET['Person']; $this->render('list',array( 'model'=>$model, )); } else { throw new \CHttpException(403, "User does not have sufficient permission for this action."); } } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { $this->render('view',array( 'model'=>$this->loadModel($id), )); } /** * Performs the AJAX validation. * @param CModel the model to be validated */ protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='person-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } }
true
7d72d06c1497857733923e7e92189b5c5f8eff28
PHP
c9s/CLIFramework
/tests/CLIFramework/TestAppCommandTest.php
UTF-8
870
2.515625
3
[ "BSD-4-Clause-UC" ]
permissive
<?php use CLIFramework\ArgInfo; use TestApp\Application; use PHPUnit\Framework\TestCase; class TestAppCommandTest extends TestCase { public function testSimpleCommand() { $command = new TestApp\Command\SimpleCommand(new Application); $command->init(); $argInfos = $command->getArgInfoList(); $this->assertNotEmpty($argInfos); $this->assertCount(1, $argInfos); $this->assertEquals('var', $argInfos[0]->name); } public function testArginfoCommand() { $cmd = new TestApp\Command\ArginfoCommand(new Application); $cmd->init(); $argInfos = $cmd->getArgInfoList(); $this->assertNotEmpty($argInfos); $this->assertCount(3, $argInfos); foreach( $argInfos as $arginfo ) { $this->assertInstanceOf('CLIFramework\ArgInfo', $arginfo); } } }
true
e2ebfb543062b95787007821aa2ef574499ca0e8
PHP
passerellesnumeriques/SDB-0.1-prototype
/www/component/authentication/FakeAuthenticationSystem.inc
UTF-8
199
2.59375
3
[]
no_license
<?php require_once("AuthenticationSystem.inc"); class FakeAuthenticationSystem extends AuthenticationSystem { public function authenticate($username, $password, &$error) { return "1"; } } ?>
true
b68aa920a096082c4df1592056f2a47f695ad93f
PHP
gotohr/simple-php-code-gen
/src/GoToHr/SimpleCodeGen/InterfaceMethodTemplate.php
UTF-8
167
2.59375
3
[]
no_license
<?php namespace GoToHr\SimpleCodeGen; class InterfaceMethodTemplate extends StructureMethodTemplate { protected function generateBody() { return ";".PHP_EOL; } }
true
8333a511bcc1e02456d6a1a3ea88a6d636a71d5b
PHP
BerilBBJ/scraperwiki-scraper-vault
/Users/C/Cato/artificer.php
UTF-8
4,058
2.8125
3
[]
no_license
<?php /* scraper by Tomasz Polonczyk http://www.tomot.eu */ require 'scraperwiki/simple_html_dom.php'; /* Extract BLOCKS */ scraperwiki::sqliteexecute("create table if not exists data (col1 char(24), col2 int(24), col3 char(24), col4 char(24), col5 char(24), col6 char(24), col7 char(24), col8 char(24), col9 char(24), col10 char(24), col11 char(24), col12 char(24), col13 char(24))"); for ($i=1;$i<=2;$i++){ $url = "http://www.gw2db.com/recipes/enchanter?page=$i"; $html = scraperwiki::scrape($url); $dom = new simple_html_dom(); $dom->load($html); foreach ($dom->find('table tr') as $row) { echo $row . "\n"; // echo $row->find('a',3)->href . $row->find('a',4)->href . $row->find('a',5)->href . $row->find('a',6)->href; $vals = $row->find('td'); //print_r($vals) ; //echo test.$vals[4].test; // if (!empty($vals)) { // if (preg_match('/[0-9a-fA-F]{64}/', $vals[1]->innertext, $matches )) { $string = $vals[4]->plaintext; preg_match_all('/\d+/', $string, $ing); $data[] = array( 'col1' => $vals[0]->plaintext, // '#2' => $matches[0], 'col2' => $vals[1]->plaintext, 'col3' => $vals[2]->plaintext, 'col4' => $vals[3]->plaintext, 'col6' => $ing[0][0], 'col7' => str_replace('-',' ',strstr($row->find('a',3)->href, '-')), 'col8' => $ing[0][1], 'col9' => str_replace('-',' ',strstr($row->find('a',4)->href, '-')), 'col10' => $ing[0][2], 'col11' => str_replace('-',' ',strstr($row->find('a',5)->href, '-')), 'col12' => $ing[0][3], 'col13' => str_replace('-',' ',strstr($row->find('a',6)->href, '-')), // 'col5' => $vals[4]->plaintext // ); // }; // } }; scraperwiki::save_sqlite(array('col1'),$data, "data"); /* Extract block data */ /* Extract transactions */ } ?> <?php /* scraper by Tomasz Polonczyk http://www.tomot.eu */ require 'scraperwiki/simple_html_dom.php'; /* Extract BLOCKS */ scraperwiki::sqliteexecute("create table if not exists data (col1 char(24), col2 int(24), col3 char(24), col4 char(24), col5 char(24), col6 char(24), col7 char(24), col8 char(24), col9 char(24), col10 char(24), col11 char(24), col12 char(24), col13 char(24))"); for ($i=1;$i<=2;$i++){ $url = "http://www.gw2db.com/recipes/enchanter?page=$i"; $html = scraperwiki::scrape($url); $dom = new simple_html_dom(); $dom->load($html); foreach ($dom->find('table tr') as $row) { echo $row . "\n"; // echo $row->find('a',3)->href . $row->find('a',4)->href . $row->find('a',5)->href . $row->find('a',6)->href; $vals = $row->find('td'); //print_r($vals) ; //echo test.$vals[4].test; // if (!empty($vals)) { // if (preg_match('/[0-9a-fA-F]{64}/', $vals[1]->innertext, $matches )) { $string = $vals[4]->plaintext; preg_match_all('/\d+/', $string, $ing); $data[] = array( 'col1' => $vals[0]->plaintext, // '#2' => $matches[0], 'col2' => $vals[1]->plaintext, 'col3' => $vals[2]->plaintext, 'col4' => $vals[3]->plaintext, 'col6' => $ing[0][0], 'col7' => str_replace('-',' ',strstr($row->find('a',3)->href, '-')), 'col8' => $ing[0][1], 'col9' => str_replace('-',' ',strstr($row->find('a',4)->href, '-')), 'col10' => $ing[0][2], 'col11' => str_replace('-',' ',strstr($row->find('a',5)->href, '-')), 'col12' => $ing[0][3], 'col13' => str_replace('-',' ',strstr($row->find('a',6)->href, '-')), // 'col5' => $vals[4]->plaintext // ); // }; // } }; scraperwiki::save_sqlite(array('col1'),$data, "data"); /* Extract block data */ /* Extract transactions */ } ?>
true
35524e6fd7669c7059c9d428aeb9ae9ad3113329
PHP
zgolus/kw
/src/Command/Write.php
UTF-8
1,719
2.71875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: jzgolinski * Date: 15.03.18 * Time: 18:29 */ namespace App\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use App\Utils\ReasonRepair; use App\Utils\ReasonValidator; Class Write extends Command { private $reasonRepair; private $reasonValidator; public function __construct(ReasonRepair $reasonRepair, ReasonValidator $reasonValidator) { parent::__construct(); $this->reasonRepair = $reasonRepair; $this->reasonValidator = $reasonValidator; } protected function configure() { $this->setName('kw:retoure:write') ->addArgument('input', InputArgument::REQUIRED, 'Input file') ->addArgument('output', InputArgument::REQUIRED, 'Output file'); } protected function execute(InputInterface $input, OutputInterface $output) { $inputHandle = fopen($input->getArgument('input'), "r"); $outputHandle = fopen($input->getArgument('output'), 'w'); if ($inputHandle) { while (($line = fgets($inputHandle)) !== false) { $line = trim($line); list($retourId, $retoureReason) = explode(',', $line, 2); $originalReason = trim($retoureReason); $repairedReason = $this->reasonRepair->repair($originalReason); fwrite($outputHandle, sprintf("%s,%s\n", $retourId, $repairedReason)); } fclose($inputHandle); } fclose($outputHandle); $output->writeln('Done.'); } }
true
3f5016657542e4f7cc68a60582c1e708870656b1
PHP
andres2r/prueba-tecnica
/app/Http/Controllers/UsersController.php
UTF-8
925
2.671875
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; class UsersController extends Controller { public function index(){ //GET request al API para obtener todos los datos $users = Http::get('https://jsonplaceholder.typicode.com/todos')->json(); $collection = collect($users); $uniqueUserId = $collection->unique('userId'); //Crando un array para contenter la cantidad de ToDo´s compledatos por cada usuario $completedArray = []; for($i = 1; $i <= count($uniqueUserId); $i++){ $completedArray[$i] = 0; } //Llenando array foreach($collection as $item){ if ($item['completed'] == true) { $completedArray[$item['userId']] += 1; } } return view('users.index', compact('uniqueUserId', 'completedArray')); } }
true
285b85d8c6740e19498f95955bec7ad617d16549
PHP
hbour/Bibliotheque
/indexArticle.php
UTF-8
2,285
2.671875
3
[]
no_license
<?php session_start(); ?> <!DOCTYPE html> <!-- Ceci est du HTML 5 --> <html lang="fr"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="reset.css" /> <link rel="stylesheet" href="style.css" /> <title>Exam Library</title> </head> <body> <div id="marges"> <?php include "header.php"; ?> <div id="sidebar"> <?php include "log.php"; ?> </div> <h2>Fiche article</h2> <?php if(!isset($_GET['id'])) { echo "Erreur: article indéfini"; } else { $id = $_GET['id']; include_once("dbconnex.php"); $idcom = connexobject("bibliotheque", "dbparam"); $requete = "SELECT OUV_Titre, OUV_Auteur, TYP_Support, OUV_Editeur, ". " OUV_Collection, OUV_Date_parution, OUV_Theme ". " FROM T_Ouvrages WHERE OUV_ID = '".$id."'"; $result = $idcom->query($requete); if(!$result) { echo "<p>Erreur requête</p>"; } else { while($res = $result->fetch_assoc()) { echo "<p>Titre : ".utf8_encode($res['OUV_Titre'])."</p>"; echo "<p>Auteur : ".utf8_encode($res['OUV_Auteur'])."</p>"; echo "<p>Code : ".utf8_encode($id)."</p>"; echo "<p>Support : ".utf8_encode($res['TYP_Support'])."</p>"; echo "<p>Editeur : ".utf8_encode($res['OUV_Editeur'])."</p>"; echo "<p>Collection : ".utf8_encode($res['OUV_Collection'])."</p>"; echo "<p>Date de parution : ".utf8_encode($res['OUV_Date_parution'])."</p>"; echo "<p>Thème : ".utf8_encode($res['OUV_Theme'])."</p>"; } } $result->close(); } ?> <h2>Statut des exemplaires</h2> <?php $requete2 = "SELECT DIS_Disponibilite ". " FROM T_Exemplaires WHERE OUV_ID = '".$id."'"; $result2 = $idcom->query($requete2); echo "<p>".$result2->num_rows." exemplaire(s) :</p>"; $present = 0; while($row = $result2->fetch_array(MYSQLI_NUM)) { foreach($row as $item) { echo "<p> - ".utf8_encode($item)." : "; if($item == 'Present') { $present = 1; } } } if($present == 1) { echo "<form method='get' id='reserver' action='indexReserver.php'>". "<input type='text' hidden='hidden' name='reserver' value='".$id."' />". "<input class='indent' type='submit' value='Réserver' /><form>"; } $result2->close(); ?> </div> </body> </html>
true
54cdff040d08bbe0ac4c56801d331fcd81a9f464
PHP
Idimma/piller-api
/app/Services/ExpoNotification.php
UTF-8
1,108
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Services; use Illuminate\Http\Request; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; class ExpoNotification { public static function sendNotification(String $notification_token, String $title, String $message, array $data) { $client = new Client([ 'headers' => [ 'Host' => 'exp.host', 'Accept' => 'application/json', 'Accept-Encoding' => 'gzip, deflate', 'Content-Type' => 'application/json' ] ]); try { $response = $client->post('https://exp.host/--/api/v2/push/send', [ 'form_params' => [ 'to' => $notification_token, 'sound' => 'default', 'title' => $title, 'body' => $message, 'data' => $data ] ]); } catch (ClientException $e) { //throw $th; $response = $e->getResponse(); } return json_decode($response->getBody(), true); } }
true
73720d0978872ec11e8109d3890e277514f3ba54
PHP
lukisanjaya/LumenElasticSearch
/app/Http/Controllers/Controller.php
UTF-8
925
2.609375
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Dingo\Api\Exception\ValidationHttpException; use Laravel\Lumen\Routing\Controller as BaseController; class Controller extends BaseController { /** * Override validate method use dingo validation exception * * @param Request $request * @param array $rules * @param array $messages * @param array $customAttributes */ public function validate( Request $request, array $rules, array $messages = [], array $customAttributes = []) { $validator = $this->getValidationFactory() ->make( $request->all(), $rules, $messages, $customAttributes ); if ($validator->fails()) { throw new ValidationHttpException( $validator->errors() ); } } }
true
6edfc46c8ced8c5187abc1614d7280926bbc45ef
PHP
bigshoesdev/KindWorker
/protected/components/TToolButtons.php
UTF-8
3,392
2.5625
3
[]
no_license
<?php namespace app\components; use Yii; use yii\helpers\Html; use yii\helpers\StringHelper; use app\models\User; class TToolButtons extends TBaseWidget { /** * * @var Model */ public $title; public $model; public $htmlOptions; /** * * @var string Current action id. */ public $actionId; /** * * @var array List of buttons actions. ('index', 'add', 'update', 'delete') * */ public $actions = [ 'add' => '<span class="glyphicon glyphicon-plus"></span>', 'update' => '<span class="glyphicon glyphicon-pencil"></span>', 'view' => '<span class="glyphicon glyphicon-eye-open"></span>', 'delete' => '<span class="glyphicon glyphicon-trash"></span>' ]; /** * * @var string|Closure Translated model name depends on actions. */ public $modelName; /** * * @var Closure Function can check whether action exist or not. */ public $hasAction; /** * @inheritdoc */ public function init() { parent::init (); if (! $this->actionId) { $this->actionId = Yii::$app->controller->action->id; } $this->modelName = get_class ( $this->model ); $this->modelName = StringHelper::basename ( $this->modelName ); } /** * @inheritdoc */ public function run() { echo '<div class="pull-right">'; if (is_array ( \Yii::$app->controller->menu )) foreach ( \Yii::$app->controller->menu as $key => $menu ) { if (! $this->hasAction ( $menu ['url'] )) continue; if (isset ( $this->actions [$key] )) { if ($key == 'delete') { $menu ['class'] = 'btn btn-danger'; /* * $menu ['label'] = $this->actions [$key]; * $menu ['data'] = [ * 'method' => 'POST', * 'confirm' => Yii::t ( 'app', 'Are you sure you want to delete this {modelName} #{id}', [ * 'modelName' => $this->modelName, * 'id' => ( isset( $this->model->id) )? $this->model->id :null * ] ) * ]; */ } if (! isset ( $menu ['label'] )) { $menu ['label'] = $this->actions [$key]; } } $visible = true; if (isset ( $menu ['visible'] )) if ($menu ['visible'] == true) $visible = true; else $visible = false; $this->htmlOptions = [ 'class' => isset ( $menu ['class'] ) ? $menu ['class'] : 'btn btn-success ', 'title' => isset ( $menu ['title'] ) ? $menu ['title'] : $menu ['label'], 'id' => isset ( $menu ['id'] ) ? $menu ['id'] : "tool-btn-" . $key ]; if (isset ( $menu ['htmlOptions'] )) $this->htmlOptions = array_merge ( $menu ['htmlOptions'], $this->htmlOptions ); if ($visible) echo ' ' . Html::a ( $menu ['label'], $menu ['url'], $this->htmlOptions ); } echo '</div>'; } /** * Returns a value indicating whether a controller action is defined. * * @param string $id * Action id * @return bool */ protected function hasAction($url) { //$enableEmails = yii::$app->setting->get ( 'Enable Emails' ); /* * if ( is_array($url)) * if ( $id == 'manage') $id = 'index'; * * $actionMap = ->actions (); * * if (isset ( $actionMap [$id] )) { * return true; * } else { * $action = Inflector::id2camel($id); * $methodName = 'action' . ucfirst($action); * if (method_exists ( Yii::$app->controller, $methodName )) { * return true; * } * } * * return false; */ return true; } }
true
a8059985a3803e33f7be75b2a9d303c5ae14a8e9
PHP
MFDonadeli/trigorh
/website/models/vaga_model.php
UTF-8
15,666
2.578125
3
[ "MIT" ]
permissive
<?php class Vaga_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->helper('password_helper'); } /** * registra_acao * * Grava ação do profissional no site * * @param int * @param int (constante da classe Acao) * @return string O hash da acao gravada no banco */ public function registra_acao($id, $acao) { log_message('debug', 'registra_acao. Param1: {' . $id . '} Param2: {' . $acao . '}'); $hash = sha1(date('Y-m-d H:i:s') . $id . $acao); $nova_acao = array( 'idprofissional' => $id, 'idacao' => $acao, 'hash' => $hash ); $this->db->insert('profissional_historico', $nova_acao); return $hash; } /** * insere_vaga * * Insere vaga * * @param string * @param string * @return boolean true ou false se existir o pedido */ public function insere_vaga($vaga, $id) { log_message('debug', 'insere_vaga. Param1: ' . $vaga . " Param2: " . $id); $arr = array( 'codvaga' => $vaga, 'idempresa' => $id ); $this->db->insert('vaga', $arr); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $this->db->insert_id(); } /** * apaga_vaga * * Apaga vaga * * @param string * @return boolean true ou false se existir o pedido */ public function apaga_vaga($vaga) { log_message('debug', 'apaga_vaga. Param1: ' . $vaga); $this->db->where('idvaga', $vaga); $result = $this->db->get('profissional_vaga'); if($result->num_rows() > 0) { return false; } $this->db->where('idvaga', $vaga); $this->db->delete('vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); } /** * update_dados_vaga * * Atualiza dados pessoais de profissional * * @param array * @param array * @return boolean true ou false se existir o pedido */ public function update_dados_vaga($arr, $beneficio) { log_message('debug', 'update_dados_vaga'); $this->db->where('idvaga', $arr['idvaga']); $this->db->update('vaga', $arr); if(is_array($beneficio)) { $this->db->where('idvaga', $arr['idvaga']); $this->db->delete('beneficio_vaga'); foreach($beneficio as $benef) { $arrbenef = array( 'idvaga' => $arr['idvaga'], 'idbeneficio' => $benef ); $this->db->insert('beneficio_vaga', $arrbenef); } } else log_message('debug', 'Benefício não é array'); log_message('debug', 'Last Query: ' . $this->db->last_query()); } /** * get_dados_vaga * * Busca dados pessoais de vaga * * @param int * @return array */ public function get_dados_vaga($id) { log_message('debug', 'get_dados_vaga. Param1: ' . $id); $this->db->where('idvaga', $id); $result = $this->db->get('vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->row(); } /** * get_beneficios_vaga * * Busca dados pessoais de vaga * * @param int * @return array */ public function get_beneficios_vaga($id) { log_message('debug', 'get_beneficios_vaga. Param1: ' . $id); $this->db->where('idvaga', $id); $result = $this->db->get('beneficio_vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->result(); } /** * update_idioma * * Insere/Atualiza dados de formação acadêmica da vaga * * @param array * @return boolean true ou false se existir o pedido */ public function update_idioma($arr, $ididioma) { log_message('debug', 'update_idioma. Idioma: ' . $ididioma); if(empty($ididioma)) { $this->db->insert('conhecimento_vaga', $arr); } else { $this->db->where('idconhecimento_vaga', $ididioma); $this->db->update('conhecimento_vaga', $arr); } log_message('debug', 'Last Query: ' . $this->db->last_query()); } /** * update_idioma * * Insere/Atualiza dados de formação acadêmica do profissional * * @param array * @return boolean true ou false se existir o pedido */ public function update_informatica($arr, $idinformatica) { log_message('debug', 'update_idioma'); if(empty($idinformatica)) { $this->db->insert('conhecimento_vaga', $arr); } else { $this->db->where('idconhecimento_vaga', $idinformatica); $this->db->update('conhecimento_vaga', $arr); } log_message('debug', 'Last Query: ' . $this->db->last_query()); } /** * update_curso * * Insere/Atualiza dados de cursos da vaga * * @param array * @return boolean true ou false se existir o pedido */ public function update_curso($arr, $idcurso) { log_message('debug', 'update_curso. Param1: ' . $idcurso); if(empty($idcurso)) { $this->db->insert('formacao_vaga', $arr); } else { $this->db->where('idformacao_vaga', $idcurso); $this->db->update('formacao_vaga', $arr); } log_message('debug', 'Last Query: ' . $this->db->last_query()); } /** * get_idioma * * Seleciona um idioma da vaga * * @param int * @param int * @return boolean true ou false se existir o pedido */ public function get_idioma($id, $id_idioma) { log_message('debug', 'get_idioma. Param1: ' . $id . ' Param2: ' . $id_idioma); $this->db->select('conhecimento_vaga.idconhecimento_vaga, conhecimento_vaga.idconhecimento, conhecimento_vaga.id_vaga, conhecimento_vaga.conhecimento, conhecimento_vaga.obrigatorio, conhecimento_vaga.nivel, nivel_idioma.nivel_idioma'); $this->db->from('conhecimento_vaga'); $this->db->join('nivel_idioma', 'conhecimento_vaga.nivel = nivel_idioma.idnivel_idioma'); $this->db->where('conhecimento_vaga.id_vaga', $id); $this->db->where('conhecimento_vaga.idconhecimento_vaga', $id_idioma); $result = $this->db->get(); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->row(); } /** * get_idiomas * * Busca os idiomas do profissional * * @param int * @return array */ public function get_idiomas($id) { log_message('debug', 'get_idiomas. Param1: ' . $id); $this->db->select('conhecimento_vaga.*, nivel_idioma.nivel_idioma'); $this->db->from('conhecimento_vaga'); $this->db->join('conhecimento', 'conhecimento_vaga.idconhecimento = conhecimento.idconhecimento'); $this->db->join('nivel_idioma', 'conhecimento_vaga.nivel = nivel_idioma.idnivel_idioma'); $this->db->where('conhecimento.idtipo_conhecimento = 2'); $this->db->where('conhecimento_vaga.id_vaga', $id); $result = $this->db->get(); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->result(); } /** * apaga_idioma * * Apaga dados de idioma do profissional * * @param int * @param int * @return boolean true ou false se existir o pedido */ public function apaga_idioma($id, $id_idioma) { log_message('debug', 'apaga_idioma'); $this->db->where('idconhecimento_vaga', $id_idioma); $this->db->where('id_vaga', $id); $this->db->delete('conhecimento_vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); } //****** INFORMATICA /** * get_informatica * * Seleciona um conhecimento de informática da vaga * * @param int * @param int * @return boolean true ou false se existir o pedido */ public function get_informatica($id, $id_informatica) { log_message('debug', 'get_informatica. Param1: ' . $id . ' Param2: ' . $id_informatica); $this->db->where('conhecimento_vaga.id_vaga', $id); $this->db->where('conhecimento_vaga.idconhecimento_vaga', $id_informatica); $result = $this->db->get('conhecimento_vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->row(); } /** * get_idiomas * * Busca os conhecimento de informática da vaga * * @param int * @return array */ public function get_informaticas($id) { log_message('debug', 'get_idiomas. Param1: ' . $id); $this->db->select('conhecimento_vaga.*, subtipo_conhecimento.subtipo_conhecimento'); $this->db->from('conhecimento_vaga'); $this->db->join('conhecimento', 'conhecimento_vaga.idconhecimento = conhecimento.idconhecimento'); $this->db->join('subtipo_conhecimento', 'conhecimento.idsubtipo_conhecimento = subtipo_conhecimento.idsubtipo_conhecimento'); $this->db->where('conhecimento.idtipo_conhecimento = 1'); $this->db->where('conhecimento_vaga.id_vaga', $id); $this->db->order_by('subtipo_conhecimento.subtipo_conhecimento'); $result = $this->db->get(); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->result(); } /** * apaga_informática * * Apaga dados de informática do profissional * * @param int * @param int * @return boolean true ou false se existir o pedido */ public function apaga_informatica($id, $id_informatica) { log_message('debug', 'apaga_informática'); $this->db->where('idconhecimento_vaga', $id_informatica); $this->db->where('id_vaga', $id); $this->db->delete('conhecimento_vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); } /*** CURSOS /** * get_curso * * Seleciona um curso requerido da vaga * * @param int * @param int * @return boolean true ou false se existir o pedido */ public function get_curso($id, $idcurso) { log_message('debug', 'get_curso. Param1: ' . $id . ' Param2: ' . $idcurso); $this->db->where('idvaga', $id); $this->db->where('idformacao_vaga', $idcurso); $result = $this->db->get('formacao_vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->row(); } /** * get_cursos * * Busca as formações necessárias para a vaga * * @param int * @return array */ public function get_cursos($id) { log_message('debug', 'get_cursos. Param1: ' . $id); $this->db->where('idvaga', $id); $result = $this->db->get('formacao_vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->result(); } /** * apaga_cursos * * Apaga curso requerido para a vaga * * @param int * @param int * @return boolean true ou false se existir o pedido */ public function apaga_cursos($id, $idcurso) { log_message('debug', 'apaga_idioma'); $this->db->where('idvaga', $id); $this->db->where('idformacao_vaga', $idcurso); $this->db->delete('formacao_vaga'); log_message('debug', 'Last Query: ' . $this->db->last_query()); } /** * informacao_basica * * Traz nome, porcentagem do currículo preenchido e data da última atualização do currículo * * @param int * @return array */ public function informacao_basica($id) { log_message('debug', 'informacao_basica. Param1: ' . $id); $this->db->select('p.nome, p.porcentagem_cadastro, ph.data'); $this->db->from('profissional p'); $this->db->join('profissional_historico ph', 'p.idprofissional = ph.idprofissional'); $this->db->where('p.idprofissional', $id); $this->db->where('ph.idacao = 2'); $this->db->order_by('ph.idprofissional_historico', 'DESC'); $this->db->limit(1); $result = $this->db->get(); return $result->row(); } public function busca_informatica($conhecimento) { log_message('debug', 'busca_idioma. Param1: ' . $conhecimento); $this->db->select('conhecimento.idconhecimento, conhecimento.conhecimento'); $this->db->from('conhecimento'); $this->db->like('conhecimento.conhecimento', $conhecimento, 'both'); $this->db->where('idtipo_conhecimento', '1'); $this->db->order_by('conhecimento.conhecimento'); $result = $this->db->get(); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->result(); } public function busca_idioma($conhecimento) { log_message('debug', 'busca_idioma. Param1: ' . $conhecimento); $this->db->select('conhecimento.idconhecimento, conhecimento.conhecimento'); $this->db->from('conhecimento'); $this->db->like('conhecimento.conhecimento', $conhecimento, 'both'); $this->db->where('idtipo_conhecimento', '2'); $this->db->order_by('conhecimento.conhecimento'); $result = $this->db->get(); log_message('debug', 'Last Query: ' . $this->db->last_query()); return $result->result(); } } ?>
true
0dd0b1602c8ac8f97073613307c94a30711e6b23
PHP
LoicFeuga/ShareEverything
/php/classes/Room.php
UTF-8
1,523
3.078125
3
[]
no_license
<?php class Room{ private $id; private $name; private $description; private $id_tchat; private $pdo; public function __construct($name ="no_name", $description = "no_description",$pdo){ $this->name = $name; $this->description = $description; $this->pdo = $pdo; } public function insertRoom(){ $this->pdo->execute("INSERT INTO se_room (name, description) VALUES ('".$this->name."', '".$this->description."') "); } public function createTchat(){ $req = $this->pdo->queryOne("SELECT MAX(id_tchat) AS id_tchat FROM se_room "); $this->id_tchat = $req->id_tchat; $this->id_tchat++; $this->pdo->execute("UPDATE se_room SET id_tchat = '".$this->id_tchat."' WHERE name= '".$this->name."' "); } public function getId(){ return $this->id; } public function getIdTchat(){ return $this->id_tchat; } public function setId($id){ $this->id=$id; } public function exist(){ $req = $this->pdo->queryOne("SELECT * FROM se_room WHERE name = '".$this->name."' "); if($req->id != 0 && $req !=NULL){ return 1; }else{ return 0; } } public function getRoom(){ $req = $this->pdo->queryOne("SELECT * FROM se_room WHERE name = '".$this->name."' "); $this->id = $req->id; $this->description = $req->description; } public function setRoomFromBDD(){ $req = $this->pdo->queryOne("SELECT * FROM se_room WHERE name = '".$this->name."' "); $this->id = $req->id; $this->description = $req->description; $this->id_tchat = $req->id_tchat; $this->name = $req->name; } } ?>
true
f833529a38a8a0ffc17a4977d4c9c86d784a813e
PHP
newsukarun/nts_hackathon
/inc/rest-api/sms/sms-no-food.php
UTF-8
1,521
2.59375
3
[]
no_license
<?php use NTSFOOD\SMS_Sender; class NTS_FOOD_Coupon extends WP_REST_Controller { //The namespace and version for the REST SERVER var $ntsfood_namespacce = 'sms/v'; var $ntsfood_version = '1'; public function register_routes() { $namespace = $this->ntsfood_namespacce . $this->ntsfood_version; $base = 'nofood'; register_rest_route( $namespace, '/' . $base, array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'food_opt_out' ), ), ) ); } // Register our REST Server public function hook_rest_server() { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } public function food_opt_out( WP_REST_Request $request ) { $keyword = filter_input( INPUT_POST, 'keyword', FILTER_SANITIZE_STRING ); $message = filter_input( INPUT_POST, 'message', FILTER_SANITIZE_STRING ); $msg_fragments = explode( ' ', $message ); $msg_fragments = array_map( 'trim', $msg_fragments ); if( 2 < count( $msg_fragments ) ) { return new WP_REST_Response( [ 'message' => __( 'Invalid SMS!' ) ], 403 ); } $sms_handler = new NTSFOOD\SMS_Sender( [ 'employee' => $message ] ); $send_sms = $sms_handler->send_sms(); if( is_wp_error( $send_sms ) ) { return new WP_REST_Response( [ 'message' => $send_sms->get_error_message() ], 403 ); } return new WP_REST_Response( [ 'message' => __( 'Coupon sent successfully' ) ], 200 ); } } $my_rest_server = new NTS_FOOD_Coupon(); $my_rest_server->hook_rest_server();
true
5fa47589bab66673a63eb8ddc7100155121c9894
PHP
MarijaJankovic623/PSI_Implementacija
/application/models/UserValidationModel.php
UTF-8
33,112
2.921875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php /** * Description of registrationModel * * @author Marija */ class UserValidationModel extends CI_Model { public function __construct() { parent::__construct(); $this->load->library("my_database"); } /** * Provera sesije za sve vrste korisnika. * * Poziva se unutar ostalih funkcija za proveru sesija * ona proverava samo da li je korisnik koji pokusava da prostupi * ulogovan i ako nije vraca ga na pocetnu stranu sistema. * * */ public function checkSession() { $is_logged_in = $this->session->userdata('loggedIn'); if (!isset($is_logged_in) || $is_logged_in != true) { redirect("ErrorCtrl"); } } public function checkSessionKorisnik() { $this->checkSession(); $korisnik = $this->session->userdata('korisnik'); if (!$korisnik) { redirect("ErrorCtrl"); } } public function checkSessionRestoran() { $this->checkSession(); $restoran = $this->session->userdata('restoran'); if (!$restoran) { redirect("ErrorCtrl"); } } public function checkSessionKonobar() { $this->checkSession(); $konobar = $this->session->userdata('konobar'); if (!$konobar) { redirect("ErrorCtrl"); } } public function checkSessionAdmin() { $this->checkSession(); $admin = $this->session->userdata('admin'); if (!$admin) { redirect("ErrorCtrl"); } } /** * Logovanje korisnika. * * Proverava da li korisnik sa datim imenom i sifrom * postoji, i ako postoji puni podatke o sesiji i vraca * poruku o uspehu, u suprotnom o neuspehu. * * @param string $kime Korisnicko ime * @param string $lozinka Korisnicka lozinka * @return boolean Informacija o uspehu logovanja */ public function loginKorisnik($kime, $lozinka) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); //dohvatanje iskaza $stmt->prepare("SELECT * FROM korisnik WHERE KIme = ? AND Lozinka = ?"); //pravljenje istog $stmt->bind_param("ss", $kime, $lozinka); //vezivanej parametara $stmt->execute(); $kor = $stmt->get_result()->fetch_assoc(); if (isset($kor['IDKorisnik'])) { $data = array( 'userid' => $kor['IDKorisnik'], 'username' => $kime, 'loggedIn' => true, 'korisnik' => true, 'restoran' => false, 'konobar' => false, 'admin' => false ); $this->session->set_userdata($data); return true; } else { return false; } } /** * Logovanje restorana. * * Proverava da li restoran sa datim imenom i sifrom * postoji, i ako postoji puni podatke o sesiji i vraca * poruku o uspehu, u suprotnom o neuspehu. * * @param string $kime Korisnicko ime * @param string $lozinka Korisnicka lozinka * @return boolean Informacija o uspehu logovanja */ public function loginRestoran($kime, $lozinka) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); //dohvatanje iskaza $stmt->prepare("SELECT * FROM restoran WHERE KIme = ? AND Lozinka = ?"); //pravljenje istog $stmt->bind_param("ss", $kime, $lozinka); //vezivanej parametara $stmt->execute(); $res = $stmt->get_result()->fetch_assoc(); if (isset($res['IDRestoran'])) { $data = array( 'userid' => $res['IDRestoran'], 'username' => $kime, 'loggedIn' => true, 'restoran' => true, 'konobar' => false, 'korisnik' => false, 'admin' => false ); $this->session->set_userdata($data); return true; } else { return false; } } /** * Logovanje konobara. * * Proverava da li konobar sa datim imenom i sifrom * postoji, i ako postoji puni podatke o sesiji i vraca * poruku o uspehu, u suprotnom o neuspehu. * * @param string $kime Korisnicko ime * @param string $lozinka Korisnicka lozinka * @return boolean Informacija o uspehu logovanja */ public function loginKonobar($kime, $lozinka) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); //dohvatanje iskaza $stmt->prepare("SELECT * FROM konobar WHERE KIme = ? AND Lozinka = ?"); //pravljenje istog $stmt->bind_param("ss", $kime, $lozinka); //vezivanej parametara $stmt->execute(); $res = $stmt->get_result()->fetch_assoc(); if (isset($res['IDKonobar'])) { $data = array( 'userid' => $res['IDKonobar'], 'username' => $kime, 'loggedIn' => true, 'konobar' => true, 'korisnik' => false, 'restoran' => false, 'admin' => false ); $this->session->set_userdata($data); return true; } else { return false; } } /** * Logovanje administratora. * * Proverava da li administrator sa datim imenom i sifrom * postoji, i ako postoji puni podatke o sesiji i vraca * poruku o uspehu, u suprotnom o neuspehu. * * @param string $kime Korisnicko ime * @param string $lozinka Korisnicka lozinka * @return boolean Informacija o uspehu logovanja */ public function loginAdmin($kime, $lozinka) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("SELECT * FROM admin WHERE KIme = ? AND Lozinka = ?"); $stmt->bind_param("ss", $kime, $lozinka); $stmt->execute(); $res = $stmt->get_result()->fetch_assoc(); if (isset($res['IDAdmin'])) { $data = array( 'userid' => $res['IDAdmin'], 'username' => $kime, 'loggedIn' => true, 'admin' => true, 'konobar' => false, 'korisnik' => false, 'restoran' => false ); $this->session->set_userdata($data); return true; } else { return false; } } /** * Proverava da li je moguce loginovanje bilo kog tipa korisnika * * Metoda poziva sve metode vezane za proveru loginovanja odredjee vrste korisnika * * * @param string $kime korisniko ime * @param string $lozinka korisnicka lozinka * @return boolean uspesnos mogucnosti logovanja */ public function login($kime, $lozinka) { if ($this->loginKorisnik($kime, $lozinka) || $this->loginKonobar($kime, $lozinka) || $this->loginRestoran($kime, $lozinka) || $this->loginAdmin($kime, $lozinka)) { return true; } else { return false; } } /** * Proverava da li je registracija restorana moguca * * Metoda prihvata sve parametre vezane za registraciju restorana i proverava ih * shodno pravilima sistema. Ukoliko sve provere prodju kreira se restoran sa odredjenom galerijom slika, * i stolovima.(sto i slike su naglaseni jer oni nisu samo polja u restoranu vec i posebne tabele u bazi) * * @param array $res asocijativni niz koji sadrzi sve podatke unete preko forme za registraciju restorana * @return boolean uspesnost registracije restorana */ public function validateCreateRestoran($res) { $conn = $this->my_database->conn; $conn->autocommit(FALSE); $ok = true; $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $this->load->database(); $this->form_validation->set_rules('kime', 'korisnicko ime', 'is_unique[Korisnik.KIme]|is_unique[Restoran.KIme]|is_unique[Konobar.KIme]|is_unique[Admin.KIme]|min_length[4]|max_length[49]|trim|required'); $this->form_validation->set_rules('kod', 'kod za registraciju konobara', 'is_unique[Restoran.KodKonobara]|trim|required|min_length[3]|max_length[10]'); $this->form_validation->set_rules('lozinka', 'lozinka', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('iobj', 'ime objekta', 'required|trim|min_length[3]|max_length[49]'); $this->form_validation->set_rules('ivlasnika', 'ime vlasnika', 'required|trim|min_length[3]|max_length[49]'); $this->form_validation->set_rules('pvlasnika', 'prezime vlasnika', 'required|trim|min_length[4]|max_length[49]'); $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim|min_length[4]|max_length[49]'); $this->form_validation->set_rules('kuhinje', 'kuhinje', 'required|trim|min_length[4]|max_length[999]'); $this->form_validation->set_rules('opis', 'opis restorana', 'required|trim|min_length[4]|max_length[2999]'); if ($this->form_validation->run() == FALSE) { return false; } else { $stmt = $conn->stmt_init(); $stmt->prepare("INSERT INTO restoran(KIme,Lozinka,ImeObjekta, ImeVlasnika,PrezimeVlasnika,Email,Opis,Kuhinja,Opstina,KodKonobara)VALUES(?,?,?,?,?,?,?,?,?,?)"); $stmt->bind_param("sssssssssi", $res['kime'], $res['lozinka'], $res['iobj'], $res['ivlasnika'], $res['pvlasnika'], $res['email'], $res['opis'], $res['kuhinje'], $res['opstina'], $res['kod']); $stmt->execute() ? null : $ok = false; $restoranId = $stmt->insert_id; if (is_numeric($res['sto2'])) { for ($i = 1; $i <= $res['sto2']; $i++) { $this->createSto(2, $restoranId) ? null : $ok = false; } } if (is_numeric($res['sto4'])) { for ($i = 1; $i <= $res['sto4']; $i++) { $this->createSto(4, $restoranId) ? null : $ok = false; } } if (is_numeric($res['sto6'])) { for ($i = 1; $i <= $res['sto6']; $i++) { $this->createSto(6, $restoranId) ? null : $ok = false; } } if(!( $this->uploadSlika($restoranId) == true)) $ok = false; if ($ok == false) { $conn->rollback(); $conn->autocommit(TRUE); return false; } else { $conn->commit(); } $conn->autocommit(TRUE); return true; } } /** * Vrsi cuvanje napravljenih izmena na profilu restorana * * Metoda prima sve parametre vezane za izmenu profila restorana * i vrsi provere nad njima shodno pravilima sistema. Ukoliko sve * provere prodju, pamte se promene u bazi. Ukoliko ne prodju, izmene * nece biti upamcene i vraca se poruka o neuspehu. * * @param array $restoran asocijativni niz koji sadrzi sve podatke o restoranu koji su uneti u formu * @param integer $id ID restorana * @return boolean Uspeh/neuspeh */ public function updateRestaurant($restoran, $id) { $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $this->load->database(); $this->form_validation->set_rules('lozinka', 'lozinka', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('iobj', 'ime objekta', 'required|trim|min_length[3]|max_length[49]'); $this->form_validation->set_rules('ivlasnika', 'ime vlasnika', 'required|trim|min_length[3]|max_length[49]'); $this->form_validation->set_rules('pvlasnika', 'prezime vlasnika', 'required|trim|min_length[4]|max_length[49]'); $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim|min_length[4]|max_length[49]'); $this->form_validation->set_rules('kuhinje', 'kuhinje', 'required|trim|min_length[4]|max_length[999]'); $this->form_validation->set_rules('opis', 'opis restorana', 'required|trim|min_length[4]|max_length[2999]'); if ($this->form_validation->run() == FALSE) { return false; } else { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("UPDATE restoran SET Lozinka=?,ImeObjekta=?,ImeVlasnika=?,PrezimeVlasnika=?,Email=?,Opis=?,Kuhinja=?,Opstina=? WHERE IDRestoran=?"); $stmt->bind_param("ssssssssi", $restoran['lozinka'], $restoran['iobj'], $restoran['ivlasnika'], $restoran['pvlasnika'], $restoran['email'], $restoran['opis'], $restoran['kuhinje'], $restoran['opstina'], $id); $stmt->execute(); $restoranId = $stmt->insert_id; if (is_numeric($restoran['sto2'])) { $this->TableForTwo($restoran, $id); } if (is_numeric($restoran['sto4'])) { $this->TableForFour($restoran, $id); } if (is_numeric($restoran['sto6'])) { $this->TableForSix($restoran, $id); } return true; } } /** * Pravi nove stolove za dvoje, ili brise stare, prilikom update-a * profila restorana * * Metoda prima asocijativni niz svih podataka o restoranu * cija se izmena vrsi i, na osnovu novog broja stolova koji je * za tu kolicinu ljudi, dodaju se novi stolovi u bazu, ili se * brise razlika prethodnih i novih. * * @param array $restoran asocijativni niz podataka o restoranu * @param integer $id ID restorana */ public function TableForTwo($restoran, $id) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $param['broj'] = 2; $stmt->prepare("SELECT * FROM sto WHERE IDRestoranFK=? AND BrojOsoba=?"); $stmt->bind_param("ii", $id, $param['broj']); $stmt->execute(); $result = $stmt->get_result()->num_rows; if ($result > $restoran['sto2']) { for ($i = 1; $i <= ($result - $restoran['sto2']); $i++) { $this->deleteSto(2, $id); } } else if ($result < $restoran['sto2']) { for ($i = 1; $i <= ($restoran['sto2'] - $result); $i++) { $this->createSto(2, $id); } } } /** * Dodaje nove stolove za cetvoro, ili brise stare, prilikom * update-a profila restorana * * Metoda prima asocijativni niz svih podataka o restoranu * cija se izmena vrsi i, na osnovu novog broja stolova koji je * za tu kolicinu ljudi, dodaju se novi stolovi u bazu, ili se * brise razlika prethodnih i novih. * * @param array $restoran asocijativni niz podataka o restoranu * @param integer $id ID restorana */ public function TableForFour($restoran, $id) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $param['broj'] = 4; $stmt->prepare("SELECT * FROM sto WHERE IDRestoranFK=? AND BrojOsoba=?"); $stmt->bind_param("ii", $id, $param['broj']); $stmt->execute(); $result = $stmt->get_result()->num_rows; if ($result > $restoran['sto4']) { for ($i = 1; $i <= ($result - $restoran['sto4']); $i++) { $this->deleteSto(4, $id); } } else if ($result < $restoran['sto4']) { for ($i = 1; $i <= ($restoran['sto4'] - $result); $i++) { $this->createSto(4, $id); } } } /** * Dodaje nove stolove za sestoro, ili brise stare, prilikom * update-a profila restorana * * Metoda prima asocijativni niz svih podataka o restoranu * cija se izmena vrsi i, na osnovu novog broja stolova koji je * za tu kolicinu ljudi, dodaju se novi stolovi u bazu, ili se * brise razlika prethodnih i novih. * * @param array $restoran asocijativni niz podataka o restoranu * @param integer $id ID restorana */ public function TableForSix($restoran, $id) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $param['broj'] = 6; $stmt->prepare("SELECT * FROM sto WHERE IDRestoranFK=? AND BrojOsoba=?"); $stmt->bind_param("ii", $id, $param['broj']); $stmt->execute(); $result = $stmt->get_result()->num_rows; if ($result > $restoran['sto6']) { for ($i = 1; $i <= ($result - $restoran['sto6']); $i++) { $this->deleteSto(6, $id); } } else if ($result < $restoran['sto6']) { for ($i = 1; $i <= ($restoran['sto6'] - $result); $i++) { $this->createSto(6, $id); } } } /** * Funkcija koja kreira sto za odredjeni restoran * * Funkcija koja vrsi insertovanje u bazu * Kreira novu tabelu sto za oredjeni restoran * * @param Integer $brojOsoba tip stola koji se kreira, koliko ljudi moze da sedne za isti * @param Integer $restoranId id restorana kome sto pripada */ public function createSto($brojOsoba, $restoranId) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("INSERT INTO sto(IDRestoranFK,BrojOsoba)VALUES(?,?)"); $stmt->bind_param("ii", $restoranId, $brojOsoba); return $stmt->execute(); } /** * Funkcija koja brise sto za odredjeni restoran * * Metoda prima broj osoba i id restorana, na osnovu kojih * povezuje koji sto u bazi treba da izbrise. Vrsi brisanje reda * iz baze. * * @param integer $brojOsoba koliko ljudi moze da sedne za sto * @param integer $id ID restorana kome taj sto pripada */ public function deleteSto($brojOsoba, $id) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("DELETE FROM sto WHERE IDRestoranFK=? AND BrojOsoba=? LIMIT 1"); $stmt->bind_param("ii", $id, $brojOsoba); $stmt->execute(); } /** * Proverava da li je registracija korisnika moguca. * * Metoda proverava sve parametre vezane za registraciju korisnika i * proverava ih u skladu sa pravilima sistema. Ukoliko su provere prosle * uspesno kreira se novi korisnik. * * @param array $kor Asocijativni niz koji sadrzi sve podatke * unete preko forme za registraciju korisnika * @return boolean Informacija o uspehu ili neuspehu registracije */ public function validateCreateKorisnik($kor) { $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $this->load->database(); $this->form_validation->set_rules('username', 'korisnicko ime', 'is_unique[Korisnik.KIme]|is_unique[Restoran.KIme]|is_unique[Konobar.KIme]|is_unique[Admin.KIme]|trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('name', 'ime vlasnika', 'trim|required|min_length[3]|max_length[49]'); $this->form_validation->set_rules('lastname', 'prezime vlasnika', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email'); if ($this->form_validation->run() == FALSE) { return false; } else { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("INSERT INTO korisnik(KIme,Lozinka,Ime,Prezime,Email)VALUES(?,?,?,?,?)"); $stmt->bind_param("sssss", $kor['username'], $kor['password'], $kor['name'], $kor['lastname'], $kor['email']); $stmt->execute(); return true; } } /** * Vrsi cuvanje napravljenih izmena na profilu korisnika * * Metoda prima sve parametre vezane za izmenu profila korisnika * i vrsi provere nad njima shodno pravilima sistema. Ukoliko sve * provere prodju, pamte se promene u bazi. Ukoliko ne prodju, izmene * nece biti upamcene i vraca se poruka o neuspehu. * * @param array $korisnik asocijativni niz podataka o korisniku koji se prosledjuju kroz formu * @param integer $id ID korisnika * @return boolean Uspeh/neuspeh */ public function updateUser($korisnik, $id) { $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $this->load->database(); $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('name', 'ime vlasnika', 'trim|required|min_length[3]|max_length[49]'); $this->form_validation->set_rules('lastname', 'prezime vlasnika', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email'); if ($this->form_validation->run() == FALSE) { return false; } else { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("UPDATE korisnik SET Lozinka=?,Ime=?,Prezime=?,Email=? WHERE IDKorisnik=?"); $stmt->bind_param("ssssi", $korisnik['password'], $korisnik['name'], $korisnik['lastname'], $korisnik['email'], $id); $stmt->execute(); return true; } } /** * Proverava da li je registracija konobara moguca. * * Metoda prihvata sve parametre vezane za registraciju admina i proverava ih * u skladu sa pravilima sistema. Ukoliko sve provere prodju uspesno, * kreira se novi konobar. * * @param array $konobar Asocijativni niz koji sadrzi sve podatke * unete preko forme za registraciju konobara * @return boolean Informacija o uspehu ili neuspehu registracije */ public function validateCreateKonobar($konobar) { $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $this->load->database(); $this->form_validation->set_rules('username', 'korisnicko ime', 'is_unique[Korisnik.KIme]|is_unique[Restoran.KIme]|is_unique[Konobar.KIme]|is_unique[Admin.KIme]|min_length[4]|max_length[49]|trim|required'); $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('name', 'ime vlasnika', 'trim|required|min_length[3]|max_length[49]'); $this->form_validation->set_rules('lastname', 'prezime vlasnika', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email'); $this->form_validation->set_rules('kod', 'kod konobara', 'required|trim|min_length[3]|max_length[10]'); $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("SELECT IDRestoran FROM restoran WHERE KodKonobara = ?"); $konobar['kod'] +=0; $stmt->bind_param("i", $konobar['kod']); $stmt->execute(); $result = $stmt->get_result()->fetch_array(); if ($this->form_validation->run() == FALSE || $result == null) { return false; } else { $konobar['IDRestoranFK'] = $result['IDRestoran'] + 0; $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("INSERT INTO konobar(KIme,Lozinka,Ime,Prezime,Email,IDRestoranFK)VALUES(?,?,?,?,?,?)"); $stmt->bind_param("sssssi", $konobar['username'], $konobar['password'], $konobar['name'], $konobar['lastname'], $konobar['email'], $konobar['IDRestoranFK']); $stmt->execute(); return true; } } /** * Vrsi cuvanje napravljenih izmena na profilu konobara * * Metoda prima sve parametre vezane za izmenu profila konobara * i vrsi provere nad njima shodno pravilima sistema. Ukoliko sve * provere prodju, pamte se promene u bazi. Ukoliko ne prodju, izmene * nece biti upamcene i vraca se poruka o neuspehu. * * @param array $konobar asocijativni niz podataka o konobaru koji se prosledjuju iz forme * @param integer $id ID konobar * @return boolean Uspeh/neuspeh */ public function updateWaiter($konobar, $id) { $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $this->load->database(); $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('name', 'ime vlasnika', 'trim|required|min_length[3]|max_length[49]'); $this->form_validation->set_rules('lastname', 'prezime vlasnika', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email'); if ($this->form_validation->run() == FALSE) { return false; } else { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("UPDATE konobar SET Lozinka=?,Ime=?,Prezime=?,Email=? WHERE IDKonobar=?"); $stmt->bind_param("ssssi", $konobar['password'], $konobar['name'], $konobar['lastname'], $konobar['email'], $id); $stmt->execute(); return true; } } /** * Proverava da li je registracija admina moguca. * * Metoda prihvata sve parametre vezane za registraciju admina i proverava ih * u skladu sa pravilima sistema. Ukoliko sve provere prodju uspesno kreira se novi admin. * * @param array $admin Asocijativni niz koji sadrzi sve podatke * unete preko forme za registraciju admina * @return boolean Informacija o uspehu ili neuspehu registracije */ public function validateCreateAdmin($admin) { $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $this->load->database(); $this->form_validation->set_rules('username', 'korisnicko ime', 'is_unique[Korisnik.KIme]|is_unique[Restoran.KIme]|is_unique[Konobar.KIme]|is_unique[Admin.KIme]|trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('name', 'ime admina', 'trim|required|min_length[3]|max_length[49]'); $this->form_validation->set_rules('lastname', 'prezime admina', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email'); $this->form_validation->set_rules('code', 'kod za admina', 'required|trim|min_length[3]|max_length[10]'); $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("SELECT IDAdmin FROM admin WHERE KodAdmina = ?"); $admin['kod'] +=0; $stmt->bind_param("i", $admin['kod']); $stmt->execute(); $result = $stmt->get_result()->fetch_array(); if ($this->form_validation->run() == FALSE || $result == NULL) { return false; } else { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("INSERT INTO admin(KIme,Lozinka,Ime,Prezime,Email,KodAdmina)VALUES(?,?,?,?,?,?)"); $stmt->bind_param("sssssi", $admin['username'], $admin['password'], $admin['ime'], $admin['prezime'], $admin['email'], $admin['kod']); $stmt->execute(); return true; } } /** * Vrsi cuvanje napravljenih izmena na profilu admina * * Metoda prima sve parametre vezane za izmenu profila admina * i vrsi provere nad njima shodno pravilima sistema. Ukoliko sve * provere prodju, pamte se promene u bazi. Ukoliko ne prodju, izmene * nece biti upamcene i vraca se poruka o neuspehu. * * @param array $admin asocijativni niz podataka o adminu koji se prosledjuju kroz formu * @param integer $id ID admin * @return boolean Uspeh/neuspeh */ public function updateAdmin($admin, $id) { $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $this->load->database(); $this->form_validation->set_rules('password', 'lozinka', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('name', 'ime admina', 'trim|required|min_length[3]|max_length[49]'); $this->form_validation->set_rules('lastname', 'prezime admina', 'trim|required|min_length[4]|max_length[49]'); $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[4]|max_length[49]|valid_email'); if ($this->form_validation->run() == FALSE) { return false; } else { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("UPDATE admin SET Lozinka=?,Ime=?,Prezime=?,Email=? WHERE IDAdmin=?"); $stmt->bind_param("ssssi", $admin['password'], $admin['ime'], $admin['prezime'], $admin['email'], $id); $stmt->execute(); return true; } } public function uploadSlika($id) { $target_dir = "./slike/" . $id . "/"; mkdir($target_dir); $total = count($_FILES['slike']['name']); for ($i = 0; $i < $total; $i++) { $target_file = $target_dir . basename($_FILES["slike"]["name"][$i]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if (isset($_POST["submit"])) { $check = getimagesize($_FILES["slike"]["tmp_name"][$i]); if ($check !== false) { $uploadOk = 1; } else { return "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { return "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["slike"]["size"][$i] > 500000) { return "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") { return "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { return "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["slike"]["tmp_name"][$i], $target_file)) { $this->insertSlika($id, $target_file); } else { return "Sorry, there was an error uploading your file."; } } } return true; } public function insertSlika($id, $target) { $conn = $this->my_database->conn; $stmt = $conn->stmt_init(); $stmt->prepare("INSERT INTO slika(IDRestoranFK, Putanja) VALUES(?,?)"); $stmt->bind_param("is", $id, $target); $stmt->execute(); } }
true
6db1335f586ccb6014ee05ab512bd40aa0a05832
PHP
christian-reis/loja-web-reis
/App/Action/Admin/LoginAction.php
UTF-8
2,071
2.53125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Christian Reis * Date: 14/06/2018 * Time: 17:24 */ namespace App\Action\Admin; use App\Action\Action; class LoginAction extends Action { public function index($request, $response){//renderiza a tela de login if(isset($_SESSION[PREFIX.'logado'])){ return $response->withRedirect(PATH.'/admin/products'); } //return $this->view->render($response,'admin/login/login.phtml'); $vars['title'] = 'Faça seu login'; $vars['page'] = 'login'; return $this->view->render($response,'template.phtml',$vars); //return $this->view->render($response,'page/login.phtml'); } public function login($request, $response){ //realiza o login, faz a operação com o banco de dados $data = $request->getParsedBody(); $email = strip_tags(filter_var($data['email'],FILTER_SANITIZE_STRING)); $pass = strip_tags(filter_var($data['pass'],FILTER_SANITIZE_STRING)); if($email != '' && $pass != ''){ $sql = "SELECT * FROM `user` WHERE email_user = ? AND pass_user = ?"; $user = $this->db->prepare($sql); $user->execute(array($email,$pass)); if($user->rowCount() > 0){ $r = $user->fetch(\PDO::FETCH_OBJ); $_SESSION[PREFIX.'logado'] = true; $_SESSION[PREFIX.'id_user'] = $r->iduser; return $response->withRedirect(PATH.'/admin/products'); }else{ $vars['erro'] = 'Você não foi encontrado no sistema.'; return $this->view->render($response,'admin/login/login.phtml',$vars); } }else{ $vars['erro'] = 'Preencha todos os campos.'; return $this->view->render($response,'admin/login/login.phtml',$vars); } } public function logout($request, $response){ //destroi a sessão, saindo da área administrativa unset($_SESSION[PREFIX.'logado']); session_destroy(); return $response->withRedirect(PATH.'/'); } }
true
04ea58ec13273e53ebabdad319663de93963abcd
PHP
dru-id/sdk-consumer-rewards
/src/Security/Authentication.php
UTF-8
2,223
2.71875
3
[]
no_license
<?php namespace ConsumerRewards\SDK\Security; use ConsumerRewards\SDK\Exception\ConsumerRewardsSdkAuthException; use ConsumerRewards\SDK\Tools\Container; use ConsumerRewards\SDK\Tools\RequiredParameterTrait; use ConsumerRewards\SDK\Tools\UserPasswordGrantTrait; class Authentication { use RequiredParameterTrait; use UserPasswordGrantTrait; /** * @var AuthCredentials $credentials */ private $credentials; /** * @var JWT $jwt */ protected $jwt; public static function build() { return new Authentication(); } /** * AuthCredentials constructor. */ public function __construct() { } /** * @return AuthCredentials */ public function getCredentials(): AuthCredentials { return $this->credentials; } /** * @param AuthCredentials $credentials * @return Authentication */ public function setCredentials(AuthCredentials $credentials): Authentication { $this->credentials = $credentials; return $this; } /** * @return JWT */ public function getJwt(): JWT { return $this->jwt; } /** * @param JWT $jwt */ public function setJwt(JWT $jwt) { $this->jwt = $jwt; } /** * @return JWT token for Bearer Auth Request * @throws ConsumerRewardsSdkAuthException */ public function authorize() { $this->checkRequiredParameters($this->getRequiredRequestParameters(), $this->getCredentials()->jsonSerialize()); $options['body'] = \GuzzleHttp\json_encode($this->getCredentials()); $request = Container::get('http')->getRequest('POST', Container::get('http')->buildApiUrl('/auth'), $options); $response = Container::get('http')->getResponse($request, ['http_errors' => false]); if (($response->hasHeader('Authorization')) && ($response->hasHeader('Expires'))) { $this->setJwt(new JWT($response->getHeaderLine('Authorization'), strtotime($response->getHeaderLine('Expires')))); } else { throw new ConsumerRewardsSdkAuthException("Not Auth Response from Server"); } return $this->getJwt(); } }
true