{ // 获取包含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 !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转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 !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; 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, 'OCR模型免费转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\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2,"cells":{"blob_id":{"kind":"string","value":"e47b73fe4b910d3beaab00a746cb3a94340bd147"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"jhonharoldpizarro2021/agricolaApp"},"path":{"kind":"string","value":"/querys/q_informe_costos.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3328,"string":"3,328"},"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":" $row[\"id_unidad_agricola\"],\n \"tc\" => $row[\"tipo_costo\"],\n \"valor\" => $row[\"valor\"],\n );\n if ( !in_array( $row[\"id_unidad_agricola\"],$suertes ) ){\n $suertes[] = $row[\"id_unidad_agricola\"];\n $nSuerte[] = $row[\"nombre_unidad_agricola\"];\n $finca[] = $row[\"id_finca\"];\n $nFinca[] = $row[\"nombre_finca\"];\n }\n }\n $informeSuertes = array();\n \n for ($i=0; $i < count($suertes); $i++){\n $queryTmp = \"SELECT * FROM qryInformeCostos WHERE id_unidad_agricola='\".$suertes[$i].\"'\";\n $resultadoTmp = mysqli_query($con, $queryTmp);\n $informeTmp = array();\n while( $rowTmp = mysqli_fetch_array( $resultadoTmp ) ){\n $informeTmp[] = array(\n \"tc\" => $rowTmp[\"tipo_costo\"],\n \"valor\" => $rowTmp[\"valor\"],\n );\n if ( !array_key_exists( $rowTmp[\"tipo_costo\"],$colores ) ){\n $queryColor = \" SELECT valor FROM parametros_generales WHERE nombre='\".$rowTmp[\"tipo_costo\"].\"' AND tipo='color' \";\n $resultadoColor = mysqli_query($con, $queryColor);\n if ($rowColor = mysqli_fetch_array($resultadoColor )){\n $colores[$rowTmp[\"tipo_costo\"]] = $rowColor[\"valor\"];\n }\n }\n }\n $informeSuertes[]=array(\n \"idFinca\" => $finca[$i],\n \"nFinca\" => $nFinca[$i],\n \"idSuerte\" => $suertes[$i],\n \"nSuerte\" => $nSuerte[$i],\n \"informes\" => $informeTmp,\n \"query\" => $queryTmp,\n ); \n }\n //retorno\n if( count($informe) > 0) {\n $retorno[\"estado\"] = \"OK\";\n $retorno[\"informe\"] = $informe;\n $retorno[\"informeSuertes\"] = $informeSuertes;\n $retorno[\"colores\"] = $colores;\n }\n else {\n $retorno[\"estado\"] = \"EMPTY\";\n }\n break; \n }\n if( !close_bd($con) ) {\n $retorno[\"msg\"] = \"Error al cerrar la conexión a la BDD\";\n }\n }\n else {\n $retorno[\"estado\"] = \"ERROR\";\n $retorno[\"msg\"] = \"Error de conexión a la BDD:\". mysqli_connect_error();\n }\n}\nelse {\n $retorno[\"estado\"] = \"ERROR\";\n $retorno[\"msg\"] = \"Parámetros no encontrados\";\n}\nheader('Content-Type: application/json; charset=utf-8');\necho json_encode( $retorno );\n\n?>\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":3,"cells":{"blob_id":{"kind":"string","value":"ae81f87dfe291586fe18e2cb1ef8530080064749"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"RenLiZhou/laravel_admin"},"path":{"kind":"string","value":"/app/Http/Controllers/Controller.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":982,"string":"982"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"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":"fails()) {\n $bags = $validator->getMessageBag()->toArray();\n foreach ($bags as $bag) {\n foreach ($bag as $item) {\n return $item;\n }\n }\n }\n return null;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":4,"cells":{"blob_id":{"kind":"string","value":"f8b576e114554e94365232a843ca549b298cc800"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"netgen-layouts/layouts-contentful"},"path":{"kind":"string","value":"/lib/Routing/EntrySluggerInterface.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":305,"string":"305"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"all();\n $this->validate($request, [\n 'name'=>'required',\n 'phone'=>'required|max:10|unique:member',\n 'password' => 'min:6|same:password2',\n ],\n [\n 'password.same' => 'Password Not Matching',\n ]);\n\n //$input = $request->all();\n //$input['password'] = Hash::make($request->password);\n\n Member::create($request->all());//strore to database\n return redirect('/');\n }\n\n /**\n * Display the specified resource.\n *\n * @param \\App\\Models\\Register $register\n * @return \\Illuminate\\Http\\Response\n */\n public function show(Register $register)\n {\n //\n }\n\n /**\n * Show the form for editing the specified resource.\n *\n * @param \\App\\Models\\Register $register\n * @return \\Illuminate\\Http\\Response\n */\n public function edit(Register $register)\n {\n //\n }\n\n /**\n * Update the specified resource in storage.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\App\\Models\\Register $register\n * @return \\Illuminate\\Http\\Response\n */\n public function update(Request $request, Register $register)\n {\n //\n }\n\n /**\n * Remove the specified resource from storage.\n *\n * @param \\App\\Models\\Register $register\n * @return \\Illuminate\\Http\\Response\n */\n public function destroy(Register $register)\n {\n //\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":6,"cells":{"blob_id":{"kind":"string","value":"42e089ec4638894bed82e40ad2bbde973a0fadab"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"Edwin-En/Accedo"},"path":{"kind":"string","value":"/3. API con PHP/PokemonAPI/login.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1504,"string":"1,504"},"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":"prepare('SELECT id, email, password FROM usuarios WHERE email=:email');\n $records->bindParam(':email', $_POST['email']);\n $records->execute();\n $results = $records->fetch(PDO::FETCH_ASSOC);\n\n $message = '';\n\n if (count($results) > 0 && password_verify($_POST['password'], $results['password'])) {\n $_SESSION['user_id'] = $results['id'];\n header('Location: /PokemonAPI/index.php');\n } else {\n $message = \"Las contraseñas no coinciden\";\n }\n\n }\n\n?>\n\n\n\n \n \n Inicio de sesion \n\n \n\n \n \n\n \n\n

Inicia sesion

\n o Registrate \n\n \n

\n \n\n

\n \n \n \n
\n\n\n \n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":7,"cells":{"blob_id":{"kind":"string","value":"4d2dfaa51b0edabb9fecb4217f28af34635c2a55"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"eskguptha/php"},"path":{"kind":"string","value":"/read_csv.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":824,"string":"824"},"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":"\n\n\n\t\n\n\n\n

Read data from csv using php

\n\n\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n \n \n \n \n \n \n \n \n \n \n \n \n \n
SKUNameCategoryPriceQty
\n\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":8,"cells":{"blob_id":{"kind":"string","value":"19ddef5195ac36e49aef493cb42e45529ac43e66"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"zikezhang/LaravelAdmin"},"path":{"kind":"string","value":"/src/Verecom/Admin/User/Form/PasswordForm.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2222,"string":"2,222"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"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":"users = $users;\n $this->validator = $validator;\n $this->mailer = $mailer;\n }\n\n /**\n *\n *\n * @author ZZK\n * @link http://verecom.com\n *\n * @param $email\n *\n * @return void\n */\n public function forgot($email)\n {\n $user = $this->users->findByLogin($email);\n $this->mailer->sendReset($user);\n Event::fire('users.password.forgot', array($user));\n }\n\n /**\n * Reset a given user password\n *\n * @author ZZK\n * @link http://verecom.com\n *\n * @param array $creds\n *\n * @return bool\n */\n public function reset(array $creds)\n {\n try\n {\n if ($this->validator->with($creds)->passes())\n {\n $this->users->resetPassword($creds['code'],$creds['password']);\n return true;\n }\n }\n catch (UserNotFoundException $e)\n {\n $this->validator->add('UserNotFoundException',$e->getMessage());\n }\n\n return false;\n\n }\n\n /**\n * Get the validation errors\n *\n * @author ZZK\n * @link http://verecom.com\n *\n * @return array\n */\n public function getErrors()\n {\n return $this->validator->errors();\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":9,"cells":{"blob_id":{"kind":"string","value":"28f42776206c068a3fb1a5e3479eca82fefbbf6c"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"aheadWorks/module-langshop"},"path":{"kind":"string","value":"/Api/Data/TranslatableResource/PaginationInterface.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1107,"string":"1,107"},"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":"attributes['student_id']=ucwords($value);\n }\n\n\n public function setAmountPaidAttribute($value)\n {\n $this->attributes['amount_paid']=ucwords($value);\n }\n\n\n public function setPaymentModeAttribute($value)\n {\n $this->attributes['payment_mode']=ucwords($value);\n }\n\n\n public function setReferenceNoAttribute($value)\n {\n $this->attributes['reference_no']=strtoupper($value);\n }\n \n \n public function setReceiptNoAttribute($value)\n {\n $this->attributes['receipt_no']=strtoupper($value);\n }\n\n\n public function setDatePaiddAttribute($value)\n {\n $this->attributes['date_paid']=ucwords($value);\n }\n\n\n\n public function student()\n {\n return $this->belongsTo('App\\Model\\Student');\n }\n \n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":11,"cells":{"blob_id":{"kind":"string","value":"e363598aa8ad134e038d964173d661c38573641d"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"moahmedmish/code_repository"},"path":{"kind":"string","value":"/app/Http/Controllers/RepositoryController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1377,"string":"1,377"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"repositoryIntegrationServices = $repositoryIntegrationServices;\n }\n\n /**\n * GET DATA FROM Code Repository.\n *\n * @param Request $request\n * @return \\Illuminate\\Http\\JsonResponse\n */\n public function get(FilterDataRequest $request,$code_repository)\n {\n $finalResults = $this->repositoryIntegrationServices->filterData($request->all(),$code_repository);\n\n if (! $finalResults && count($finalResults)) {\n return $this->_ReturnJsonResponse('Failed Operation : Something Went Wrong ...!', [], [], Response::HTTP_BAD_REQUEST);\n }\n\n return $this->_ReturnJsonResponse('Successfully Operation.', [], $finalResults, Response::HTTP_OK);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":12,"cells":{"blob_id":{"kind":"string","value":"955f0a07895735b60f4327c756169bc827da9f9d"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"koftikes/symfony-adminlte-bundle"},"path":{"kind":"string","value":"/src/Model/NotificationInterface.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":736,"string":"736"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"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":"get_columns();\n $hidden = $this->get_hidden_columns();\n $sortable = $this->get_sortable_columns();\n $action = $this->current_action();\n\n $data = $this->table_data();\n usort( $data, array( &$this, 'sort_data' ) );\n\n $perPage = 10;\n $currentPage = $this->get_pagenum();\n $totalItems = count($data);\n\n $this->set_pagination_args( array(\n 'total_items' => $totalItems,\n 'per_page' => $perPage\n ) );\n\n $data = array_slice($data,(($currentPage-1)*$perPage),$perPage);\n $this->_column_headers = array($columns, $hidden, $sortable);\n\n $search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : false;\n if(!empty($search)){\n global $wpdb;\n \n try {\n $search = sanitize_text_field( $search );\n $data = $wpdb->get_results(\"SELECT * FROM {$wpdb->prefix}lic_activations WHERE UserName LIKE '%$search%'\", ARRAY_A);\n if(!is_wp_error( $wpdb )){\n $this->items = $data;\n }\n } catch (\\Throwable $th) {\n //throw $th;\n }\n\n }else{\n $this->items = $data;\n }\n \n }\n\n /**\n * Override the parent columns method. Defines the columns to use in your listing table\n *\n * @return Array\n */\n public function get_columns(){\n $columns = array(\n 'cb' => '',\n 'ID' => 'ID',\n 'Orderno' => 'Order No',\n 'Mtid' => 'Mtid',\n 'Userid' => 'User ID',\n 'UserName' => 'User Name',\n 'Prodcode' => 'Product Code',\n 'Status' => 'Status',\n 'Comment' => 'Comment',\n 'Editable' => 'Editable',\n 'Expirytime' => 'Expirytime',\n 'Modifydate' => 'Modifydate'\n );\n\n return $columns;\n }\n\n /**\n * Define which columns are hidden\n *\n * @return Array\n */\n public function get_hidden_columns()\n {\n return array();\n }\n\n /**\n * Define the sortable columns\n *\n * @return Array\n */\n public function get_sortable_columns()\n {\n return array(\n 'ID' => array('ID', true),\n 'Orderno' => array('Orderno', true),\n 'Mtid' => array('Mtid', true),\n 'Userid' => array('Userid', true),\n 'UserName' => array('UserName', true)\n );\n }\n\n\n /**\n * Get the table data\n *\n * @return Array\n */\n private function table_data(){\n $data = array();\n\n global $wpdb;\n\n $data = $wpdb->get_results(\"SELECT * FROM {$wpdb->prefix}lic_activations ORDER BY ID ASC\", ARRAY_A);\n \n return $data;\n }\n\n /**\n * Define what data to show on each column of the table\n *\n * @param Array $item Data\n * @param String $column_name - Current column name\n *\n * @return Mixed\n */\n public function column_default( $item, $column_name ){\n switch( $column_name ) {\n case 'ID':\n case 'Orderno':\n case 'Mtid':\n case 'Userid':\n case 'UserName':\n case 'Prodcode':\n case 'Status':\n case 'Comment':\n case 'Editable':\n case 'Expirytime':\n case 'Modifydate':\n return $item[ $column_name ];\n default:\n return print_r( $item, true ) ;\n }\n }\n\n function get_bulk_actions() {\n $actions = array(\n 'products_disable' => 'Disable Lifetime License',\n 'subscription_disable' => 'Disable Subscription License',\n 'enable_products_' => 'Enable Lifetime License',\n 'enable_subscription_' => 'Enable Subscription License'\n );\n return $actions;\n }\n\n function column_cb($item) {\n return sprintf(\n '', $item['Orderno']\n ); \n }\n\n // All form actions\n function current_action(){\n global $wpdb;\n\n if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'products_disable'){\n if(isset($_REQUEST['orders']) && !empty($_REQUEST['orders'])){\n $orders_data = $_REQUEST['orders'];\n if(is_array($orders_data)){\n foreach($orders_data as $data){\n \n $order_id = $data;\n \n $order = wc_get_order( $order_id );\n if($order !== false){\n $items = $order->get_items();\n \n foreach ( $items as $item ) {\n $product_id = $item->get_product_id();\n \n if(WC_Product_Factory::get_product_type($product_id) !== 'subscription'){\n $wpdb->update($wpdb->prefix.'lic_activations', array(\n 'Editable' => 0\n ),array( 'Orderno' => $order_id ),array('%d'),array('%d'));\n }\n }\n }\n }\n }\n }else{\n print_r(\"No order selected.\");\n }\n }\n\n if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'subscription_disable'){\n if(isset($_REQUEST['orders']) && !empty($_REQUEST['orders'])){\n $orders_data = $_REQUEST['orders'];\n if(is_array($orders_data)){\n foreach($orders_data as $data){\n \n $order_id = $data;\n \n $order = wc_get_order( $order_id );\n if($order !== false){\n $items = $order->get_items();\n \n foreach ( $items as $item ) {\n $product_id = $item->get_product_id();\n \n if(WC_Product_Factory::get_product_type($product_id) === 'subscription'){\n $wpdb->update($wpdb->prefix.'lic_activations', array(\n 'Editable' => 0\n ),array( 'Orderno' => $order_id ),array('%d'),array('%d'));\n }\n }\n }\n }\n }\n }else{\n print_r(\"No orders selected.\");\n }\n \n }\n\n if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'enable_products_'){\n if(isset($_REQUEST['orders']) && !empty($_REQUEST['orders'])){\n $orders_data = $_REQUEST['orders'];\n if(is_array($orders_data)){\n foreach($orders_data as $data){\n \n $order_id = $data;\n \n $order = wc_get_order( $order_id );\n if($order !== false){\n $items = $order->get_items();\n \n foreach ( $items as $item ) {\n $product_id = $item->get_product_id();\n \n if(WC_Product_Factory::get_product_type($product_id) !== 'subscription'){\n $wpdb->update($wpdb->prefix.'lic_activations', array(\n 'Editable' => 1\n ),array( 'Orderno' => $order_id ),array('%d'),array('%d'));\n }\n }\n }\n }\n }\n }else{\n print_r(\"No orders selected.\");\n }\n \n }\n\n if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'enable_subscription_'){\n if(isset($_REQUEST['orders']) && !empty($_REQUEST['orders'])){\n $orders_data = $_REQUEST['orders'];\n if(is_array($orders_data)){\n foreach($orders_data as $data){\n \n $order_id = $data;\n \n $order = wc_get_order( $order_id );\n if($order !== false){\n $items = $order->get_items();\n \n foreach ( $items as $item ) {\n $product_id = $item->get_product_id();\n \n if(WC_Product_Factory::get_product_type($product_id) === 'subscription'){\n $wpdb->update($wpdb->prefix.'lic_activations', array(\n 'Editable' => 1\n ),array( 'Orderno' => $order_id ),array('%d'),array('%d'));\n }\n }\n }\n }\n }\n }else{\n print_r(\"No order selected.\");\n }\n }\n }\n\n /**\n * Allows you to sort the data by the variables set in the $_GET\n *\n * @return Mixed\n */\n private function sort_data( $a, $b )\n {\n // Set defaults\n $orderby = 'ID';\n $order = 'asc';\n\n // If orderby is set, use this as the sort column\n if(!empty($_GET['orderby']))\n {\n $orderby = $_GET['orderby'];\n }\n\n // If order is set use this as the order\n if(!empty($_GET['order']))\n {\n $order = $_GET['order'];\n }\n\n\n $result = strcmp( $a[$orderby], $b[$orderby] );\n\n if($order === 'asc')\n {\n return $result;\n }\n\n return -$result;\n }\n\n} //class"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":14,"cells":{"blob_id":{"kind":"string","value":"a010d320967cb31a4cd28b20f2eb45c8b8a536e5"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"xiebruce/PicUploader"},"path":{"kind":"string","value":"/vendor/cloudinary/cloudinary_php/tests/TagTest.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":45334,"string":"45,334"},"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":" 'custom_value1', 'custom_attr2' => 'custom_value2');\n private static $common_image_options = array(\n 'effect' => 'sepia',\n 'cloud_name' => 'test123',\n 'client_hints' => false,\n );\n private static $fill_transformation;\n private static $fill_trans_str;\n private static $common_srcset;\n private static $breakpoints_arr;\n private static $sizes_attr;\n\n public static function setUpBeforeClass()\n {\n self::$breakpoints_arr = array(self::$min_width, 200, 300, self::$max_width);\n self::$max_images = count(self::$breakpoints_arr);\n self::$common_srcset = array('breakpoints' => self::$breakpoints_arr);\n\n self::$fill_transformation = ['width' => self::$max_width, 'height' => self::$max_width, 'crop' => 'fill'];\n self::$fill_trans_str = \"c_fill,h_\" . self::$max_width . \",w_\" . self::$max_width;\n\n self::$sizes_attr = implode(\n ', ',\n array_map(\n function ($w) {\n return \"(max-width: ${w}px) ${w}px\";\n },\n self::$breakpoints_arr\n )\n );\n\n Curl::$instance = new Curl();\n }\n\n protected function setUp()\n {\n Cloudinary::reset_config();\n Cloudinary::config(\n array(\n \"cloud_name\" => \"test123\",\n \"api_key\" => \"a\",\n \"api_secret\" => \"b\",\n \"secure_distribution\" => null,\n \"private_cdn\" => false,\n \"cname\" => null\n )\n );\n }\n\n public function test_cl_image_tag()\n {\n $tag = cl_image_tag(\"test\", array(\"width\" => 10, \"height\" => 10, \"crop\" => \"fill\", \"format\" => \"png\"));\n $this->assertEquals(\n \"\",\n $tag\n );\n }\n\n /**\n * Should create a meta tag with client hints\n */\n public function test_cl_client_hints_meta_tag()\n {\n $doc = new DOMDocument();\n $doc->loadHTML(cl_client_hints_meta_tag());\n $tags = $doc->getElementsByTagName('meta');\n $this->assertEquals($tags->length, 1);\n $this->assertEquals($tags->item(0)->getAttribute('content'), 'DPR, Viewport-Width, Width');\n $this->assertEquals($tags->item(0)->getAttribute('http-equiv'), 'Accept-CH');\n }\n\n /**\n * Check that cl_image_tag encodes special characters.\n */\n public function test_cl_image_tag_special_characters_encoding()\n {\n $tag = cl_image_tag(\n \"test's special < \\\"characters\\\" >\",\n array(\"width\" => 10, \"height\" => 10, \"crop\" => \"fill\", \"format\" => \"png\", \"alt\" => \"< test's > special \\\"\")\n );\n $expected = \"&lt; test&#039;s &gt; special &quot;\";\n\n $this->assertEquals($expected, $tag);\n }\n\n public function test_responsive_width()\n {\n // should add responsive width transformation\n $tag = cl_image_tag(\"hello\", array(\"responsive_width\" => true, \"format\" => \"png\"));\n $this->assertEquals(\n \"\",\n $tag\n );\n\n $options = array(\"width\" => 100, \"height\" => 100, \"crop\" => \"crop\", \"responsive_width\" => true);\n $result = Cloudinary::cloudinary_url(\"test\", $options);\n $this->assertEquals($options, array(\"responsive\" => true));\n $this->assertEquals($result, TagTest::DEFAULT_UPLOAD_PATH . \"c_crop,h_100,w_100/c_limit,w_auto/test\");\n Cloudinary::config(\n array(\n \"responsive_width_transformation\" => array(\n \"width\" => \"auto:breakpoints\",\n \"crop\" => \"pad\",\n ),\n )\n );\n $options = array(\"width\" => 100, \"height\" => 100, \"crop\" => \"crop\", \"responsive_width\" => true);\n $result = Cloudinary::cloudinary_url(\"test\", $options);\n $this->assertEquals($options, array(\"responsive\" => true));\n $this->assertEquals(\n $result,\n TagTest::DEFAULT_UPLOAD_PATH . \"c_crop,h_100,w_100/c_pad,w_auto:breakpoints/test\"\n );\n }\n\n public function test_width_auto()\n {\n // should support width=auto\n $tag = cl_image_tag(\"hello\", array(\"width\" => \"auto\", \"crop\" => \"limit\", \"format\" => \"png\"));\n $this->assertEquals(\n \"\",\n $tag\n );\n $tag = cl_image_tag(\"hello\", array(\"width\" => \"auto:breakpoints\", \"crop\" => \"limit\", \"format\" => \"png\"));\n $this->assertEquals(\n \"\",\n $tag\n );\n $this->cloudinary_url_assertion(\n \"test\",\n array(\"width\" => \"auto:20\", \"crop\" => 'fill'),\n TagTest::DEFAULT_UPLOAD_PATH . \"c_fill,w_auto:20/test\",\n array('responsive' => true)\n );\n $this->cloudinary_url_assertion(\n \"test\",\n array(\"width\" => \"auto:20:350\", \"crop\" => 'fill'),\n TagTest::DEFAULT_UPLOAD_PATH . \"c_fill,w_auto:20:350/test\",\n array('responsive' => true)\n );\n $this->cloudinary_url_assertion(\n \"test\",\n array(\"width\" => \"auto:breakpoints\", \"crop\" => 'fill'),\n TagTest::DEFAULT_UPLOAD_PATH . \"c_fill,w_auto:breakpoints/test\",\n array('responsive' => true)\n );\n $this->cloudinary_url_assertion(\n \"test\",\n array(\"width\" => \"auto:breakpoints_100_1900_20_15\", \"crop\" => 'fill'),\n TagTest::DEFAULT_UPLOAD_PATH . \"c_fill,w_auto:breakpoints_100_1900_20_15/test\",\n array('responsive' => true)\n );\n $this->cloudinary_url_assertion(\n \"test\",\n array(\"width\" => \"auto:breakpoints:json\", \"crop\" => 'fill'),\n TagTest::DEFAULT_UPLOAD_PATH . \"c_fill,w_auto:breakpoints:json/test\",\n array('responsive' => true)\n );\n }\n\n public function test_initial_width_and_height()\n {\n $options = array(\"crop\" => \"crop\", \"width\" => \"iw\", \"height\" => \"ih\");\n $this->cloudinary_url_assertion(\n \"test\",\n $options,\n TagTest::DEFAULT_UPLOAD_PATH . \"c_crop,h_ih,w_iw/test\"\n );\n }\n\n /**\n * @param $options\n * @param string $message\n */\n public function shared_client_hints($options, $message = '')\n {\n $tag = cl_image_tag('sample.jpg', $options);\n $this->assertEquals(\n \"\",\n $tag,\n $message\n );\n $tag = cl_image_tag('sample.jpg', array_merge(array(\"responsive\" => true), $options));\n $this->assertEquals(\n \"\",\n $tag,\n $message\n );\n }\n\n public function test_client_hints_as_option()\n {\n $this->shared_client_hints(\n array(\n \"dpr\" => \"auto\",\n \"cloud_name\" => \"test\",\n \"width\" => \"auto\",\n \"crop\" => \"scale\",\n \"client_hints\" => true,\n ),\n \"support client_hints as an option\"\n );\n }\n\n public function test_client_hints_as_global()\n {\n Cloudinary::config(array(\"client_hints\" => true));\n $this->shared_client_hints(\n array(\n \"dpr\" => \"auto\",\n \"cloud_name\" => \"test\",\n \"width\" => \"auto\",\n \"crop\" => \"scale\",\n ),\n \"support client hints as global configuration\"\n );\n }\n\n public function test_client_hints_false()\n {\n Cloudinary::config(array(\"responsive\" => true));\n $tag = cl_image_tag(\n 'sample.jpg',\n array(\n \"width\" => \"auto\",\n \"crop\" => \"scale\",\n \"cloud_name\" => \"test123\",\n \"client_hints\" => false,\n )\n );\n $this->assertEquals(\n \"\",\n $tag,\n \"should use normal responsive behaviour\"\n );\n }\n\n /**\n * @internal\n * Helper method for generating expected `img` and `source` tags\n *\n * @param string $tag_name Expected tag name(img or source)\n * @param string $public_id Public ID of the image\n * @param string $common_trans_str Default transformation string to be used in all resources\n * @param string $custom_trans_str Optional custom transformation string to be be used inside srcset resources\n * If not provided, $common_trans_str is used\n * @param array $srcset_breakpoints Optional list of breakpoints for srcset. If not provided srcset is omitted\n * @param array $attributes Associative array of custom attributes to be added to the tag\n *\n * @param bool $is_void Indicates whether tag is an HTML5 void tag (does not need to be self-closed)\n *\n * @return string Resulting tag\n */\n private function common_image_tag_helper(\n $tag_name,\n $public_id,\n $common_trans_str,\n $custom_trans_str = '',\n $srcset_breakpoints = array(),\n $attributes = array(),\n $is_void = false\n ) {\n if (empty($custom_trans_str)) {\n $custom_trans_str = $common_trans_str;\n }\n\n if (!empty($srcset_breakpoints)) {\n $single_srcset_image = function ($w) use ($custom_trans_str, $public_id) {\n return self::DEFAULT_UPLOAD_PATH . \"{$custom_trans_str}/c_scale,w_{$w}/{$public_id} {$w}w\";\n };\n $attributes['srcset'] = implode(', ', array_map($single_srcset_image, $srcset_breakpoints));\n }\n\n $tag = \"<$tag_name\";\n\n $attributes_str = implode(\n ' ',\n array_map(\n function ($k, $v) {\n return \"$k='$v'\";\n },\n array_keys($attributes),\n array_values($attributes)\n )\n );\n\n if (!empty($attributes_str)) {\n $tag .= \" {$attributes_str}\";\n }\n\n $tag .= $is_void ? \">\" : \"/>\"; // HTML5 void elements do not need to be self closed\n\n if (getenv('DEBUG')) {\n echo preg_replace('/([,\\']) /', \"$1\\n \", $tag) . \"\\n\\n\";\n }\n\n return $tag;\n }\n\n /**\n * @internal\n * Helper method for test_cl_image_tag_srcset for generating expected image tag\n *\n * @param string $public_id Public ID of the image\n * @param string $common_trans_str Default transformation string to be used in all resources\n * @param string $custom_trans_str Optional custom transformation string to be be used inside srcset resources\n * If not provided, $common_trans_str is used\n * @param array $srcset_breakpoints Optional list of breakpoints for srcset. If not provided srcset is omitted\n * @param array $attributes Associative array of custom attributes to be added to the tag\n *\n * @return string Resulting image tag\n */\n private function get_expected_cl_image_tag(\n $public_id,\n $common_trans_str,\n $custom_trans_str = '',\n $srcset_breakpoints = array(),\n $attributes = array()\n ) {\n\n Cloudinary::array_unshift_assoc(\n $attributes,\n 'src',\n self::DEFAULT_UPLOAD_PATH . \"{$common_trans_str}/{$public_id}\"\n );\n\n return $this->common_image_tag_helper(\n \"img\",\n $public_id,\n $common_trans_str,\n $custom_trans_str,\n $srcset_breakpoints,\n $attributes\n );\n }\n\n /**\n * @internal\n * Helper method for for generating expected `source` tag\n *\n * @param string $public_id Public ID of the image\n * @param string $common_trans_str Default transformation string to be used in all resources\n * @param string $custom_trans_str Optional custom transformation string to be be used inside srcset resources\n * If not provided, $common_trans_str is used\n * @param array $srcset_breakpoints Optional list of breakpoints for srcset. If not provided srcset is omitted\n * @param array $attributes Associative array of custom attributes to be added to the tag\n *\n * @return string Resulting `source` tag\n */\n private function get_expected_cl_source_tag(\n $public_id,\n $common_trans_str,\n $custom_trans_str = '',\n $srcset_breakpoints = array(),\n $attributes = array()\n ) {\n\n $attributes['srcset'] = self::DEFAULT_UPLOAD_PATH . \"{$common_trans_str}/{$public_id }\";\n\n ksort($attributes); // Used here to produce output similar to Cloudinary::html_attrs\n\n return $this->common_image_tag_helper(\n \"source\",\n $public_id,\n $common_trans_str,\n $custom_trans_str,\n $srcset_breakpoints,\n $attributes,\n true\n );\n }\n\n /**\n * Should create srcset attribute with provided breakpoints\n */\n public function test_cl_image_tag_srcset()\n {\n $expected_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n self::$breakpoints_arr\n );\n\n $tag_with_breakpoints = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array('srcset' => self::$common_srcset)\n )\n );\n\n $this->assertEquals(\n $expected_tag,\n $tag_with_breakpoints,\n 'Should create img srcset attribute with provided breakpoints'\n );\n }\n\n public function test_support_srcset_attribute_defined_by_min_width_max_width_and_max_images()\n {\n $tag_min_max_count = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array(\n 'srcset' => array(\n 'min_width' => self::$min_width,\n 'max_width' => $x = self::$max_width,\n 'max_images' => count(self::$breakpoints_arr)\n )\n )\n )\n );\n\n $expected_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n self::$breakpoints_arr\n );\n\n $this->assertEquals(\n $expected_tag,\n $tag_min_max_count,\n 'Should support srcset attribute defined by min_width, max_width, and max_images'\n );\n\n // Should support 1 image in srcset\n $tag_one_image_by_params = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array(\n 'srcset' => array(\n 'min_width' => self::$breakpoints_arr[0],\n 'max_width' => self::$max_width,\n 'max_images' => 1\n )\n )\n )\n );\n\n $expected_1_image_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n array(self::$max_width)\n );\n\n $this->assertEquals($expected_1_image_tag, $tag_one_image_by_params);\n\n $tag_one_image_by_breakpoints = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array('srcset' => array('breakpoints' => array(self::$max_width)))\n )\n );\n $this->assertEquals($expected_1_image_tag, $tag_one_image_by_breakpoints);\n\n // Should support custom transformation for srcset items\n $custom_transformation = array(\"transformation\" => array(\"crop\" => \"crop\", \"width\" => 10, \"height\" => 20));\n\n $tag_custom_transformation = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array(\n 'srcset' => array_merge(\n self::$common_srcset,\n $custom_transformation\n )\n )\n )\n );\n\n $custom_transformation_str = 'c_crop,h_20,w_10';\n $custom_expected_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n $custom_transformation_str,\n self::$breakpoints_arr\n );\n\n $this->assertEquals($custom_expected_tag, $tag_custom_transformation);\n\n // Should populate sizes attribute\n $tag_with_sizes = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array(\n 'srcset' => array_merge(\n self::$common_srcset,\n array('sizes' => true)\n )\n )\n )\n );\n\n $expected_tag_with_sizes = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n self::$breakpoints_arr,\n array('sizes' => self::$sizes_attr)\n );\n $this->assertEquals($expected_tag_with_sizes, $tag_with_sizes);\n\n // Should support srcset string value\n $raw_srcset_value = \"some srcset data as is\";\n $tag_with_raw_srcset = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array('attributes' => array('srcset' => $raw_srcset_value))\n )\n );\n\n $expected_raw_srcset = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n array(),\n array('srcset' => $raw_srcset_value)\n );\n\n $this->assertEquals($expected_raw_srcset, $tag_with_raw_srcset);\n\n // Should remove width and height attributes in case srcset is specified, but passed to transformation\n $tag_with_sizes = cl_image_tag(\n self::$public_id,\n array_merge(\n array_merge(\n self::$common_image_options,\n array('width' => 500, 'height' => 500)\n ),\n array('srcset' => self::$common_srcset)\n )\n );\n\n $expected_tag_without_width_and_height = self::get_expected_cl_image_tag(\n self::$public_id,\n 'e_sepia,h_500,w_500',\n '',\n self::$breakpoints_arr\n );\n $this->assertEquals($expected_tag_without_width_and_height, $tag_with_sizes);\n }\n\n /**\n * Should omit srcset attribute on invalid values\n *\n * @throws \\Exception\n */\n public function test_srcset_invalid_values()\n {\n $invalid_breakpoints = array(\n array('sizes' => true), // srcset data not provided\n array('max_width' => 300, 'max_images' => 3), // no min_width\n array('min_width' => '1', 'max_width' => 300, 'max_images' => 3), // invalid min_width\n array('min_width' => 100, 'max_images' => 3), // no max_width\n array('min_width' => '1', 'max_width' => '3', 'max_images' => 3), // invalid max_width\n array('min_width' => 200, 'max_width' => 100, 'max_images' => 3), // min_width > max_width\n array('min_width' => 100, 'max_width' => 300), // no max_images\n array('min_width' => 100, 'max_width' => 300, 'max_images' => 0), // invalid max_images\n array('min_width' => 100, 'max_width' => 300, 'max_images' => -17), // invalid max_images\n array('min_width' => 100, 'max_width' => 300, 'max_images' => '3'), // invalid max_images\n array('min_width' => 100, 'max_width' => 300, 'max_images' => null), // invalid max_images\n );\n\n\n $err_log_original_destination = ini_get('error_log');\n // Suppress error messages in error log\n ini_set('error_log', '/dev/null');\n\n try {\n foreach ($invalid_breakpoints as $value) {\n $tag = cl_image_tag(\n self::$public_id,\n array_merge(self::$common_image_options, array('srcset' => $value))\n );\n\n self::assertNotContains(\"srcset\", $tag);\n }\n } catch (\\Exception $e) {\n ini_set('error_log', $err_log_original_destination);\n throw $e;\n }\n\n ini_set('error_log', $err_log_original_destination);\n }\n\n public function test_cl_image_tag_responsive_breakpoints_cache()\n {\n $cache = ResponsiveBreakpointsCache::instance();\n $cache->setCacheAdapter(new KeyValueCacheAdapter(new DummyCacheStorage()));\n\n $cache->set(self::$public_id, self::$common_image_options, self::$breakpoints_arr);\n\n $expected_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n self::$breakpoints_arr\n );\n\n $image_tag = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n [\"srcset\"=> [\"use_cache\" => true]]\n )\n );\n\n $this->assertEquals($expected_tag, $image_tag);\n }\n\n public function test_create_a_tag_with_custom_attributes_legacy_approach()\n {\n $tag_with_custom_legacy_attribute = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n self::$custom_attributes\n )\n );\n\n $expected_custom_attributes_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n array(),\n self::$custom_attributes\n );\n\n $this->assertEquals($expected_custom_attributes_tag, $tag_with_custom_legacy_attribute);\n }\n\n public function test_create_a_tag_with_legacy_srcset_attribute()\n {\n $srcset_attribute = ['srcset' =>'http://custom.srcset.attr/sample.jpg 100w'];\n $tag_with_custom_srcset_attribute = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n $srcset_attribute\n )\n );\n\n $expected_custom_attributes_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n array(),\n $srcset_attribute\n );\n\n $this->assertEquals($expected_custom_attributes_tag, $tag_with_custom_srcset_attribute);\n }\n\n\n public function test_consume_custom_attributes_from_attributes_key()\n {\n $tag_with_custom_attribute = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array('attributes' => self::$custom_attributes)\n )\n );\n $expected_custom_attributes_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n array(),\n self::$custom_attributes\n );\n $this->assertEquals($expected_custom_attributes_tag, $tag_with_custom_attribute);\n }\n\n public function test_override_existing_attributes_with_specified_by_custom_ones()\n {\n $updated_attributes = array('alt' => 'updated alt');\n $tag_with_custom_overriden_attribute = cl_image_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array('alt' => 'original alt', 'attributes' => $updated_attributes)\n )\n );\n\n $expected_overriden_attributes_tag = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n array(),\n $updated_attributes\n );\n $this->assertEquals($expected_overriden_attributes_tag, $tag_with_custom_overriden_attribute);\n }\n\n public function test_dpr_auto()\n {\n // should support width=auto\n $tag = cl_image_tag(\"hello\", array(\"dpr\" => \"auto\", \"format\" => \"png\"));\n $this->assertEquals(\n \"\",\n $tag\n );\n }\n\n public function test_cl_sprite_tag()\n {\n $url = cl_sprite_tag(\"mytag\", array(\"crop\" => \"fill\", \"width\" => 10, \"height\" => 10));\n $this->assertEquals(\n \"\",\n $url\n );\n }\n\n public function test_cl_video_thumbnail_path()\n {\n $this->assertEquals(cl_video_thumbnail_path('movie_id'), TagTest::VIDEO_UPLOAD_PATH . \"movie_id.jpg\");\n $this->assertEquals(\n cl_video_thumbnail_path('movie_id', array('width' => 100)),\n TagTest::VIDEO_UPLOAD_PATH . \"w_100/movie_id.jpg\"\n );\n }\n\n public function test_cl_video_thumbnail_tag()\n {\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"movie_id.jpg\";\n $this->assertEquals(\n cl_video_thumbnail_tag('movie_id'),\n \"\"\n );\n\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"w_100/movie_id.jpg\";\n $this->assertEquals(\n cl_video_thumbnail_tag('movie_id', array('width' => 100)),\n \"\"\n );\n }\n\n public function test_cl_video_tag()\n {\n //default\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"movie\";\n $this->assertEquals(\n cl_video_tag('movie'),\n \"\"\n );\n }\n\n public function test_cl_video_tag_with_attributes()\n {\n //test video attributes\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"movie\";\n $this->assertEquals(\n cl_video_tag(\n 'movie',\n array('autoplay' => true, 'controls', 'loop', 'muted' => \"true\", 'preload', 'style' => 'border: 1px')\n ),\n \"\"\n );\n }\n\n public function test_cl_video_tag_with_transformation()\n {\n //test video attributes\n $options = array(\n 'source_types' => \"mp4\",\n 'html_height' => \"100\",\n 'html_width' => \"200\",\n 'video_codec' => array('codec' => 'h264'),\n 'audio_codec' => 'acc',\n 'start_offset' => 3,\n );\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"ac_acc,so_3,vc_h264/movie\";\n $this->assertEquals(\n cl_video_tag('movie', $options),\n \"\"\n );\n\n unset($options['source_types']);\n $this->assertEquals(\n cl_video_tag('movie', $options),\n \"\"\n );\n\n unset($options['html_height']);\n unset($options['html_width']);\n $options['width'] = 250;\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"ac_acc,so_3,vc_h264,w_250/movie\";\n $this->assertEquals(\n cl_video_tag('movie', $options),\n \"\"\n );\n\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"ac_acc,c_fit,so_3,vc_h264,w_250/movie\";\n $options['crop'] = 'fit';\n $this->assertEquals(\n cl_video_tag('movie', $options),\n \"\"\n );\n }\n\n public function test_cl_video_tag_with_fallback()\n {\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"movie\";\n $fallback = \"Cannot display video\";\n $this->assertEquals(\n cl_video_tag('movie', array('fallback_content' => $fallback)),\n \"\"\n );\n $this->assertEquals(\n cl_video_tag('movie', array('fallback_content' => $fallback, 'source_types' => \"mp4\")),\n \"\"\n );\n }\n\n public function test_cl_video_tag_with_source_types()\n {\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"movie\";\n $this->assertEquals(\n cl_video_tag('movie', array('source_types' => array('ogv', 'mp4'))),\n \"\"\n );\n }\n\n public function test_cl_video_tag_with_source_transformation()\n {\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"q_50/w_100/movie\";\n $expected_ogv_url = TagTest::VIDEO_UPLOAD_PATH . \"q_50/q_70,w_100/movie\";\n $expected_mp4_url = TagTest::VIDEO_UPLOAD_PATH . \"q_50/q_30,w_100/movie\";\n $this->assertEquals(\n cl_video_tag(\n 'movie',\n array(\n 'width' => 100,\n 'transformation' => array(array('quality' => 50)),\n 'source_transformation' => array(\n 'ogv' => array('quality' => 70),\n 'mp4' => array('quality' => 30),\n ),\n )\n ),\n \"\"\n );\n\n $this->assertEquals(\n cl_video_tag(\n 'movie',\n array(\n 'width' => 100,\n 'transformation' => array(array('quality' => 50)),\n 'source_transformation' => array(\n 'ogv' => array('quality' => 70),\n 'mp4' => array('quality' => 30),\n ),\n 'source_types' => array('webm', 'mp4'),\n )\n ),\n \"\"\n );\n }\n\n public function test_cl_video_tag_with_poster()\n {\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"movie\";\n\n $expected_poster_url = 'http://image/somewhere.jpg';\n $this->assertEquals(\n cl_video_tag('movie', array('poster' => $expected_poster_url, 'source_types' => \"mp4\")),\n \"\"\n );\n\n $expected_poster_url = TagTest::VIDEO_UPLOAD_PATH . \"g_north/movie.jpg\";\n $this->assertEquals(\n cl_video_tag(\n 'movie',\n array('poster' => array('gravity' => 'north'), 'source_types' => \"mp4\")\n ),\n \"\"\n );\n\n $expected_poster_url = TagTest::DEFAULT_UPLOAD_PATH . \"g_north/my_poster.jpg\";\n $this->assertEquals(\n cl_video_tag(\n 'movie',\n array(\n 'poster' => array('gravity' => 'north', 'public_id' => 'my_poster', 'format' => 'jpg'),\n 'source_types' => \"mp4\",\n )\n ),\n \"\"\n );\n\n $this->assertEquals(\n cl_video_tag('movie', array('poster' => null, 'source_types' => \"mp4\")),\n \"\"\n );\n\n $this->assertEquals(\n cl_video_tag('movie', array('poster' => false, 'source_types' => \"mp4\")),\n \"\"\n );\n }\n\n /**\n * Check that cl_video_tag encodes special characters.\n */\n public function test_cl_video_tag_special_characters_encoding()\n {\n $expected_url = TagTest::VIDEO_UPLOAD_PATH . \"movie%27s%20id%21%40%23%24%25%5E%26%2A%28\";\n\n $this->assertEquals(\n \"\",\n cl_video_tag(\"movie's id!@#$%^&*(\", array('source_types' => \"mp4\"))\n );\n }\n\n public function test_cl_video_tag_default_sources()\n {\n $expected_url = self::VIDEO_UPLOAD_PATH . \"%smovie.%s\";\n\n $this->assertEquals(\n \"\",\n cl_video_tag('movie', array('sources' => default_video_sources()))\n );\n }\n\n public function test_cl_video_tag_custom_sources()\n {\n $custom_sources = [\n [\n \"type\" => \"mp4\",\n \"codecs\" => \"vp8, vorbis\",\n \"transformations\" => [\"video_codec\" => \"auto\"]\n ],\n [\n \"type\" => \"webm\",\n \"codecs\" => \"avc1.4D401E, mp4a.40.2\",\n \"transformations\" => [\"video_codec\" => \"auto\"]\n ]\n ];\n $expected_url = self::VIDEO_UPLOAD_PATH . \"%smovie.%s\";\n\n $this->assertEquals(\n \"\",\n cl_video_tag('movie', array('sources' => $custom_sources))\n );\n }\n\n public function test_cl_video_tag_sources_codecs_array()\n {\n $custom_sources = [\n [\n \"type\" => \"mp4\",\n \"codecs\" => [\"vp8\", \"vorbis\"],\n \"transformations\" => [\"video_codec\" => \"auto\"]\n ],\n [\n \"type\" => \"webm\",\n \"codecs\" => [\"avc1.4D401E\", \"mp4a.40.2\"],\n \"transformations\" => [\"video_codec\" => \"auto\"]\n ]\n ];\n $expected_url = self::VIDEO_UPLOAD_PATH . \"%smovie.%s\";\n\n $this->assertEquals(\n \"\",\n cl_video_tag('movie', array('sources' => $custom_sources))\n );\n }\n\n public function test_cl_video_tag_sources_with_transformation()\n {\n $options = array(\n 'source_types' => \"mp4\",\n 'html_height' => \"100\",\n 'html_width' => \"200\",\n 'video_codec' => array('codec' => 'h264'),\n 'audio_codec' => 'acc',\n 'start_offset' => 3,\n 'sources' => default_video_sources()\n );\n $expected_url = self::VIDEO_UPLOAD_PATH . \"ac_acc,so_3,%smovie.%s\";\n\n $this->assertEquals(\n \"\",\n cl_video_tag('movie', $options)\n );\n }\n\n public function test_upload_tag()\n {\n $pattern = \"//\";\n $this->assertRegExp($pattern, cl_upload_tag('image'));\n $this->assertRegExp($pattern, cl_image_upload_tag('image'));\n\n $pattern = \"//\";\n $this->assertRegExp(\n $pattern,\n cl_upload_tag('image', array('chunk_size' => 5000000))\n );\n\n $pattern = \"//\";\n $this->assertRegExp(\n $pattern,\n cl_upload_tag('image', array(\"html\" => array('class' => 'classy')))\n );\n }\n\n public function test_cl_source_tag()\n {\n $expected_tag = self::get_expected_cl_source_tag(\n self::$public_id,\n self::$common_transformation_str,\n '',\n self::$breakpoints_arr,\n array('sizes' => self::$sizes_attr, \"media\" => generate_media_attr([\"max_width\" =>self::$max_width]))\n );\n\n $source_tag_with_srcset = cl_source_tag(\n self::$public_id,\n array_merge(\n self::$common_image_options,\n array(\n 'srcset' => array_merge(\n self::$common_srcset,\n array('sizes' => true)\n )\n ),\n array(\n 'media' => array(\"max_width\" =>self::$max_width)\n )\n )\n );\n\n $this->assertEquals(\n $expected_tag,\n $source_tag_with_srcset,\n 'Should create source tag with srcset and sizes attributes with provided breakpoints'\n );\n }\n\n public function test_cl_picture_tag()\n {\n $tag = cl_picture_tag(\n self::$public_id,\n self::$fill_transformation,\n [\n [\n \"max_width\" =>self::$min_width,\n \"transformation\" => [\"effect\" => \"sepia\", \"angle\" => 17, \"width\" => self::$min_width]\n ],\n [\n \"min_width\" => self::$min_width,\n \"max_width\" => self::$max_width,\n \"transformation\" => [\"effect\" => \"colorize\", \"angle\" => 18, \"width\" => self::$max_width]\n\n ],\n [\n \"min_width\" => self::$max_width,\n \"transformation\" => [\"effect\" => \"blur\", \"angle\" => 19, \"width\" => self::$max_width]\n ]\n ]\n );\n\n\n $expected_source1 = self::get_expected_cl_source_tag(\n self::$public_id,\n self::$fill_trans_str . \"/\" . \"a_17,e_sepia,w_\" . self::$min_width,\n '',\n [],\n [\"media\" => generate_media_attr([\"max_width\" =>self::$min_width])]\n );\n\n $expected_source2 = self::get_expected_cl_source_tag(\n self::$public_id,\n self::$fill_trans_str . \"/\" . \"a_18,e_colorize,w_\" . self::$max_width,\n '',\n [],\n [\"media\" => generate_media_attr([\"min_width\" => self::$min_width, \"max_width\" =>self::$max_width])]\n\n );\n\n $expected_source3 = self::get_expected_cl_source_tag(\n self::$public_id,\n self::$fill_trans_str . \"/\" . \"a_19,e_blur,w_\" . self::$max_width,\n '',\n [],\n [\"media\" => generate_media_attr([\"min_width\" => self::$max_width])]\n );\n\n $expected_img = self::get_expected_cl_image_tag(\n self::$public_id,\n self::$fill_trans_str,\n '',\n [],\n ['height' => self::$max_width, 'width' => self::$max_width]\n );\n\n $exp = \"\" . $expected_source1 . $expected_source2 . $expected_source3 . $expected_img . \"\";\n\n $this->assertEquals($exp, $tag);\n }\n\n private function cloudinary_url_assertion($source, $options, $expected, $expected_options = array())\n {\n $url = Cloudinary::cloudinary_url($source, $options);\n $this->assertEquals($expected_options, $options);\n $this->assertEquals($expected, $url);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":15,"cells":{"blob_id":{"kind":"string","value":"98b05ed17c6b2767ad5c61a6fa19ce374ab51cf7"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"geertvangent/ects"},"path":{"kind":"string","value":"/Application/Discovery/Module/TrainingInfo/Implementation/Bamaflex/SubTrajectory.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2032,"string":"2,032"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"get_default_property(self::PROPERTY_SOURCE);\n }\n\n /**\n *\n * @param int $source\n */\n public function set_source($source)\n {\n $this->set_default_property(self::PROPERTY_SOURCE, $source);\n }\n\n public function get_trajectory_id()\n {\n return $this->get_default_property(self::PROPERTY_TRAJECTORY_ID);\n }\n\n public function set_trajectory_id($trajectory_id)\n {\n $this->set_default_property(self::PROPERTY_TRAJECTORY_ID, $trajectory_id);\n }\n\n public function get_name()\n {\n return $this->get_default_property(self::PROPERTY_NAME);\n }\n\n public function set_name($name)\n {\n $this->set_default_property(self::PROPERTY_NAME, $name);\n }\n\n public static function get_default_property_names($extended_property_names = array())\n {\n $extended_property_names[] = self::PROPERTY_SOURCE;\n $extended_property_names[] = self::PROPERTY_TRAJECTORY_ID;\n $extended_property_names[] = self::PROPERTY_NAME;\n \n return parent::get_default_property_names($extended_property_names);\n }\n\n /**\n *\n * @return DataManagerInterface\n */\n public function get_data_manager()\n {\n // return DataManager :: getInstance();\n }\n\n public function get_courses()\n {\n return $this->courses;\n }\n\n public function set_courses($courses)\n {\n $this->courses = $courses;\n }\n\n public function has_courses()\n {\n return count($this->courses) > 0;\n }\n\n public function add_course($course)\n {\n $this->courses[] = $course;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":16,"cells":{"blob_id":{"kind":"string","value":"dca0c6f61110f1915cc1f6da78b2e7d755eb7eed"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"codingmetta/webshop-plenty-planty.github.io"},"path":{"kind":"string","value":"/scripts/registration-submit.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1466,"string":"1,466"},"score":{"kind":"number","value":3.203125,"string":"3.203125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"click here to log in. ';\n} else {\n echo 'Repeated Password is incorrect. Please try again.';\n}\n\n/** @fn 'Double Check Password' \n * @brief Checks if both entered passwords are the same\n */\nfunction check_password($pw, $rpw){\n if($pw == $rpw){\n return true;\n } else {\n return false;\n }\n}\n\n/** @fn 'Add User' \n * @brief Adds user with given credentials to table 'Users'\n */\nfunction add_user($conn, $rl, $fn, $sn, $em, $un, $pw)\n{\n$sql = \"INSERT INTO Users (role, forename, surname, email, username, password) VALUES ('$rl','$fn','$sn','$em', '$un', '$pw')\";\nif ($conn->query($sql) === TRUE) {\n} else {\n echo \"Error: \" . $sql . \"
\" . $conn->error;\n}\n}\n\n ?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":17,"cells":{"blob_id":{"kind":"string","value":"2551d4cd6a250f478909d7a972051a86d892c64f"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"bZez/SF5-GRC"},"path":{"kind":"string","value":"/src/Entity/Partner.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1907,"string":"1,907"},"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":"users = new ArrayCollection();\n }\n\n public function getId(): ?int\n {\n return $this->id;\n }\n\n public function getNom(): ?string\n {\n return $this->nom;\n }\n\n public function setNom(string $nom): self\n {\n $this->nom = $nom;\n\n return $this;\n }\n\n public function getProduits(): ?array\n {\n return $this->produits;\n }\n\n public function setProduits(array $produits): self\n {\n $this->produits = $produits;\n\n return $this;\n }\n\n /**\n * @return Collection|User[]\n */\n public function getUsers(): Collection\n {\n return $this->users;\n }\n\n public function addUser(User $user): self\n {\n if (!$this->users->contains($user)) {\n $this->users[] = $user;\n $user->setPartner($this);\n }\n\n return $this;\n }\n\n public function removeUser(User $user): self\n {\n if ($this->users->contains($user)) {\n $this->users->removeElement($user);\n // set the owning side to null (unless already changed)\n if ($user->getPartner() === $this) {\n $user->setPartner(null);\n }\n }\n\n return $this;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":18,"cells":{"blob_id":{"kind":"string","value":"0bfe953c03db6e83aa9c8b79ff1b592349296d95"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"mildphp/framework"},"path":{"kind":"string","value":"/src/Mild/Support/Events/LocaleUpdated.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":320,"string":"320"},"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":"locale = $locale;\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":19,"cells":{"blob_id":{"kind":"string","value":"60cff38b1dc0ce25f5af042eab05ce7e87843af1"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"impact-pt/impact-ios"},"path":{"kind":"string","value":"/PhP/createApmt.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":882,"string":"882"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":20,"cells":{"blob_id":{"kind":"string","value":"c4994521d8f9788f619f7a2e43097b1d4e9ef1e4"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"kolholga/oop"},"path":{"kind":"string","value":"/app/lib/User.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2109,"string":"2,109"},"score":{"kind":"number","value":3.671875,"string":"3.671875"},"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":"age = $a;\n $this->name = $n;\n }\n*/\n\n public function __construct()\n {\n echo 'Я нахожусь в пространстве имен \\Ddd\\fff';\n }\n\n\n public function getAge() // ГЕТТЕР - метод для возвращения значения свойства age\n {\n //self::LOGIN; - обращаемся к константе\n return $this->age;\n }\n\n public function getName() // ГЕТТЕР - метод для возвращения значения свойства name\n {\n return $this->name;\n }\n\n public function setAge($age) // СЕТТЕР - метод / устанавливает возраст\n {\n if ($age > 18 && $age < 60) {\n $this->age = $age;\n }\n }\n\n public function setName($name) // СЕТТЕР - метод / устанавливает имя\n {\n $this->name = $name;\n }\n}\n\n//$man = new User('Vasya', '18'); // в $man присваиваем объект класса User\n\n//$man->name = 'Вася';\n//$man->age = '18';\n\n/*\n$man = new User; // сoздали объект User // если нет конструкторa, скобки можно не ставить\n$man->setAge(' 25');\n$man->setName(' Petya ');\necho 'My name is ' . $man->getName() . \"age\" . $man->getAge() . ' years old
';\n*/\n//echo 'My login is ' . User::LOGIN;\n\n\n/*\nvar_dump($man);\necho '
';\n\n$man2 = new User('Gena', '21');\n//$man2->name = 'Петя';\n//$man2->age = '30';\n\nvar_dump($man2);\necho '
';\n\nvar_dump($man);\n*/\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":21,"cells":{"blob_id":{"kind":"string","value":"ed7403019c0b50ada63c9d649535c3fd06ce9a74"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"pimpmypixel/confirmit-authoring"},"path":{"kind":"string","value":"/src/StructType/QuestionFormBase.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9704,"string":"9,704"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"setStartPosition($startPosition)\n ->setNotPerformDataCleaningOnMasking($notPerformDataCleaningOnMasking)\n ->setLevel($level)\n ->setJscriptExpression($jscriptExpression)\n ->setBenchmarkType($benchmarkType)\n ->setSeed($seed)\n ->setValidationCode($validationCode)\n ->setParentGrid3DFormName($parentGrid3DFormName);\n }\n /**\n * Get StartPosition value\n * @return int\n */\n public function getStartPosition()\n {\n return $this->StartPosition;\n }\n /**\n * Set StartPosition value\n * @param int $startPosition\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public function setStartPosition($startPosition = null)\n {\n // validation for constraint: int\n if (!is_null($startPosition) && !is_numeric($startPosition)) {\n throw new \\InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, \"%s\" given', gettype($startPosition)), __LINE__);\n }\n $this->StartPosition = $startPosition;\n return $this;\n }\n /**\n * Get NotPerformDataCleaningOnMasking value\n * @return bool\n */\n public function getNotPerformDataCleaningOnMasking()\n {\n return $this->NotPerformDataCleaningOnMasking;\n }\n /**\n * Set NotPerformDataCleaningOnMasking value\n * @param bool $notPerformDataCleaningOnMasking\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public function setNotPerformDataCleaningOnMasking($notPerformDataCleaningOnMasking = null)\n {\n // validation for constraint: boolean\n if (!is_null($notPerformDataCleaningOnMasking) && !is_bool($notPerformDataCleaningOnMasking)) {\n throw new \\InvalidArgumentException(sprintf('Invalid value, please provide a bool, \"%s\" given', gettype($notPerformDataCleaningOnMasking)), __LINE__);\n }\n $this->NotPerformDataCleaningOnMasking = $notPerformDataCleaningOnMasking;\n return $this;\n }\n /**\n * Get Level value\n * @return int\n */\n public function getLevel()\n {\n return $this->Level;\n }\n /**\n * Set Level value\n * @param int $level\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public function setLevel($level = null)\n {\n // validation for constraint: int\n if (!is_null($level) && !is_numeric($level)) {\n throw new \\InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, \"%s\" given', gettype($level)), __LINE__);\n }\n $this->Level = $level;\n return $this;\n }\n /**\n * Get JscriptExpression value\n * @return bool\n */\n public function getJscriptExpression()\n {\n return $this->JscriptExpression;\n }\n /**\n * Set JscriptExpression value\n * @param bool $jscriptExpression\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public function setJscriptExpression($jscriptExpression = null)\n {\n // validation for constraint: boolean\n if (!is_null($jscriptExpression) && !is_bool($jscriptExpression)) {\n throw new \\InvalidArgumentException(sprintf('Invalid value, please provide a bool, \"%s\" given', gettype($jscriptExpression)), __LINE__);\n }\n $this->JscriptExpression = $jscriptExpression;\n return $this;\n }\n /**\n * Get BenchmarkType value\n * @return string\n */\n public function getBenchmarkType()\n {\n return $this->BenchmarkType;\n }\n /**\n * Set BenchmarkType value\n * @uses \\Confirmit\\Authoring\\EnumType\\BenchmarkFormType::valueIsValid()\n * @uses \\Confirmit\\Authoring\\EnumType\\BenchmarkFormType::getValidValues()\n * @throws \\InvalidArgumentException\n * @param string $benchmarkType\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public function setBenchmarkType($benchmarkType = null)\n {\n // validation for constraint: enumeration\n if (!\\Confirmit\\Authoring\\EnumType\\BenchmarkFormType::valueIsValid($benchmarkType)) {\n throw new \\InvalidArgumentException(sprintf('Value \"%s\" is invalid, please use one of: %s', $benchmarkType, implode(', ', \\Confirmit\\Authoring\\EnumType\\BenchmarkFormType::getValidValues())), __LINE__);\n }\n $this->BenchmarkType = $benchmarkType;\n return $this;\n }\n /**\n * Get Seed value\n * @return int\n */\n public function getSeed()\n {\n return $this->Seed;\n }\n /**\n * Set Seed value\n * @param int $seed\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public function setSeed($seed = null)\n {\n // validation for constraint: int\n if (!is_null($seed) && !is_numeric($seed)) {\n throw new \\InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, \"%s\" given', gettype($seed)), __LINE__);\n }\n $this->Seed = $seed;\n return $this;\n }\n /**\n * Get ValidationCode value\n * @return string|null\n */\n public function getValidationCode()\n {\n return $this->ValidationCode;\n }\n /**\n * Set ValidationCode value\n * @param string $validationCode\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public function setValidationCode($validationCode = null)\n {\n // validation for constraint: string\n if (!is_null($validationCode) && !is_string($validationCode)) {\n throw new \\InvalidArgumentException(sprintf('Invalid value, please provide a string, \"%s\" given', gettype($validationCode)), __LINE__);\n }\n $this->ValidationCode = $validationCode;\n return $this;\n }\n /**\n * Get ParentGrid3DFormName value\n * @return string|null\n */\n public function getParentGrid3DFormName()\n {\n return $this->ParentGrid3DFormName;\n }\n /**\n * Set ParentGrid3DFormName value\n * @param string $parentGrid3DFormName\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public function setParentGrid3DFormName($parentGrid3DFormName = null)\n {\n // validation for constraint: string\n if (!is_null($parentGrid3DFormName) && !is_string($parentGrid3DFormName)) {\n throw new \\InvalidArgumentException(sprintf('Invalid value, please provide a string, \"%s\" given', gettype($parentGrid3DFormName)), __LINE__);\n }\n $this->ParentGrid3DFormName = $parentGrid3DFormName;\n return $this;\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 AbstractStructBase::__set_state()\n * @uses AbstractStructBase::__set_state()\n * @param array $array the exported values\n * @return \\Confirmit\\Authoring\\StructType\\QuestionFormBase\n */\n public static function __set_state(array $array)\n {\n return parent::__set_state($array);\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":22,"cells":{"blob_id":{"kind":"string","value":"a8c1eecbc7f0ebc4290620f66ae3b1e7e88ecff3"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"MorisPae/PHPTraining"},"path":{"kind":"string","value":"/20170508/test1.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":139,"string":"139"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\" . $var_int .\"
\". $var_float;\n?>\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":23,"cells":{"blob_id":{"kind":"string","value":"b0b69ee2b1dcb7587636235c70dd5abfa6536d29"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"orangeShadow/pastebin-api"},"path":{"kind":"string","value":"/src/Repositories/PastebinRepository.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2570,"string":"2,570"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"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":"api_dev_key = $api_dev_key;\n $this->client = new Client();\n }\n\n /**\n * Create Paste\n *\n * @param $attributes\n * @return string\n *\n */\n public function createPaste(array $attributes):string\n {\n $attributes['api_option'] = 'paste';\n\n return $this->sendRequest('POST', 'api/api_post.php', $attributes);\n }\n\n\n /**\n * Get paste list\n *\n * @param $attributes\n * @return string\n */\n public function getPasteList(array $attributes):string\n {\n $attributes['api_option'] = 'list';\n\n return $this->sendRequest('POST', 'api/api_post.php', $attributes);\n }\n\n /**\n * Get paste list\n *\n * @param $attributes\n * @return string\n */\n public function deletePaste(array $attributes):string\n {\n $attributes['api_option'] = 'delete';\n\n return $this->sendRequest('POST', 'api/api_post.php', $attributes);\n }\n\n /**\n * Get paste list\n *\n * @param $attributes\n * @return string\n */\n public function getPasteRaw(array $attributes):string\n {\n $attributes['api_option'] = 'show_paste';\n\n return $this->sendRequest('POST', 'api/api_raw.php', $attributes);\n }\n\n /**\n * Send request to the server through Guzzle Client\n *\n * @param $method\n * @param $path\n * @param $attributes\n * @return string\n *\n * @throws Exceptions\\InvalidResponseException\n */\n private function sendRequest(string $method, string $path, array $attributes): string\n {\n\n $attributes['api_dev_key'] = $this->api_dev_key;\n\n $request = new Request($method, $this->pastebin_host . $path, ['Content-Type' => 'application/x-www-form-urlencoded'], http_build_query($attributes, '', '&'));\n\n try {\n $response = $this->client->send($request);\n } catch (ClientException $e) {\n throw new Exceptions\\InvalidResponseException($e->getMessage(), $e->getCode(), $e);\n }\n\n return $response->getBody()->getContents();\n }\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":24,"cells":{"blob_id":{"kind":"string","value":"9fc9c4355f07c88fe5e04a7839b35a84a69bfdf9"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"HaruItari/target_21"},"path":{"kind":"string","value":"/common/components/WebUser.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4234,"string":"4,234"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"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":"getModel()) {\r\n return Yii::app()->db->createCommand(\"\r\n SELECT\r\n t.role\r\n FROM\r\n user_group AS t,\r\n user\r\n WHERE\r\n t.id = user.group\r\n AND user.id = {$this->id}\r\n \")->queryScalar();\r\n }\r\n }\r\n\r\n /**\r\n * Получение flash-сообщения и обрамление его в тематические блоки.\r\n * Перегрузка стандартного метода {@link parent::getFlash}.\r\n * @param string $key Ключ сообщения\r\n * @param string $type Тип возвращаемого значения\r\n * @param mixed $defaultValue Возвращаемое значение в случае отсутствия сообщения\r\n * @param boolean $delete Удалить сообщение после вывода\r\n * @return mixed or bool\r\n */\r\n public function getFlash($key, $type = null, $defaultValue = null, $delete = true)\r\n {\r\n $return = parent::getFlash($key, $defaultValue, $delete);\r\n\r\n if (isset($return)) {\r\n switch ($type) {\r\n case 'info' :\r\n return '
' . $return . '
';\r\n break;\r\n\r\n case 'note' :\r\n return '
' . $return . '
';\r\n break;\r\n\r\n case 'error' :\r\n return '
' . $return . '
';\r\n break;\r\n\r\n default :\r\n return $return;\r\n break;\r\n }\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /**\r\n * Проверка наличия flash-сообщения.\r\n * Перегрузка стандартного метода {@link parent::hasFlash}.\r\n * @param string $key Ключ сообщения\r\n * @return boolean Существование сообщения\r\n */\r\n public function hasFlash($key)\r\n {\r\n return $this->getFlash($key, null, null, false) !== null;\r\n }\r\n\r\n /**\r\n * Установка якорной страницы, на которую в дальнейшем будет возвращен пользователь.\r\n * @params string $url Фиксируемый адрес. Если не указан, присваивается текущая страница.\r\n * @return void\r\n */\r\n public function setAnchorUrl($url = null)\r\n {\r\n if($url === null)\r\n $url = Yii::app()->request->getRequestUri();\r\n\r\n $this->setState('_anchorUrl', $url);\r\n }\r\n\r\n /**\r\n * Возвращает адрес якорной страницы.\r\n * @return string\r\n */\r\n public function getAnchorUrl()\r\n {\r\n return $this->getState('_anchorUrl');\r\n }\r\n\r\n /**\r\n * @see CWebUser::beforeLogin()\r\n */\r\n protected function beforeLogin($id, $states, $fromCookie)\r\n {\r\n if ($fromCookie) {\r\n if(!empty($states['cookiesSolt']))\r\n return MUser::model()->findByAttributes(array(\r\n 'id' => $states['id'],\r\n 'cookies_solt' => $states['cookiesSolt'],\r\n ));\r\n else\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Данные о пользователе (модель MUser).\r\n * @var object\r\n */\r\n private $_model = null;\r\n\r\n /**\r\n * Получение экземпляра $this->_model.\r\n * Если он не опреелен, создание нового.\r\n * @return object\r\n */\r\n private function getModel()\r\n {\r\n if (!$this->isGuest && $this->_model === null) {\r\n $this->_model = MUser::model()->findByPk($this->id);\r\n }\r\n\r\n return $this->_model;\r\n }\r\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":25,"cells":{"blob_id":{"kind":"string","value":"043b5fbce711fc4a876aba984ccdac3894bcf3ae"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"jfoxworth/makstudio"},"path":{"kind":"string","value":"/database/migrations/2019_09_03_082133_create_builds_table.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":982,"string":"982"},"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":"bigIncrements('id');\n\t\t\t$table->bigInteger('user_id');\t\t// ID of user that stored the build\n\t\t\t$table->text('build_data');\t\t\t// Content of build\n\t\t\t$table->string('build_id'); \t\t// Something to identify that build - bench, fin wall, etc\n\t\t\t$table->softDeletes();\n\t\t\t$table->timestamps();\n\t\t});\n\t}\n\n\t/**\n\t * Reverse the migrations.\n\t *\n\t * @return void\n\t */\n\tpublic function down()\n\t{\n\t\tSchema::dropIfExists('builds');\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":26,"cells":{"blob_id":{"kind":"string","value":"c0db680a174e29ef21182cb0578569f8a3cee0d0"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"JuanRobles2164/CustomLaravelVersion"},"path":{"kind":"string","value":"/app/Console/Commands/Helpers/MakeViewHelper.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":663,"string":"663"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" $(\"#loginbody\").load(\"report1.php\");\n\t';\n\texit;\n\t}\n\tif($rep == \"rep2\")\n\t{\n\techo '';\n\texit;\n\t}\n\t}\nelse\n\techo \"Incorrect User name or password\";\n?>\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":28,"cells":{"blob_id":{"kind":"string","value":"52be89f86457ce0223d902d6f455a526a1406a5e"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"StereoFlo/Example-Laravel"},"path":{"kind":"string","value":"/engine/app/Models/RoleUser.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1840,"string":"1,840"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"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('user_id', $userId)->where('role_id', $roleId)->get();\n if (!$this->checkEmptyObject($role)) {\n return (bool) $this->create([\n 'role_id' => $roleId,\n 'user_id' => $userId,\n ]);\n }\n return false;\n }\n\n /**\n * @param int $userId\n * @param string $roleId\n *\n * @return bool\n */\n public function enableRoleByName(int $userId, string $roleId): bool\n {\n $getRole = $this->getRole()->getByName($roleId);\n if (empty($getRole)) {\n return false;\n }\n $role = $this->where('user_id', $userId)->where('role_id', $getRole['id'])->get();\n if (!$this->checkEmptyObject($role)) {\n return (bool) $this->create([\n 'role_id' => $getRole['id'],\n 'user_id' => $userId,\n ]);\n }\n return false;\n }\n\n /**\n * @param int $userId\n * @param int $roleId\n *\n * @return bool\n */\n public function disableRole(int $userId, int $roleId = 0): bool\n {\n return $this->where('user_id', $userId)->where('role_id', $roleId)->delete();\n }\n\n /**\n * @param int $userId\n *\n * @return bool\n */\n public function disableAllRole(int $userId): bool\n {\n return $this->where('user_id', $userId)->delete();\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":29,"cells":{"blob_id":{"kind":"string","value":"76737d51eeedea01987cccb61efca92af5478956"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"gaoxiangbo9527/php-manual"},"path":{"kind":"string","value":"/Examples/Language Reference/Constants/Syntax/Example #1 Defining Constants.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":141,"string":"141"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n\t\n\t\t\n\t\t\t\n\t\t\t\t\");\n\t\t\t\tprint(\"\");\n\t\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\t\t\tprint(\"\");\n\t\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\t\t\tprint(\"\");\n\t\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\t\t\tprint(\"\");\n\t\t\t\t$HostRating=getHostRating($userID);\n\t\t\t\t$TotalHostRates=getLikes($userID);\n\t\t\t\t$PlayerRating=getPlayerRating($userID);\n\t\t\t\t$TotalPlayerRates=getTotalRatingsAsPlayer($userID);\n\t\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\t\t\tprint(\"\");\n\t\t\t\tprint(\"\");\n\t\t\tprint(\"\");\n\t\tprint(\"\");\n\tprint(\"
\n\t\t\t\t\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t \t\tprint(\"Profile Picture\");\n\t\t\t\t}\n\t\t\t\tprint(\"Name:{$name}
Age:{$age}
UserName:{$username}
Host Rating:{$HostRating}/{$TotalHostRates} ({$TotalHostRates} vote(s))
Player Rating{$PlayerRating}/{$TotalPlayerRates} ({$TotalPlayerRates} vote(s))
\");\n\tif(isset($_SESSION['UserID']) AND $_SESSION['UserID'] == $userID)\n\t\tprint(\"Edit Profile Information
\");\n\t// getUpcomingGames($userID);\n}\nelse\n{\n\tif(isset($_SESSION['UserID']))\n\t{\n\t\techo \"

User does not exist.

\";\n\t}\n\telse\n\t{\n\t\t\n\t}\n}\n\n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":31,"cells":{"blob_id":{"kind":"string","value":"d98eb5ea9d92dbc065cb468b1b09f1893d52d0aa"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"mctech4/mvc-php"},"path":{"kind":"string","value":"/lib/app/util/hash.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":593,"string":"593"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n \n \n \n getParams() as $k => $v) $response->setValue($k, $v);\n }\n}\n\nclass Quick_Rest_AppRunnerTest\n extends Quick_Test_Case\n implements Quick_Rest_Controller\n{\n public function setUp( ) {\n $this->_cut = new Quick_Rest_AppRunner();\n }\n\n public function testRouteCallShouldAcceptCallbacksThatAppearValid( ) {\n // valid\n $this->_cut->routeCall('GET', '/path1', 'Quick_Rest_AppRunnerTest_EchoController::echoAction');\n $this->_cut->routeCall('GET', '/path2', 'function_exists');\n $this->_cut->routeCall('GET', '/path3', create_function('$a,$b,$c', 'return;'));\n // not valid, but syntactically appear to be\n $this->_cut->routeCall('GET', '/path4', array(\"hello\", \"world\"));\n $this->_cut->routeCall('GET', '/path5', \"Hello, world\");\n }\n\n /**\n * @expectedException Quick_Rest_Exception\n */\n public function testRunCallShouldThrowExceptionIfPathNotRouted( ) {\n $this->_cut->routeCall('GET', '/foo', 'Quick_Rest_AppRunnerTest_EchoController::echoAction');\n $request = $this->_makeRequest('GET', '/bar', array(), array());\n $this->_cut->runCall($request, $this->_makeResponse());\n }\n\n public function invalidCallbackProvider( ) {\n return array(\n array(123),\n array(array(1, 2)),\n );\n }\n\n /**\n * @expectedException Quick_Rest_Exception\n * @dataProvider invalidCallbackProvider\n */\n public function testRouteCallShouldTrowExceptionIfCallbackNotValid( $callback ) {\n $this->_cut->routeCall('GET', '/call/name', $callback);\n }\n\n public function testRunCallShouldInvokeDoublecolonStringCallback( ) {\n $this->_cut->routeCall('GET|POST|OTHER', \"/call/path\", 'Quick_Rest_AppRunnerTest_EchoController::echoAction');\n foreach (array('GET', 'POST', 'OTHER') as $method) {\n $id = uniqid();\n $request = $this->_makeRequest($method, '/call/path', array('a' => 1), array('b' => $id));\n $response = $this->_cut->runCall($request, $this->_makeResponse());\n $this->assertContains($id, $response->getResponse());\n }\n }\n\n public function testRunCallShouldInvokeArrayCallbacks( ) {\n $runner = $this->_makeRunner($calls = array('a', 'b', 'c'));\n foreach ($calls as $call)\n $this->_cut->routeCall('GET', \"/call/$call\", array($runner, $call));\n foreach ($calls as $call) {\n $request = $this->_makeRequest('GET', \"/call/$call\", array(), array());\n $this->_cut->runCall($request, $this->_makeResponse());\n }\n }\n\n public function testRunCallShouldInvokeAnonymousFunctionCallbacks( ) {\n if (version_compare(phpversion(), \"5.3.0\") < 0)\n $this->markTestSkipped();\n $runner = $this->_makeRunner($calls = array('a', 'b', 'c'));\n foreach ($calls as $call)\n $this->_cut->routeCall('GET', \"/call/$call\", function ($req, $resp, $app) use ($runner) {\n $path = $req->getPath();\n $method = substr($path, strrpos($req->getPath(), '/')+1);\n $runner->$method($req, $resp, $app);\n });\n foreach ($calls as $call) {\n $request = $this->_makeRequest('GET', \"/call/$call\", array(), array());\n $this->_cut->runCall($request, $this->_makeResponse());\n }\n }\n\n public function testRunCallShouldInvokeSetCallInsteadOfPath( ) {\n $runner = $this->_makeRunner($calls = array('a'));\n $this->_cut->routeCall('ALL', 'CALLS', array($runner, 'a'));\n $this->_cut->setCall('ALL::CALLS');\n $request = $this->_makeRequest('GET', '/call/foo/bar', array(), array());\n $this->_cut->runCall($request, $this->_makeResponse());\n }\n\n public function testRunCallShouldPassUserAppToActionMethod( ) {\n $app = $this->getMock('Quick_Rest_App', array('getInstance'));\n $controller = $this->getMock('Quick_Rest_Controller', array('testAction'));\n //$this->_cut->routeCall('GET', '/test', array($controller, 'testAction'));\n $routes = array(\n 'GET::/test' => array($controller, 'testAction')\n );\n $this->_cut->setRoutes($routes);\n $request = $this->_makeRequest('GET', '/test', array(), array());\n $response = $this->_makeResponse();\n $controller->expects($this->once())->method('testAction')->with($request, $response, $app);\n $this->_cut->runCall($request, $response, $app);\n }\n\n public function xx_testSpeed( ) {\n $timer = new Quick_Test_Timer();\n $timer->calibrate(10000, array($this, '_testNullSpeed'), array(1, 2));\n echo $timer->timeit(20000, 'empty call', array($this, '_testNullSpeed'), array(1, 2));\n echo $timer->timeit(20000, 'create', array($this, '_testCreateSpeed'), array(1, 2));\n $cut = new Quick_Rest_AppRunner();\n for ($call = 'aa'; $call < 'ac'; $call++) $routes[\"GET::/$call\"] = \"class::$call\";\n $cut->setRoutes($routes);\n echo $timer->timeit(1000, 'set routes(5)', array($this, '_testRoutesSpeed'), array($cut, & $routes));\n // 560k/s for 2, 390k/s for 4, 136k/s for 16, 34k/s for 77, 4k/s for 675\n // w/o is_callable test 1.75m/sec for 675!! (by ref, or 7.7k/s by value overwrite, 11k/s first assign)\n // assigning an array is linear in the number of elements ?? ...even if assigned by reference ??\n $globals = $this->_makeGlobalsForCall('GET', '/call/name', array(), array());\n $request = $this->_makeRequest('GET', '/call/name', array(), array());\n // 640k/s\n $cut->routeCall('GET', '/call/name', 'Quick_Rest_AppRunnerTest_EchoController::echoAction');\n echo $timer->timeit(20000, 'route to string w/ request', array($this, '_testRunCallSpeed'), array($cut, $request));\n // 140k/s\n echo $timer->timeit(20000, 'route to string w/ globals', array($this, '_testRunCallSpeedGlobals'), array($cut, $globals));\n // 90k/s\n $cut->routeCall('GET', '/call/name', array(new Quick_Rest_AppRunnerTest_EchoController(), 'echoAction'));\n echo $timer->timeit(20000, 'route to callback w/ globals', array($this, '_testRunCallSpeedGlobals'), array($cut, $globals));\n // 101k/s\n echo $timer->timeit(20000, 'oneshot, handle page hit', array($this, '_testOneshotPageHitSpeed'), array($cut, $globals));\n // 65k/s (85k/s on amd 3.6 GHz)\n // NOTE: measuring inside apache to capture apc autoloading delays, more like ~1k (cold) to 4k/s (looped)\n }\n\n public function _testNullSpeed( $x, $y ) {\n }\n\n public function _testRoutesSpeed( $cut, & $routes ) {\n $cut->setRoutes($routes);\n }\n\n public function _testCreateSpeed( $x, $y ) {\n $new = new Quick_Rest_AppRunner();\n }\n\n public function _testRunCallSpeed( $cut, $request ) {\n $cut->runCall($request, new Quick_Rest_Response_Http());\n }\n\n public function _testRunCallSpeedGlobals( $cut, & $globals ) {\n $request = new Quick_Rest_Request_Http();\n $request->setParamsFromGlobals($globals);\n $response = new Quick_Rest_Response_Http();\n $cut->runCall($request, $response);\n }\n\n public function _testOneshotPageHitSpeed( $cut, & $globals ) {\n $cut = new Quick_Rest_AppRunner();\n $request = new Quick_Rest_Request_Http();\n $request->setParamsFromGlobals($globals);\n $response = new Quick_Rest_Response_Http();\n //$cut->routeCall('GET', '/call/name', 'Quick_Rest_AppRunnerTest_EchoController::echoAction');\n $cut->routeCall('GET', $request->getPath(), 'Quick_Rest_AppRunnerTest_EchoController::echoAction');\n $cut->runCall($request, $response);\n }\n\n protected function _makeGlobalsForCall( $method, $uri, Array $getargs, Array $postargs ) {\n return $globals = array(\n '_GET' => $getargs,\n '_POST' => $postargs,\n '_SERVER' => array(\n 'SERVER_PROTOCOL' => 'HTTP/1.1',\n 'REQUEST_METHOD' => strtoupper($method),\n 'REQUEST_URI' => $uri,\n ),\n );\n }\n\n protected function _makeRequest( $method, $uri, Array $getargs, Array $postargs ) {\n $request = new Quick_Rest_Request_Http();\n $globals = $this->_makeGlobalsForCall($method, $uri, $getargs, $postargs);\n $request->setParamsFromGlobals($globals);\n return $request;\n }\n\n protected function _makeResponse( ) {\n return new Quick_Rest_Response_Http();\n }\n\n protected function _makeRunner( Array $calls ) {\n $runner = $this->getMock('Quick_Rest_Controller', $calls);\n foreach ($calls as $call)\n $runner->expects($this->once())->method($call);\n return $runner;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":35,"cells":{"blob_id":{"kind":"string","value":"44e7c93fa4d1df486888989c30b2c93c15b8108b"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"netzmacht/tapatalk-client-api"},"path":{"kind":"string","value":"/src/Netzmacht/Tapatalk/Api/Users/User.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1274,"string":"1,274"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n * @copyright 2014 netzmacht creative David Molineus\n * @license LGPL 3.0\n * @filesource\n *\n */\n\nnamespace Netzmacht\\Tapatalk\\Api\\Users;\n\n\nuse Netzmacht\\Tapatalk\\Transport\\MethodCallResponse;\n\nclass User\n{\n\t/**\n\t * @var int\n\t */\n\tprivate $id;\n\n\t/**\n\t * @var string\n\t */\n\tprivate $username;\n\n\t/**\n\t * @var string\n\t */\n\tprivate $avatarUrl;\n\n\n\t/**\n\t * @param int $id\n\t * @param string $username\n\t * @param string $avatar\n\t */\n\tfunction __construct($id, $username, $avatar)\n\t{\n\t\t$this->id = $id;\n\t\t$this->username = $username;\n\t\t$this->avatarUrl = $avatar;\n\t}\n\n\t/**\n\t * @param MethodCallResponse $response\n\t * @return User\n\t */\n\tpublic static function fromResponse(MethodCallResponse $response)\n\t{\n\t\treturn new static(\n\t\t\t$response->get('user_id'),\n\t\t\t$response->get('username', true),\n\t\t\t$response->get('icon_url')\n\t\t);\n\t}\n\n\n\t/**\n\t * @return mixed\n\t */\n\tpublic function getAvatarUrl()\n\t{\n\t\treturn $this->avatarUrl;\n\t}\n\n\n\t/**\n\t * @return bool\n\t */\n\tpublic function hasAvatar()\n\t{\n\t\treturn ($this->avatarUrl != null);\n\t}\n\n\n\t/**\n\t * @return int\n\t */\n\tpublic function getId()\n\t{\n\t\treturn $this->id;\n\t}\n\n\n\t/**\n\t * @return string\n\t */\n\tpublic function getUsername()\n\t{\n\t\treturn $this->username;\n\t}\n\n} "},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":36,"cells":{"blob_id":{"kind":"string","value":"b2db89ce7666651da494b824d1fa72f9e16588c9"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"lx1986tao16/tandyBlog"},"path":{"kind":"string","value":"/app/Http/Controllers/Admin/TagsController.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1636,"string":"1,636"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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":"validate($request, [\n 'name' => 'required|max:255|unique:tags',\n ]);\n\n Tag::create([\n 'name' => $request->name,\n ]);\n\n session()->flash('success', '创建Tag成功!');\n return redirect()->back();\n }\n\n public function edit($id)\n {\n $tags = Tag::findOrFail($id);\n return view('admin.tags.edit', compact('tags'));\n }\n\n public function update($id, Request $request)\n {\n $tags = Tag::findOrFail($id);\n $tags->name = $request->name;\n $tags->update();\n\n session()->flash('success', 'Tag更新成功');\n return redirect()->route('tags.index');\n }\n\n public function destroy($id)\n {\n $tag = Tag::findOrFail($id);\n $tag->delete();\n\n session()->flash('success', '删除tag成功');\n return redirect()->back();\n }\n\n public function getTags()\n {\n $tags = Tag::all();\n $tags_data = [];\n foreach ($tags as $tag) {\n array_push($tags_data, [\n \"value\" => $tag->id,\n \"text\" => $tag->name,\n ]);\n }\n\n return response()->json($tags_data);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":37,"cells":{"blob_id":{"kind":"string","value":"f6526cf0af8ac918ebb9e87c8f373b3c64a8d634"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"wwrona/php"},"path":{"kind":"string","value":"/powitalna.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":559,"string":"559"},"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":"\n\n\n\n\t Strona powitalna\n\n\n\n

Części samochodwe

\n
\n\n\n\";\n\t}\n*/\n// A teraz to samo, tylko przy użyciu concatenation:\nfor ($i = 0; $i < 4; $i++) {\necho \"\";\n}\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":38,"cells":{"blob_id":{"kind":"string","value":"6f166812d885eb0b9a553d49bf06eef21f39b141"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"marscore/hhvm"},"path":{"kind":"string","value":"/hphp/test/zend/good/ext/standard/tests/strings/htmlspecialchars_decode_variation6.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1043,"string":"1,043"},"score":{"kind":"number","value":3.5625,"string":"3.5625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["Zend-2.0","PHP-3.01","MIT"],"string":"[\n \"Zend-2.0\",\n \"PHP-3.01\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"> function main() {\necho \"*** Testing htmlspecialchars_decode() : usage variations ***\\n\";\n\n//various string inputs\n$strings = array (\n \"\\tHello \\$world \".chr(0).\"\\&!)The big brown fox jumped over the\\t\\f lazy dog\\v\\n\",\n \"\\tHello \\\"world\\\"\\t\\v \\0 This is a valid\\t string\",\n \"This converts\\t decimal to \\$string\".decbin(65).\"Hello world\",\n b\"This is a binary\\t \\v\\fstring\"\n);\n\n//loop through the strings array to check if htmlspecialchars_decode() is binary safe\n$iterator = 1;\nforeach($strings as $value) {\n echo \"-- Iteration $iterator --\\n\";\n if ($iterator < 4) {\n var_dump( htmlspecialchars_decode($value) );\n } else {\n var_dump( bin2hex(htmlspecialchars_decode($value)));\n }\n\n $iterator++;\n}\n\necho \"Done\";\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":39,"cells":{"blob_id":{"kind":"string","value":"0854c5788103ec628c79b802f09496d9beed8735"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"JvMolli/2DawServidor"},"path":{"kind":"string","value":"/examenPhp/controllers/persona.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":961,"string":"961"},"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":"nombre = $nombre;\n $this->apellidos = $apellidos;\n $this->sexo = $sexo;\n $this->edad = $edad;\n $this->telefono = $telefono;\n $this->imagen = $imagen;\n $this->contraseña = $contraseña;\n }\n\n// function getJsonData(){\n// $var = get_object_vars($this);\n// foreach ($var as &$value) {\n// if (is_object($value) && method_exists($value,'getJsonData')) {\n// $value = $value->getJsonData();\n// }\n// }\n// return $var;\n// }\n\n function __toString(){\n return $this->nombre . \" \" . $this->apellidos . \" \" . $this->sexo . \" \" . $this->edad . \" \" . $this->telefono . \" \" . $this->contraseña;\n }\n\n } \n\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":40,"cells":{"blob_id":{"kind":"string","value":"db9724d43ce97b4f11e4d54e28ad08c40438f580"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"rozinCodes/school-management"},"path":{"kind":"string","value":"/API/application/controllers/api/Login.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1927,"string":"1,927"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"load->database();\n $this->load->model(array(\"api/student_model\"));\n $this->load->model(array(\"api/common_model\"));\n $this->load->library(array(\"form_validation\"));\n $this->load->helper(\"security\");\n }\n \n\n public function admin_login_post(){\n\n $this->form_validation->set_rules(\"email\", \"Email\", \"required\");\n\n if ($this->form_validation->run() == NULL) {\n // we have some errors\n $this->response(array(\n \"status\" => 0,\n \"message\" => \"All fields are needed or filled form is not valid\"\n ) , REST_Controller::HTTP_OK);\n } else {\n\n $email = $this->security->xss_clean($this->input->post(\"email\"));\n $password = $this->security->xss_clean($this->input->post(\"password\"));\n\n $user = $this->common_model->admin_login($email, $password);\n if ($user) {\n $userdata = array(\n \"id\" => $user->ID,\n \"email\" => $user->EMAIL,\n \"first_name\" => $user->FIRST_NAME,\n \"photo\" => $user->PHOTO, \n //\"surname\" => $user->surname,\n \"roles\" => $user->ROLES_ID,\n \"authenticated\" => TRUE\n );\n\n $this->response(array(\n \"status\" => 1,\n \"message\" => \"Login Success\"\n ), REST_Controller::HTTP_OK);\n } else {\n // we have some empty field\n $this->response(array(\n \"status\" => 0,\n \"message\" => \"Login credential does not match\"\n ), REST_Controller::HTTP_OK);\n }\n }\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":41,"cells":{"blob_id":{"kind":"string","value":"64e2e363e1ec47d2ea38f353e75633e09098d4b8"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"andreadlm/unito"},"path":{"kind":"string","value":"/tweb/Vuvuzela/services/functions/authors.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1073,"string":"1,073"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"prepare(AUTHOR_QUERY);\n $statement->bindValue(':num', $num, PDO::PARAM_INT);\n $statement->execute();\n return $statement->fetchAll(PDO::FETCH_ASSOC);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":42,"cells":{"blob_id":{"kind":"string","value":"7a9398b48162c198ba025f87637b1dc6ec76e7c0"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"big-javascript-fan/HyonMoo-WooCom"},"path":{"kind":"string","value":"/hyunmoo/framework/theme/shortcodes/one_half.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":686,"string":"686"},"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":" 'no',\r\n\t\t\t), $atts);\r\n\t\t\r\n\t\t# Overwrite Default Attributes\r\n\t\t$atts = shortcode_atts( $default_atts, $atts );\r\n\r\n\t\textract( $atts );\r\n\t\t\r\n\t\t$output=\"\";\r\n\t\tif($last == 'yes') {\r\n\t\t\t$output.= '
' .do_shortcode($content). '
';\r\n\t\t} else {\r\n\t\t\t$output.= '
' .do_shortcode($content). '
';\r\n\t\t}\r\n\t\treturn $output;\r\n\t}\r\n\t\r\n\tadd_shortcode('one_half', 'hyunmoo_shortcode_one_half');\r\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":43,"cells":{"blob_id":{"kind":"string","value":"a9c8407a8d2770795c860bcf971c304185a0313a"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"nachovazquez1990/mongril_club"},"path":{"kind":"string","value":"/public_html/admin/model/consumo_class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4804,"string":"4,804"},"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":"0){\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction create_consumo($socios_id, $productos_id, $cantidad, $importe, $fecha){\n\tglobal $link;\n\n\t$socio_id = (int) $socios_id;\n\t$producto_id = (int) $productos_id;\n\t$cantidad = (float) $cantidad;\n\t$importe = (float) $importe;\n\t$fecha = $fecha;\n\t\n\tif( !$socio_id || !$producto_id || !$cantidad || !$importe || !$fecha ){\n\t\treturn false;\n\t}\n\n\t$sql = \"INSERT INTO consumos(socios_id, productos_id, cantidad, importe, fecha)\n\t\t\tVALUES('$socios_id', '$producto_id', '$cantidad', '$importe', '$fecha')\";\n\t$query = mysqli_query($link,$sql);\n\n\tif(mysqli_insert_id($link)>0){\n\t\trestar_dinero_socio($socio_id, $importe);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction read_consumo_by_id( $id ){\n\t\n\tglobal $link;\n\t\n\t$id = (int) $id; \n\n\t$sql = \"SELECT consumo_id, socios_id, producto, precio, importe, fecha FROM consumos\n\t\t\tLEFT JOIN socios ON socios_id = socio_id\n\t\t\tLEFT JOIN productos ON productos_id = producto_id\n\t\t\tWHERE consumo_id = '$id'\";\n\t$query = mysqli_query($link,$sql); \n\n\t$num_rows = mysqli_num_rows($query);\n\tif( $num_rows > 0 ){\n\t\treturn mysqli_fetch_assoc($query);\n\t}\n\treturn false;\n}\n\nfunction read_consumo_by_name( $producto ){\n\t\n\tglobal $link;\n\t\n\t$producto = mysqli_real_escape_string($link,$producto); \n\n\tif(!$producto){\n\t\treturn false;\n\t}\n\n\t$sql = \"SELECT consumo_id, producto, precio, fecha FROM consumos\n\t\t\tLEFT JOIN productos ON productos_id = producto_id\n\t\t\tWHERE productos.producto = '$producto'\";\n\t$query = mysqli_query($link,$sql); \n\n\t$num_rows = mysqli_num_rows($query);\n\tif( $num_rows > 0 ){\n\t\treturn mysqli_fetch_assoc($query);\n\t}\n\treturn false;\n}\n\nfunction read_all_consumos(){\n\t\n\tglobal $link;\n\t\n\t$sql = \"SELECT consumo_id, socios_id, producto, precio, cantidad, importe, fecha FROM consumos\n\t\t\tLEFT JOIN productos ON productos_id = producto_id\n\t\t\tORDER BY consumo_id DESC\";\n\t$query = mysqli_query($link,$sql); \n\n\t$num_rows = mysqli_num_rows($query);\n\tif( $num_rows > 0 ){\n\t\treturn $query;\n\t}\n\treturn false;\n}\n\nfunction delete_consumo( $id ){\n\t\n\tglobal $link;\n\t\n\t$id = (int) $id;\n\n\t$consumo = read_consumo_by_id($id);\n\t$socio_id = $consumo['socios_id'];\n\t$importe = $consumo ['importe'];\n\n\t$resultado = devolver_dinero_socio($socio_id, $importe);\n\tif ($resultado = false) {\n\t\treturn false;\n\t}\n\t$sql = \"DELETE FROM consumos\n\t\t\tWHERE consumo_id = '$id'\";\n\t$query = mysqli_query($link,$sql); \n\n\t$affected_rows = mysqli_affected_rows( $link );\n\tif( $affected_rows > 0 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":44,"cells":{"blob_id":{"kind":"string","value":"144c2685e7c760594d90bcc317930f9cd4c96572"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"gcarneiro/sheer"},"path":{"kind":"string","value":"/sheer/core/action/queryGenerator/Add.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2892,"string":"2,892"},"score":{"kind":"number","value":3.1875,"string":"3.1875"},"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":"actionHandler = $actionHandler;\n\t\t\n\t}\n\t\n\t/**\n\t * Método gerador da query\n\t * @param array $data\n\t * @return mixed\n\t */\n\tpublic function getQuery ($data) {\n\t\t\n\t\t//EFETUO O PROCESSAMENTO DO FIELDLIST E DOS VALORES\n\t\t$this->createFieldListAndValuesQuery($data);\n\t\t\n\t\t//GERO O NOME DA TABLE\n\t\t$this->createTableQuery();\n\t\t\n\t\t//CRIANDO A QUERY\n\t\t$replacement = array('{table}', '{fieldlist}', '{values}');\n\t\t$value = array($this->table, $this->fieldlist, $this->values);\n\t\t$query = str_replace($replacement, $value, self::QUERY_PATTERN);\n\t\t\n\t\treturn $query;\n\t\t\n\t}\n\t\n\t/**\n\t * Método para gerar o fieldList do datasource com os fields desejados\n\t */\n\tprotected function createFieldListAndValuesQuery ($data) {\n\t\t\n\t\t$queryFieldList\t= '';\n\t\t$queryValues = '';\n\t\t$first = true;\n\t\t$fields = $this->actionHandler->getDataSource()->getFields(false);\n\t\t\n\t\t//itero por todos os fields gerando tanto o fieldList quanto capturando o seu valor\n\t\tforeach ( $fields as $field ) {\n\t\t\tif( !$first ) { \n\t\t\t\t$queryFieldList .= ', ';\n\t\t\t\t$queryValues .= ', ';\n\t\t\t}\n\t\t\t\n\t\t\t//GERANDO O FIELDLIST\n\t\t\t$queryFieldList .= $field->getId();\n\t\t\t\n\t\t\t//GERANDO O VALOR\n\t\t\t\n\t\t\t//determinando o valor enviado [considero enviado se for array ou tiver pelo menos um caracter]\n\t\t\t$valorEnviado = false;\n\t\t\tif( isset($data[$field->getId()]) && ( is_array($data[$field->getId()]) || strlen($data[$field->getId()]) > 0 ) ) {\n\t\t\t\t$valorEnviado = true;\n\t\t\t}\n\t\t\t\n\t\t\t//se o valor foi enviado corretamente\n\t\t\tif( $valorEnviado ) {\n\t\t\t\t//Removo a conversao input=>primitive daqui e jogo pro actionClass para conseguir inserir arquivos\n// \t\t\t\t$sqlValue = $field::formatInputDataToPrimitive($data[$field->getId()]);\n\t\t\t\t$sqlValue = addslashes($data[$field->getId()]);\n\t\t\t\t$queryValues .= '\"'.$sqlValue.'\"';\n\t\t\t}\n\t\t\t//o valor não foi enviado\n\t\t\telse {\n\t\t\t\tif( $field->getSetNullIfBlank() ) {\n\t\t\t\t\t$queryValues .= 'NULL';\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t$queryValues .= '\"\"';\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t$first = false;\n\t\t}\n\t\t\n\t\t$queryFieldList = '('.$queryFieldList.')';\n\t\t$queryValues = '('.$queryValues.')';\n\t\t\n\t\t$this->fieldlist = $queryFieldList;\n\t\t$this->values = $queryValues;\n\t}\n\t\n\t/**\n\t * Método para gerar o campo \"table\" da query\n\t */\n\tprotected function createTableQuery () {\n\t\t$this->table = $this->actionHandler->getDataSource()->getTable();\n\t}\n\t\n\t\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":45,"cells":{"blob_id":{"kind":"string","value":"7245389bf5ad8ab0a8174c6b297e4f8e673e62e0"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"Ashiyro/Mon-Framework"},"path":{"kind":"string","value":"/Components/Router/Router.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1445,"string":"1,445"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"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":"router = new FastRouteRouter();\n }\n\n /**\n * @param string $path\n * @param string|callable $callable\n * @param string $name\n */\n public function get(string $path, $callable, ?string $name = null)\n {\n $this->router->addRoute(new ZendRoute($path, $callable, ['GET'], $name));\n }\n\n\n public function post(string $path, $callable, ?string $name = null)\n {\n $this->router->addRoute(new ZendRoute($path, $callable, ['POST'], $name));\n }\n\n /**\n * @param ServerRequestInterface $request\n * @return Route|null\n */\n public function match(ServerRequestInterface $request): ?Route\n {\n $result = $this->router->match($request);\n if ($result->isSuccess()) {\n return new Route(\n $result->getMatchedRouteName(),\n $result->getMatchedMiddleware(),\n $result->getMatchedParams()\n );\n }\n return null;\n }\n\n public function generateUri(string $name, array $params): ?string\n {\n return $this->router->generateUri($name, $params);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":46,"cells":{"blob_id":{"kind":"string","value":"51418500e4421e4f5773232a7df85b39db603e6f"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"commercetools/commercetools-sdk-php-v2"},"path":{"kind":"string","value":"/lib/commercetools-api/src/Models/ShippingMethod/ShippingMethodAddZoneActionBuilder.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1760,"string":"1,760"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"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 */\nfinal class ShippingMethodAddZoneActionBuilder implements Builder\n{\n /**\n\n * @var null|ZoneResourceIdentifier|ZoneResourceIdentifierBuilder\n */\n private $zone;\n\n /**\n *

Value to add to zoneRates.

\n *\n\n * @return null|ZoneResourceIdentifier\n */\n public function getZone()\n {\n return $this->zone instanceof ZoneResourceIdentifierBuilder ? $this->zone->build() : $this->zone;\n }\n\n /**\n * @param ?ZoneResourceIdentifier $zone\n * @return $this\n */\n public function withZone(?ZoneResourceIdentifier $zone)\n {\n $this->zone = $zone;\n\n return $this;\n }\n\n /**\n * @deprecated use withZone() instead\n * @return $this\n */\n public function withZoneBuilder(?ZoneResourceIdentifierBuilder $zone)\n {\n $this->zone = $zone;\n\n return $this;\n }\n\n public function build(): ShippingMethodAddZoneAction\n {\n return new ShippingMethodAddZoneActionModel(\n $this->zone instanceof ZoneResourceIdentifierBuilder ? $this->zone->build() : $this->zone\n );\n }\n\n public static function of(): ShippingMethodAddZoneActionBuilder\n {\n return new self();\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":47,"cells":{"blob_id":{"kind":"string","value":"3965246462eb3b518e19185905c4c9a77144d973"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"mcordingley/HashBin"},"path":{"kind":"string","value":"/src/Hasher.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":222,"string":"222"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"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":"_request->get('count', 10);\n if ($perPage > 500) {\n $perPage = 500;\n }\n elseif ($perPage <= 0) {\n $perPage = 10;\n }\n\n // page number\n $pageNumber = ($this->_request->get('offset', 0) / $perPage) + 1;\n\n /**\n * Pager Configuration\n */\n $this->_pager->setCurrentPageNumber($pageNumber);\n $this->_pager->setItemCountPerPage($perPage);\n $fields = $this->_pager->getFields();\n $fieldsIndex = array_keys($fields);\n\n /**\n * Formatting datas\n */\n $items = $this->_pager->getItems();\n $infos = $this->_pager->getPages();\n\n $datas = array();\n foreach ($items as $obj) {\n $item = array();\n foreach ($fields as $field) {\n $item[$field->getProperty()] = $field->readData($obj);\n }\n $datas[] = $item;\n }\n\n $response = array(\n \"fromPage\" => $this->_request->get('fromPage', 0),\n \"total\" => $infos->totalItemCount,\n \"count\" => count($datas),\n \"stories\" => $datas\n );\n\n return $this->jsonResponse($response);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":49,"cells":{"blob_id":{"kind":"string","value":"e241420ba1f687eb110432bd2be84b2297dabe76"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"hanxiao84322/coach_system"},"path":{"kind":"string","value":"/models/Activity.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5233,"string":"5,233"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":" '周末班',\n self::DAILY => '日常班'\n ];\n\n //课程状态\n const NEW_ADD = 1;\n const BEGIN_SIGN_UP = 2;\n const END_SIGN_UP = 3;\n const DOING = 4;\n const END = 5;\n\n static public $statusList = [\n self::NEW_ADD => '未开始报名',\n self::BEGIN_SIGN_UP => '报名开始',\n self::END_SIGN_UP => '报名结束',\n self::DOING => '进行中',\n self::END => '结束',\n ];\n\n public $already_recruit_count;\n\n /**\n * @inheritdoc\n */\n public static function tableName()\n {\n return 'activity';\n }\n\n /**\n * @inheritdoc\n */\n public function rules()\n {\n return [\n [['category', 'level_id', 'recruit_count', 'sign_up_status', 'status', 'lesson', 'score'], 'integer'],\n [['sign_up_begin_time', 'sign_up_end_time', 'begin_time', 'end_time', 'create_time', 'update_time'], 'safe'],\n [['content','bus','near_site'], 'string'],\n [['name', 'create_user', 'update_user'], 'string', 'max' => 45],\n [['address', 'launch', 'organizers', 'join_teams'], 'string', 'max' => 50]\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function attributeLabels()\n {\n return [\n 'id' => 'ID',\n 'name' => '名称',\n 'category' => '分类',\n 'level_id' => '级别',\n 'recruit_count' => '招收人数',\n 'sign_up_begin_time' => '报名开始时间',\n 'sign_up_end_time' => '报名结束时间',\n 'sign_up_status' => '报名状态',\n 'begin_time' => '开始时间',\n 'end_time' => '结束时间',\n 'status' => '状态',\n 'lesson' => '课时',\n 'address' => '地址',\n 'score' => '活动积分',\n 'launch' => '发起者',\n 'organizers' => '主办方',\n 'join_teams' => '参训着',\n 'content' => '内容',\n 'bus' => '公交路线',\n 'near_site' => '周边站点',\n 'create_time' => '创建时间',\n 'create_user' => '创建人',\n 'update_time' => '更新时间',\n 'update_user' => '更新人',\n ];\n }\n\n /**\n * @return \\yii\\db\\ActiveQuery\n */\n public function getLevel()\n {\n return $this->hasOne(Level::className(), ['id' => 'level_id']);\n }\n\n /**\n * @return \\yii\\db\\ActiveQuery\n */\n public function getActivityUsers()\n {\n return $this->hasMany(ActivityUsers::className(), ['activity_id' => 'id']);\n }\n\n public static function getAll()\n {\n $rows = (new \\yii\\db\\Query())\n ->select(['id', 'name'])\n ->from(self::tableName())\n ->where(['status'=>'1'])\n ->all();\n return $rows;\n }\n\n public static function getCategoryName($category)\n {\n return isset(self::$categoryList[$category]) ? self::$categoryList[$category] : $category;\n }\n\n public static function getSignUpStatusName($signUpStatus)\n {\n return isset(self::$signUpStatusList[$signUpStatus]) ? self::$signUpStatusList[$signUpStatus] : $signUpStatus;\n }\n\n public static function getStatusName($status)\n {\n return isset(self::$statusList[$status]) ? self::$statusList[$status] : $status;\n }\n\n public static function getOneActivityNameById($activityId)\n {\n $sql = \"SELECT name FROM `activity` WHERE id='\" . $activityId . \"'\";\n $result = Yii::$app->db->createCommand($sql)->queryOne();\n return $result['name'];\n }\n\n\n public function beforeSave($insert = '')\n {\n if (parent::beforeSave($this->isNewRecord)) {\n if ($this->isNewRecord) {\n $this->create_time = date('Y-m-d H:i:s', time());\n $this->create_user = 'admin';\n $this->update_time = date('Y-m-d H:i:s', time());\n $this->update_user = 'admin';\n } else {\n $this->update_time = date('Y-m-d H:i:s', time());\n $this->update_user = 'admin';\n }\n return true;\n } else {\n return false;\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":50,"cells":{"blob_id":{"kind":"string","value":"0fd6ed1f77dbe0c992f76b3fb542f199cfdef076"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"JayDeeJaye/anaconda-jdj-f"},"path":{"kind":"string","value":"/apis/apiHeader.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":947,"string":"947"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"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":"getCode() ?: 400;\n\theader(\"Content-Type: application/json\", NULL, $code);\n\techo json_encode([\"error\" => $e->getMessage()],JSON_PRETTY_PRINT);\n\texit;\n});\n\n// Get the request verb\n$verb = $_SERVER['REQUEST_METHOD'];\n\n// Get the api route keys from the url for GET, PUT, and DELETE\nswitch($verb) {\n case 'GET':\n case 'PUT':\n case 'DELETE':\n //GET, PUT, and DELETE requests have the form api.php/target\n\n $my_path_info = str_replace($_SERVER['SCRIPT_NAME'],'',$_SERVER['REQUEST_URI']);\n $url_pieces = explode('/', $my_path_info);\n}\n\n// Get the data from the PUT and POST requests \nswitch($verb) {\n case 'PUT':\n case 'POST':\n $params = json_decode(file_get_contents(\"php://input\"), true);\n if(!$params) {\n throw new Exception(\"Data missing or invalid\");\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":51,"cells":{"blob_id":{"kind":"string","value":"673f1c6173757c3db81787284e7288497f6f10c2"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"andrii-androshchuk/api-framework"},"path":{"kind":"string","value":"/framework/configuration/configuration.class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7908,"string":"7,908"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" \n * @copyright 2013 (c) Androschuk Andriy\n *\n * @version 0.1\n */\n\n \nclass Configuration {\n \n\t// Singletone\n private static $p_instance;\n \n // Files\n private $config_file_path;\n private $config_file_hash; \n private $php_config_file_path;\n \n // Parameters\n private $parameters = array();\n\n\n private function __construct() {}\n\n \n /**\n * @name initialize\n * Load configurations. \n * \n * @param string : name of configuration's file\n */\n public function initialize($configuration_name = \"main\") {\n \n $this->config_file_path = APPLICATION_CONFIGURATION_PATH . $configuration_name . \".cfg\";\n \n // The .cfg file doesn't exists\n if (!file_exists($this->config_file_path)) {\n \n Log::error(\"Not found .cfg file in path: $this->config_file_path\", \"Configuration\");\n }\n\n // Get hash of file\n $this->config_file_hash = md5_file($this->config_file_path);\n \n // Build path to .php configuration file\n $this->php_config_file_path = APPLICATION_CACHE_PATH . \"configuration\\\\\" . $this->config_file_hash . \".php\";\n \n // If file doesn't exists then create new \n if (!file_exists($this->php_config_file_path)) {\n \n Log::notice(\"Not found .php (compiled) configuration file in path: $this->php_config_file_path\", \"Configuration\");\n\n // Load data from .cfg file\n $file = file($this->config_file_path);\n \n if(count($file) == 0) {\n\n Log::notice(\"In configuration's file $this->config_file_path is not found keys\", \"Configuration\");\n\n return;\n }\n \n // Output string to .php configuration file\n $configuration_str = ''$value',\";\n }\n\n unset($connection_name);\n unset($file);\n \n // Delete last coma & space in array list\n $configuration_str = substr($configuration_str, 0, strlen($configuration_str) - 1);\n \n $configuration_str .= '); Configuration::instance()->loadFromArray($configuration_array);';\n \n \n // Put it into .php file\n file_put_contents($this->php_config_file_path, $configuration_str);\n \n Log::success(\"Created new configuration .php file: $this->php_config_file_path\", \"Configuration\");\n \n \n // Find and delete previous file of configuration from cache\n $files = scandir(APPLICATION_CACHE_PATH . \"configuration\");\n \n foreach ($files as $file) {\n \n if(!in_array($file, array(\".\", \"..\", \".svn\", $this->config_file_hash . \".php\"))) {\n\n unlink(APPLICATION_CACHE_PATH . \"configuration\\\\\" . $file);\n \n Log::success(\"Deleted cache configuration file: \" . APPLICATION_CACHE_PATH . \"configuration\\\\\" . $file, \"Configuration\");\n } \n }\n \n unset($files);\n }\n\n // Loading configuration\n require_once $this->php_config_file_path;\n }\n \n \n /**\n * @name instance\n * Singletone function.\n * \n * @return instance of itself \n */\n public static function instance() {\n \n if(!self::$p_instance) {\n \n self::$p_instance = new self();\n }\n \n return self::$p_instance;\n }\n \n \n /**\n * @name get\n * The function returns value of configuration parameter.\n * \n * @param string : name of configuration key\n * @return value of it.\n */ \n public function _get($_key) {\n\n if(!isset($this->parameters[$_key])) {\n \n Log::error(\"Unknow configuration key: $_key\", \"Configuration\");\n }\n \n // If parameter is boolean the return is as boolean type.\n switch($this->parameters[$_key]) {\n \n case \"true\": {\n \n return true;\n } break;\n \n case \"false\": {\n \n return false;\n } break;\n \n default: {\n \n return $this->parameters[$_key];\n } break;\n }\n }\n \n \n /**\n * @name loadFromArray\n * The function that takes parameters from array and puts it into private array.\n * \n * @param array : array of parameters\n */ \n public function loadFromArray($_arr) {\n\n $this->parameters = $_arr;\n\n Log::success(\"Configuration loaded from file: $this->php_config_file_path\", \"Configuration\");\n Log::success(\"Configuration keys count:\" . count($this->parameters), \"Configuration\"); \n }\n\n\n /**\n * @name get\n * The function return value of paramter\n * \n * @param string : name of parameter\n */\n public static function get($n) {\n\n return self::instance()->_get($n);\n }\n\t\n\t\n /**\n * @name clearCache\n * The function make clean up in cache directory\n */\n\tpublic static function clearCache() {\n\t\t\n \t$files = scandir(APPLICATION_CACHE_PATH . \"configuration\");\n \n\t\t// delete '.' & '..'\n\t\tunset($files[0]);\n\t\tunset($files[1]);\n\t\t\t \n foreach ($files as $file) {unlink(APPLICATION_CACHE_PATH . \"configuration\\\\\" . $file);\n \n Log::success(\"Deleted cache configuration file: \" . APPLICATION_CACHE_PATH . \"configuration\\\\\" . $file, \"Configuration\"); \n }\t\t\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":52,"cells":{"blob_id":{"kind":"string","value":"cc2cb4e911a729be112a191245f99d677d7e1800"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"savalonso/SEVRI"},"path":{"kind":"string","value":"/controladora/ctrUsuarios.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3286,"string":"3,286"},"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":"setCedula($_POST['cedula']);\n\t\t$usuario->setNombre($_POST['nombre']);\n\t\t$usuario->setPrimerApellido($_POST['primerApellido']);\n\t\t$usuario->setSegundoApellido($_POST['segundoApellido']);\n\t\t$usuario->setTelefono($_POST['telefono']);\n\t\t$usuario->setCorreo($_POST['email']);\n\t\t$usuario->setClave($_POST['clave']);\n\t\t$usuario->setCargo($_POST['cargo']);\n\t\t$usuario->setTipo($_POST['tipo']);\n\t\t$dataUsuarios = new dtUsuario;\n\t\t\n\t\tif($dataUsuarios->insertarUsuario($usuario) == true){\n\t\t\techo 'Se ha insertado correctamente el usuario.';\n\t\t} else {\n\t\t\techo 'No se ha insertado el usuario.';\n\t\t}\n\t}\n\t\n\tfunction actualizarUsuarios(){\n\t\t\n\t\tinclude_once (\"../dominio/dUsuario.php\");\n\t\tinclude_once (\"../data/dtUsuario.php\");\n\t\t\n\t\t$usuario = new dUsuario();\n\t\t$usuario->setNombre($_POST['nombre']);\n\t\t$usuario->setPrimerApellido($_POST['primerApellido']);\n\t\t$usuario->setSegundoApellido($_POST['segundoApellido']);\n\t\t$usuario->setTelefono($_POST['telefono']);\n\t\t$usuario->setCorreo($_POST['email']);\n\t\t$usuario->setClave($_POST['clave']);\n\t\t$usuario->setCargo($_POST['cargo']);\n\t\t$usuario->setTipo($_POST['tipo']);\n\t\t$cedula = $_POST['cedula'];\n\t\t$dataUsuario = new dtUsuario();\n\t\t\n\t\tif($dataUsuario->actualizarUsuario($usuario,$cedula) == true){\n\t\t\techo 'Se ha modificado correctamente el usuario.';\n\t\t} else {\n\t\t\techo 'No se ha modificado el usuario.';\n\t\t}\n\t}\n\t\n\t\n\tfunction eliminarUsuarios(){\n\t\t\n\t\tinclude_once (\"../dominio/dUsuario.php\");\n\t\tinclude_once (\"../data/dtUsuario.php\");\n\t\t\n\t\t$cedula = $_POST['cedula'];\n\t\t$dataUsuarios = new dtUsuario;\n\t\t\n\t\tif($dataUsuarios->eliminarUsuarios($cedula) == true){\n\t\t\techo 'Se ha eliminado correctamente el usuario.';\n\t\t} else {\n\t\t\techo 'No se ha eliminado el usuario.';\n\t\t}\n\t}\n\t\n\tfunction marcarMensajeLeido(){\n\t\t\n\t\tinclude_once (\"../logica/logicaUsuario.php\");\n\t\t\n\t\t$idMensaje = $_POST['idMensaje'];\n\t\t$logica = new logicaUsuario;\n\t\t$logica->marcarMensajeLeido($idMensaje);\n\t\techo \"true\";\n\t}\n\t\n\t\n\tfunction contarMensajesNoLeidos(){\n\t\t\n\t\tinclude_once (\"../logica/logicaUsuario.php\");\n\t\t\n\t\t$idUsuario = $_POST['cedula'];\n\t\t$logica = new logicaUsuario;\n\t\t$cantidadMensajes = $logica->contarMensajesNuevos($idUsuario);\n\t\techo $cantidadMensajes;\n\t}\n\t\n\tfunction ExisteUsuario(){\n\t\t\n\t\tinclude_once (\"../logica/logicaUsuario.php\");\n\t\t\n\t\t$usuario = $_POST['usuario'];\n\t\t$clave = $_POST['clave'];\n\t\t$logica = new logicaUsuario;\n\t\t$datos = $logica->ObtenerDatosUsuario($usuario,$clave);\n\t\t$datos = ctrUsuarios::Convertir_UTF8($datos);\n\t\techo \"\".json_encode($datos).\"\";\n\t}\n\t\n\tfunction Convertir_UTF8($array){\n\t\tforeach ($array as $key => $value) {\n\t\t\t$array[$key] = utf8_encode($value);\n\t\t}\n\t\treturn $array;\n\t}\n}\n\n\n$op = $_POST['opcion'];\n$control = new ctrUsuarios;\n\nif($op == 1){\n\t$control->insertarUsuarios();\n}\nelse if($op == 2){\t\n\t$control->actualizarUsuarios();\n}\nelse if($op == 3){\t\n\t$control->eliminarUsuarios();\n}\nelse if($op == 4){\t\n\t$control->contarMensajesNoLeidos();\n}\nelse if($op == 5){\t\n\t$control->marcarMensajeLeido();\n}\nelse if($op == 6){\t\n\t$control->ExisteUsuario();\n}\n?>"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":53,"cells":{"blob_id":{"kind":"string","value":"970098632fbc6a98a0737868a77674a717fe5547"},"language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"fdask/nottingham"},"path":{"kind":"string","value":"/src/Player.class.php"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4372,"string":"4,372"},"score":{"kind":"number","value":3.40625,"string":"3.40625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"cardHand = new Deck();\n\t\t$this->cardHand->setName(\"Hand\");\n\t\t$this->cardHand->setState(Card::STATE_FACEDOWN);\n\n\t\t$this->cardPublicStand = new Deck();\n\t\t$this->cardPublicStand->setName(\"Market stand\");\n\t\t$this->cardPublicStand->setState(Card::STATE_FACEUP);\n\n\t\t$this->cardHiddenStand = new Deck();\n\t\t$this->cardHiddenStand->setName(\"Contraband Stash\");\n\t\t$this->cardHiddenStand->setState(Card::STATE_FACEDOWN);\n\n\t\t$this->cardAux = new Deck();\n\t\t$this->cardAux->setName(\"Aux Deck\");\n\t\t$this->cardAux->setState(Card::STATE_FACEDOWN);\n\t}\n\n\t/**\n\t* returns a string representation of the player\n\t*\n\t* @return string\n\t**/\n\tpublic function __toString() {\n\t\t$ret = $this->getName() . \" [\" . $this->getGold() . \"]\";\n\n\t\tif ($this->getDoneTurn()) {\n\t\t\t$ret .= \" - DONE\";\n\t\t}\n\n\t\t$ret .= \"\\n\";\n\t\n\t\t$ret .= $this->getCardHand() . \"\\n\";\n\t\t$ret .= $this->getCardPublicStand() . \"\\n\";\n\t\t$ret .= $this->getCardHiddenStand() . \"\\n\";\n\n\t\tif (count($this->getCardAux()) > 0) {\n\t\t\t$ret .= $this->getCardAux() . \"\\n\";\n\t\t}\n\n\t\treturn $ret;\n\t}\n\n\t/**\n\t* sets the name property\n\t*\n\t* @param string $name\n\t**/\n\tpublic function setName($name) {\n\t\t$this->name = $name;\n\t}\n\n\t/**\n\t* returns the name property\n\t*\n\t* @return string\n\t**/\n\tpublic function getName() {\n\t\treturn $this->name;\n\t}\n\n\t/**\n\t* sets the gold property\n\t*\n\t* @param integer $gold\n\t**/\n\tpublic function setGold($gold) {\n\t\t$this->gold = $gold;\n\t}\n\n\t/**\n\t* adds an amount to the gold property\n\t*\n\t* @param integer $amount\n\t* @return integer the new gold count\n\t**/\n\tpublic function addGold($amount) {\n\t\t$this->gold += $amount;\n\n\t\treturn $this->gold;\n\t}\n\n\t/**\n\t* removes an amount from the gold property\n\t*\n\t* @param integer $amount\n\t* @return integer the new gold\n\t**/\n\tpublic function removeGold($amount) {\n\t\t// don't let the level fall below 1!\n\t\t$this->gold = (($this->gold - $amount) >= 0) ? ($this->gold - $amount) : 0;\n\n\t\treturn $this->gold;\n\t}\n\n\t/**\n\t* returns the gold property\n\t*\n\t* @return integer\n\t**/\n\tpublic function getGold() {\n\t\treturn $this->gold;\n\t}\n\n\t/**\n\t* sets the cardHand property\n\t*\n\t* @param Deck $deck\n\t**/\n\tpublic function setCardHand(Deck $deck) {\n\t\t$this->cardHand = $deck;\n\t}\n\n\t/**\n\t* gets the cardHand property\n\t*\n\t* @return Deck\n\t**/\n\tpublic function getCardHand() {\n\t\treturn $this->cardHand;\n\t}\n\n\t/**\n\t* sets the cardPublicStand property\n\t*\n\t* @param Deck $deck\n\t**/\n\tpublic function setCardPublicStand(Deck $deck) {\n\t\t$this->cardPublicStand = $deck;\n\t}\n\n\t/**\n\t* gets the cardPublicStand property\n\t*\n\t* @return Deck\n\t**/\n\tpublic function getCardPublicStand() {\n\t\treturn $this->cardPublicStand;\n\t}\n\n\t/**\n\t* sets the cardHiddenStand property\n\t*\n\t* @param Deck $deck\n\t**/\n\tpublic function setCardHiddenStand(Deck $deck) {\n\t\t$this->cardHiddenStand = $deck;\n\t}\n\n\t/**\n\t* gets the cardHiddenStand property\n\t*\n\t* @return Deck\n\t**/\n\tpublic function getCardHiddenStand() {\n\t\treturn $this->cardHiddenStand;\n\t}\n\n\t/**\n\t* sets the cardAux property\n\t*\n\t* @param Deck $deck\n\t**/\n\tpublic function setCardAux(Deck $deck) {\n\t\t$this->cardAux = $deck;\n\t}\n\n\t/**\n\t* gets the cardAux property\n\t*\n\t* @return Deck\n\t**/\n\tpublic function getCardAux() {\n\t\treturn $this->cardAux;\n\t}\n\n\t/**\n\t* sets the doneTurn property\n\t* \n\t* @param boolean $bool\n\t**/\n\tpublic function setDoneTurn($bool) {\n\t\t$this->doneTurn = $bool;\n\t}\n\n\t/**\n\t* gets the doneTurn property\n\t*\n\t* @return boolean\n\t**/\n\tpublic function getDoneTurn() {\n\t\treturn $this->doneTurn;\t\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":true},"paginationData":{"pageIndex":0,"numItemsPerPage":100,"numTotalItems":9914478,"offset":0,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjExOTQ1MSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9waHAiLCJleHAiOjE3NTYxMjMwNTEsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.MeJYciJ4IzsdKcX9ySFhutTOtv0A1Io1c_j7w8B6GpjrYtKz_ZhGXXPx_tbjw0oNVXWlWFRJH7J4unr1bo35AA","displayUrls":true},"dataset":"hongliu9903/stack_edu_php","isGated":false,"isPrivate":false,"hasParquetFormat":true,"author":{"_id":"648ba0d68e7f7a927675d4a3","avatarUrl":"/avatars/d82ced93656e03d60c8b55010694f908.svg","fullname":"Hong Liu","name":"hongliu9903","type":"user","isPro":false,"isHf":false,"isHfAdmin":false,"isMod":false,"followerCount":6},"compact":true}">
Dataset Viewer
Auto-converted to Parquet
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
e23749a6ec2558f2694d851ab8a82ea55d81ee8c
PHP
ulisescruzescamilla/finicity-sdk
/src/Models/ReportSummary.php
UTF-8
4,071
2.84375
3
[ "MIT" ]
permissive
<?php namespace FinicityAPILib\Models; use JsonSerializable; /** * @todo Write general description for this model */ class ReportSummary implements JsonSerializable { /** * The Finicity report ID * @required * @var string $id public property */ public $id; /** * Finicity ID for the consumer * @required * @var string $consumerId public property */ public $consumerId; /** * Last 4 digits of the report consumer's Social Security number * @required * @var string $consumerSsn public property */ public $consumerSsn; /** * Name of Finicity partner requesting the report * @required * @var string $requesterName public property */ public $requesterName; /** * The unique requestId for this specific call request * @required * @var string $requestId public property */ public $requestId; /** * @todo Write general description for this property * @required * @var \FinicityAPILib\Models\ReportConstraints $constraints public property */ public $constraints; /** * Report type * @required * @var string $type public property */ public $type; /** * inProgress, success, or failure * @required * @var string $status public property */ public $status; /** * The date the report was generated * @required * @var integer $createdDate public property */ public $createdDate; /** * All additional properties for this model * @var array $additionalProperties public property */ public $additionalProperties = array(); /** * Constructor to set initial or default values of member properties * @param string $id Initialization value for $this->id * @param string $consumerId Initialization value for $this->consumerId * @param string $consumerSsn Initialization value for $this->consumerSsn * @param string $requesterName Initialization value for $this->requesterName * @param string $requestId Initialization value for $this->requestId * @param ReportConstraints $constraints Initialization value for $this->constraints * @param string $type Initialization value for $this->type * @param string $status Initialization value for $this->status * @param integer $createdDate Initialization value for $this->createdDate */ public function __construct() { if (9 == func_num_args()) { $this->id = func_get_arg(0); $this->consumerId = func_get_arg(1); $this->consumerSsn = func_get_arg(2); $this->requesterName = func_get_arg(3); $this->requestId = func_get_arg(4); $this->constraints = func_get_arg(5); $this->type = func_get_arg(6); $this->status = func_get_arg(7); $this->createdDate = func_get_arg(8); } } /** * Add an additional property to this model. * @param string $name Name of property * @param mixed $value Value of property */ public function addAdditionalProperty($name, $value) { $this->additionalProperties[$name] = $value; } /** * Encode this object to JSON */ public function jsonSerialize() { $json = array(); $json['id'] = $this->id; $json['consumerId'] = $this->consumerId; $json['consumerSsn'] = $this->consumerSsn; $json['requesterName'] = $this->requesterName; $json['requestId'] = $this->requestId; $json['constraints'] = $this->constraints; $json['type'] = $this->type; $json['status'] = $this->status; $json['createdDate'] = $this->createdDate; return array_merge($json, $this->additionalProperties); } }
true
7071313c1a3cbecf79354e25904f0eb97bcf4356
PHP
alexismolineau/OpenClassrooms
/PHP/POO/TP_2/index.php
UTF-8
4,423
3.1875
3
[]
no_license
<?php //------------------------------ // Charchement des Classes //------------------------------ function loadClass($class){ require $class . '.php'; } spl_autoload_register('loadClass'); //------------------------------ // Session Gestion //------------------------------ session_start(); if (isset($_GET['logOut'])){ session_destroy(); header('Location: .'); exit(); } //------------------------------ // Instance CharacterManager //------------------------------ $db = new PDO('mysql:host=localhost:8889; dbname=tp_cours', 'root', 'root'); // On émet une alerte à chaque fois qu'une requête a échoué. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $manager = new CharacterManager($db); //------------------------------ // Session existante //------------------------------ if (isset($_SESSION['person'])){ $person = $_SESSION['person']; } //------------------------------ // Créer $person //------------------------------ if (isset($_POST['name']) && isset($_POST['create'])){ $name = htmlspecialchars($_POST['name']); $create = htmlspecialchars($_POST['create']); $person = new Character(['name' => $name]); if (!$person->nameAvaible()){ echo 'Le nom n\'est pas valable'; unset($person); } elseif ($manager->exists($person->getName())) { echo 'Le pseudo existe déjà'; unset($person); } else { $manager->create($person); } } //------------------------------ // Utiliser $person //------------------------------ elseif (isset($_POST['name']) && isset($_POST['use'])){ $name = htmlspecialchars($_POST['name']); $create = htmlspecialchars($_POST['use']); if ($manager->exists($name)){ $person = $manager->read($name); } else { echo 'Le personnage n\'existe pas'; } } // Si on a cliqué sur un personnage pour le frapper. elseif (isset($_GET['hit'])) { if (!isset($person)){ $message = 'Merci de créer un personnage ou de vous identifier.'; } else { if (!$manager->exists((int) $_GET['hit'])){ $message = 'Le personnage que vous voulez frapper n\'existe pas !'; } else { $personToHit = $manager->read((int) $_GET['hit']); // On stocke dans $retour les éventuelles erreurs ou messages que renvoie la méthode frapper. $return = $person->hit($personToHit); switch ($return){ case Character::ITS_ME : $message = 'Mais... pourquoi voulez-vous vous frapper ???'; break; case Character::CHARACTER_HIT : $message = 'Le personnage a bien été frappé !'; $manager->update($person); $manager->update($personToHit); break; case Character::CHARACTER_KILL : $message = 'Vous avez tué ce personnage !'; $manager->update($person); $manager->delete($personToHit); break; } } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Warcraft beta 0.1</title> </head> <body> <p>Nombre de personnages créés: <?php echo $manager->count() ?> </p> <?php // On a un message à afficher ? if (isset($message)){ echo '<p>' . $message . '</p>'; } // Si on utilise un personnage (nouveau ou pas). if (isset($person)){ ?> <p><a href="?logOut=1">Déconnexion</a></p> <fieldset> <legend>Mes informations</legend> <p> Nom : <?php echo htmlspecialchars($person->getName()) ?><br /> Dégâts : <?php echo $person->getDamages() ?> </p> </fieldset> <fieldset> <legend>Qui frapper ?</legend> <p> <?php // Affiche la liste des personnages $persons = $manager->readAll($person->getName()); if (empty($persons)){ echo 'Personne à frapper !'; } else { foreach ($persons as $onePerson){ echo '<a href="?hit=' . $onePerson->getId() . '">' . htmlspecialchars($onePerson->getName()) . '</a> (dégâts : ' . $onePerson->getDamages() . '<br />'; } } ?> </p> </fieldset> <?php } else{ ?> <form action="" method="post"> <label for="name">Nom du personnage: </label> <input id="name" type="text" name="name"> <input type="submit" name="use" value="Utiliser ce personnage"> <br> <label for="type">Classe du personnage: </label> <select name="type"> <option value="Warrior">Guerrier</option> <option value="Wizard">Mage</option> </select> <input type="submit" name="create" value="Créer ce personnage"> </form> <?php } ?> </body> </html> <?php if (isset($person)){ $_SESSION['person'] = $person; } ?>
true
e47b73fe4b910d3beaab00a746cb3a94340bd147
PHP
jhonharoldpizarro2021/agricolaApp
/querys/q_informe_costos.php
UTF-8
3,328
2.515625
3
[]
no_license
<?php session_start(); ob_start(); $retorno = array(); if( $_POST ){ include "../functions.php"; $con = start_connect(); if( $con ){ switch ( $_POST["opcion"]){ case 1: //Consultar todos $query = " SELECT * FROM qryInformeCostos WHERE id_finca=".$_POST["finca"]." "; $resultado = mysqli_query($con, $query); $informe = array(); $suertes = array(); $colores = array(); while( $row = mysqli_fetch_array( $resultado ) ){ $informe[] = array( "suerte" => $row["id_unidad_agricola"], "tc" => $row["tipo_costo"], "valor" => $row["valor"], ); if ( !in_array( $row["id_unidad_agricola"],$suertes ) ){ $suertes[] = $row["id_unidad_agricola"]; $nSuerte[] = $row["nombre_unidad_agricola"]; $finca[] = $row["id_finca"]; $nFinca[] = $row["nombre_finca"]; } } $informeSuertes = array(); for ($i=0; $i < count($suertes); $i++){ $queryTmp = "SELECT * FROM qryInformeCostos WHERE id_unidad_agricola='".$suertes[$i]."'"; $resultadoTmp = mysqli_query($con, $queryTmp); $informeTmp = array(); while( $rowTmp = mysqli_fetch_array( $resultadoTmp ) ){ $informeTmp[] = array( "tc" => $rowTmp["tipo_costo"], "valor" => $rowTmp["valor"], ); if ( !array_key_exists( $rowTmp["tipo_costo"],$colores ) ){ $queryColor = " SELECT valor FROM parametros_generales WHERE nombre='".$rowTmp["tipo_costo"]."' AND tipo='color' "; $resultadoColor = mysqli_query($con, $queryColor); if ($rowColor = mysqli_fetch_array($resultadoColor )){ $colores[$rowTmp["tipo_costo"]] = $rowColor["valor"]; } } } $informeSuertes[]=array( "idFinca" => $finca[$i], "nFinca" => $nFinca[$i], "idSuerte" => $suertes[$i], "nSuerte" => $nSuerte[$i], "informes" => $informeTmp, "query" => $queryTmp, ); } //retorno if( count($informe) > 0) { $retorno["estado"] = "OK"; $retorno["informe"] = $informe; $retorno["informeSuertes"] = $informeSuertes; $retorno["colores"] = $colores; } else { $retorno["estado"] = "EMPTY"; } break; } if( !close_bd($con) ) { $retorno["msg"] = "Error al cerrar la conexión a la BDD"; } } else { $retorno["estado"] = "ERROR"; $retorno["msg"] = "Error de conexión a la BDD:". mysqli_connect_error(); } } else { $retorno["estado"] = "ERROR"; $retorno["msg"] = "Parámetros no encontrados"; } header('Content-Type: application/json; charset=utf-8'); echo json_encode( $retorno ); ?>
true
ae81f87dfe291586fe18e2cb1ef8530080064749
PHP
RenLiZhou/laravel_admin
/app/Http/Controllers/Controller.php
UTF-8
982
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller as BaseController; use Illuminate\Support\Facades\Validator; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; /** * 验证表单规则 * @param array $params * @param $rules * @param $messages * @return string|null * */ protected function validateParams(array $params, array $rules, array $messages) { $validator = Validator::make($params, $rules, $messages); if ($validator->fails()) { $bags = $validator->getMessageBag()->toArray(); foreach ($bags as $bag) { foreach ($bag as $item) { return $item; } } } return null; } }
true
f8b576e114554e94365232a843ca549b298cc800
PHP
netgen-layouts/layouts-contentful
/lib/Routing/EntrySluggerInterface.php
UTF-8
305
2.5625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Netgen\Layouts\Contentful\Routing; use Netgen\Layouts\Contentful\Entity\ContentfulEntry; interface EntrySluggerInterface { /** * Returns the slug for the provided entry. */ public function getSlug(ContentfulEntry $contentfulEntry): string; }
true
b0d7c95069f8126848257dbca6f08b9480baf463
PHP
hemanthcmbadoor/laravellogin
/app/Http/Controllers/RegisterController.php
UTF-8
2,253
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Models\Member; use Illuminate\Http\Request; class RegisterController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('layouts.register'); //return "hai"; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return "create"; } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //return "hai"; //return $request->all(); $this->validate($request, [ 'name'=>'required', 'phone'=>'required|max:10|unique:member', 'password' => 'min:6|same:password2', ], [ 'password.same' => 'Password Not Matching', ]); //$input = $request->all(); //$input['password'] = Hash::make($request->password); Member::create($request->all());//strore to database return redirect('/'); } /** * Display the specified resource. * * @param \App\Models\Register $register * @return \Illuminate\Http\Response */ public function show(Register $register) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Register $register * @return \Illuminate\Http\Response */ public function edit(Register $register) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Register $register * @return \Illuminate\Http\Response */ public function update(Request $request, Register $register) { // } /** * Remove the specified resource from storage. * * @param \App\Models\Register $register * @return \Illuminate\Http\Response */ public function destroy(Register $register) { // } }
true
42e089ec4638894bed82e40ad2bbde973a0fadab
PHP
Edwin-En/Accedo
/3. API con PHP/PokemonAPI/login.php
UTF-8
1,504
2.921875
3
[]
no_license
<?php // Inicio de sesion, requiere una cuenta ya registrada en la base de datos // Se ingresa con email y contraseña session_start(); if (isset($_SESSION['user_id'])) { header('Location: /PokemonAPI/listapokemones.html'); } require 'database.php'; if (!empty($_POST['email']) && !empty($_POST['password'])) { $records = $coneccion->prepare('SELECT id, email, password FROM usuarios WHERE email=:email'); $records->bindParam(':email', $_POST['email']); $records->execute(); $results = $records->fetch(PDO::FETCH_ASSOC); $message = ''; if (count($results) > 0 && password_verify($_POST['password'], $results['password'])) { $_SESSION['user_id'] = $results['id']; header('Location: /PokemonAPI/index.php'); } else { $message = "Las contraseñas no coinciden"; } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> Inicio de sesion </title> <link rel="stylesheet" href="assets/css/style.css"> </head> <body> <?php require 'partials/header.php' ?> <h2> Inicia sesion </h2> <span> o <a href="signup.php">Registrate</a> </span> <?php if (!empty($message)) : ?> <p><?= $message ?> <?php endif; ?> <form action="login.php" method="post"> <input type="text" name="email" placeholder="Ingresa tu correo"> <input type="password" name="password" placeholder="Ingresa tu contraseña"> <input type="submit" value="Enviar"> </form> </body> </html>
true
4d2dfaa51b0edabb9fecb4217f28af34635c2a55
PHP
eskguptha/php
/read_csv.php
UTF-8
824
2.921875
3
[]
no_license
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>Read data from csv using php</h1> <table class="table table-striped table-hover journal_table"> <thead> <th>SKU</th> <th>Name</th> <th>Category</th> <th>Price</th> <th>Qty</th> </thead> <tbody> <?php $file = "products.csv"; $handle = fopen($file, "r"); $j = 0; while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $j++; ?> <tr> <td><?php echo $data['0']; ?></td> <td><?php echo $data['1']; ?></td> <td><?php echo $data['2']; ?></td> <td><?php echo $data['3']; ?></td> <td><?php echo $data['4']; ?></td> </tr> <?php }?> </tbody> </table> </body> </html>
true
19ddef5195ac36e49aef493cb42e45529ac43e66
PHP
zikezhang/LaravelAdmin
/src/Verecom/Admin/User/Form/PasswordForm.php
UTF-8
2,222
2.8125
3
[ "MIT" ]
permissive
<?php namespace Verecom\Admin\User\Form; use Event; use Verecom\Admin\User\Repo\AdminUserInterface; use Verecom\Admin\Services\Validation\ValidableInterface; use Verecom\Admin\User\Repo\UserNotFoundException; use Verecom\Admin\User\UserMailerInterface; class PasswordForm implements PasswordFormInterface { /** * @var \Verecom\Admin\User\Repo\AdminUserInterface */ protected $users; /** * @var ValidableInterface */ protected $validator; /** * @var \Verecom\Admin\User\UserMailerInterface */ protected $mailer; /** * @param ValidableInterface $validator * @param AdminUserInterface $users * @param \Verecom\Admin\User\UserMailerInterface $mailer */ public function __construct( ValidableInterface $validator, AdminUserInterface $users, UserMailerInterface $mailer ) { $this->users = $users; $this->validator = $validator; $this->mailer = $mailer; } /** * * * @author ZZK * @link http://verecom.com * * @param $email * * @return void */ public function forgot($email) { $user = $this->users->findByLogin($email); $this->mailer->sendReset($user); Event::fire('users.password.forgot', array($user)); } /** * Reset a given user password * * @author ZZK * @link http://verecom.com * * @param array $creds * * @return bool */ public function reset(array $creds) { try { if ($this->validator->with($creds)->passes()) { $this->users->resetPassword($creds['code'],$creds['password']); return true; } } catch (UserNotFoundException $e) { $this->validator->add('UserNotFoundException',$e->getMessage()); } return false; } /** * Get the validation errors * * @author ZZK * @link http://verecom.com * * @return array */ public function getErrors() { return $this->validator->errors(); } }
true
28f42776206c068a3fb1a5e3479eca82fefbbf6c
PHP
aheadWorks/module-langshop
/Api/Data/TranslatableResource/PaginationInterface.php
UTF-8
1,107
2.71875
3
[]
no_license
<?php namespace Aheadworks\Langshop\Api\Data\TranslatableResource; interface PaginationInterface { /** * Set page * * @param int $page * @return $this */ public function setPage(int $page); /** * Get page * * @return int|null */ public function getPage(): ?int; /** * Set page size * * @param int $pageSize * @return $this */ public function setPageSize(int $pageSize); /** * Get page size * * @return int|null */ public function getPageSize(): ?int; /** * Set total pages * * @param int $totalPages * @return $this */ public function setTotalPages(int $totalPages); /** * Get total pages * * @return int|null */ public function getTotalPages(): ?int; /** * Set total items * * @param int $totalItems * @return $this */ public function setTotalItems(int $totalItems); /** * Get total items * * @return int|null */ public function getTotalItems(): ?int; }
true
353404a5c1f02f03e98f03719301826d3078e4db
PHP
nyachomofred/SAICA_GROUP_WELFARE_MANAGEMENT_SYSTEM
/app/Paymenthistory.php
UTF-8
1,142
2.578125
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Paymenthistory extends Model { // protected $fillable=[ 'student_id', 'amount_paid', 'payment_mode', 'reference_no', 'date_paid', 'receipt_no' ]; public function setStudentIdAttribute($value) { $this->attributes['student_id']=ucwords($value); } public function setAmountPaidAttribute($value) { $this->attributes['amount_paid']=ucwords($value); } public function setPaymentModeAttribute($value) { $this->attributes['payment_mode']=ucwords($value); } public function setReferenceNoAttribute($value) { $this->attributes['reference_no']=strtoupper($value); } public function setReceiptNoAttribute($value) { $this->attributes['receipt_no']=strtoupper($value); } public function setDatePaiddAttribute($value) { $this->attributes['date_paid']=ucwords($value); } public function student() { return $this->belongsTo('App\Model\Student'); } }
true
e363598aa8ad134e038d964173d661c38573641d
PHP
moahmedmish/code_repository
/app/Http/Controllers/RepositoryController.php
UTF-8
1,377
2.65625
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Http\Requests\FilterDataRequest; use App\Services\RepositoryIntegrationServices; use Illuminate\Http\Request; use Illuminate\Http\Response; class RepositoryController extends Controller { /* * @var OBJECT repositoryIntegrationServices * */ private $repositoryIntegrationServices; /** * INJECT SEARCH Repository Code SERVICES TO ACCESS THOSE SERVICES. * * HotelsController constructor. * * @param RepositoryIntegrationServices $hotelIntegrationServices */ public function __construct(RepositoryIntegrationServices $repositoryIntegrationServices) { $this->repositoryIntegrationServices = $repositoryIntegrationServices; } /** * GET DATA FROM Code Repository. * * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function get(FilterDataRequest $request,$code_repository) { $finalResults = $this->repositoryIntegrationServices->filterData($request->all(),$code_repository); if (! $finalResults && count($finalResults)) { return $this->_ReturnJsonResponse('Failed Operation : Something Went Wrong ...!', [], [], Response::HTTP_BAD_REQUEST); } return $this->_ReturnJsonResponse('Successfully Operation.', [], $finalResults, Response::HTTP_OK); } }
true
955f0a07895735b60f4327c756169bc827da9f9d
PHP
koftikes/symfony-adminlte-bundle
/src/Model/NotificationInterface.php
UTF-8
736
2.765625
3
[ "MIT" ]
permissive
<?php namespace SbS\AdminLTEBundle\Model; /** * Interface NotificationInterface. */ interface NotificationInterface { /** * Types of notice. */ const TYPE_SUCCESS = 'success'; const TYPE_INFO = 'info'; const TYPE_WARNING = 'warning'; const TYPE_DANGER = 'danger'; /** * Should return Notice identifier. * * @return int */ public function getId(); /** * Should return Notice Message. * * @return string */ public function getMessage(); /** * Should return Notice Icon. * Example: "fa fa-check-circle text-red' * See: http://fontawesome.io/icons/. * * @return string */ public function getIcon(); }
true
d1e83656b94591d78e33d940af98b649c65c3f1a
PHP
junaidzx90/subs-activations
/inc/activated_users_table.php
UTF-8
10,472
2.671875
3
[]
no_license
<?php class Activated_Users extends WP_List_Table { /** * Prepare the items for the table to process * * @return Void */ public function prepare_items(){ $columns = $this->get_columns(); $hidden = $this->get_hidden_columns(); $sortable = $this->get_sortable_columns(); $action = $this->current_action(); $data = $this->table_data(); usort( $data, array( &$this, 'sort_data' ) ); $perPage = 10; $currentPage = $this->get_pagenum(); $totalItems = count($data); $this->set_pagination_args( array( 'total_items' => $totalItems, 'per_page' => $perPage ) ); $data = array_slice($data,(($currentPage-1)*$perPage),$perPage); $this->_column_headers = array($columns, $hidden, $sortable); $search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : false; if(!empty($search)){ global $wpdb; try { $search = sanitize_text_field( $search ); $data = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}lic_activations WHERE UserName LIKE '%$search%'", ARRAY_A); if(!is_wp_error( $wpdb )){ $this->items = $data; } } catch (\Throwable $th) { //throw $th; } }else{ $this->items = $data; } } /** * Override the parent columns method. Defines the columns to use in your listing table * * @return Array */ public function get_columns(){ $columns = array( 'cb' => '<input type="checkbox" />', 'ID' => 'ID', 'Orderno' => 'Order No', 'Mtid' => 'Mtid', 'Userid' => 'User ID', 'UserName' => 'User Name', 'Prodcode' => 'Product Code', 'Status' => 'Status', 'Comment' => 'Comment', 'Editable' => 'Editable', 'Expirytime' => 'Expirytime', 'Modifydate' => 'Modifydate' ); return $columns; } /** * Define which columns are hidden * * @return Array */ public function get_hidden_columns() { return array(); } /** * Define the sortable columns * * @return Array */ public function get_sortable_columns() { return array( 'ID' => array('ID', true), 'Orderno' => array('Orderno', true), 'Mtid' => array('Mtid', true), 'Userid' => array('Userid', true), 'UserName' => array('UserName', true) ); } /** * Get the table data * * @return Array */ private function table_data(){ $data = array(); global $wpdb; $data = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}lic_activations ORDER BY ID ASC", ARRAY_A); return $data; } /** * Define what data to show on each column of the table * * @param Array $item Data * @param String $column_name - Current column name * * @return Mixed */ public function column_default( $item, $column_name ){ switch( $column_name ) { case 'ID': case 'Orderno': case 'Mtid': case 'Userid': case 'UserName': case 'Prodcode': case 'Status': case 'Comment': case 'Editable': case 'Expirytime': case 'Modifydate': return $item[ $column_name ]; default: return print_r( $item, true ) ; } } function get_bulk_actions() { $actions = array( 'products_disable' => 'Disable Lifetime License', 'subscription_disable' => 'Disable Subscription License', 'enable_products_' => 'Enable Lifetime License', 'enable_subscription_' => 'Enable Subscription License' ); return $actions; } function column_cb($item) { return sprintf( '<input type="checkbox" name="orders[]" value="%s" />', $item['Orderno'] ); } // All form actions function current_action(){ global $wpdb; if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'products_disable'){ if(isset($_REQUEST['orders']) && !empty($_REQUEST['orders'])){ $orders_data = $_REQUEST['orders']; if(is_array($orders_data)){ foreach($orders_data as $data){ $order_id = $data; $order = wc_get_order( $order_id ); if($order !== false){ $items = $order->get_items(); foreach ( $items as $item ) { $product_id = $item->get_product_id(); if(WC_Product_Factory::get_product_type($product_id) !== 'subscription'){ $wpdb->update($wpdb->prefix.'lic_activations', array( 'Editable' => 0 ),array( 'Orderno' => $order_id ),array('%d'),array('%d')); } } } } } }else{ print_r("No order selected."); } } if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'subscription_disable'){ if(isset($_REQUEST['orders']) && !empty($_REQUEST['orders'])){ $orders_data = $_REQUEST['orders']; if(is_array($orders_data)){ foreach($orders_data as $data){ $order_id = $data; $order = wc_get_order( $order_id ); if($order !== false){ $items = $order->get_items(); foreach ( $items as $item ) { $product_id = $item->get_product_id(); if(WC_Product_Factory::get_product_type($product_id) === 'subscription'){ $wpdb->update($wpdb->prefix.'lic_activations', array( 'Editable' => 0 ),array( 'Orderno' => $order_id ),array('%d'),array('%d')); } } } } } }else{ print_r("No orders selected."); } } if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'enable_products_'){ if(isset($_REQUEST['orders']) && !empty($_REQUEST['orders'])){ $orders_data = $_REQUEST['orders']; if(is_array($orders_data)){ foreach($orders_data as $data){ $order_id = $data; $order = wc_get_order( $order_id ); if($order !== false){ $items = $order->get_items(); foreach ( $items as $item ) { $product_id = $item->get_product_id(); if(WC_Product_Factory::get_product_type($product_id) !== 'subscription'){ $wpdb->update($wpdb->prefix.'lic_activations', array( 'Editable' => 1 ),array( 'Orderno' => $order_id ),array('%d'),array('%d')); } } } } } }else{ print_r("No orders selected."); } } if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'enable_subscription_'){ if(isset($_REQUEST['orders']) && !empty($_REQUEST['orders'])){ $orders_data = $_REQUEST['orders']; if(is_array($orders_data)){ foreach($orders_data as $data){ $order_id = $data; $order = wc_get_order( $order_id ); if($order !== false){ $items = $order->get_items(); foreach ( $items as $item ) { $product_id = $item->get_product_id(); if(WC_Product_Factory::get_product_type($product_id) === 'subscription'){ $wpdb->update($wpdb->prefix.'lic_activations', array( 'Editable' => 1 ),array( 'Orderno' => $order_id ),array('%d'),array('%d')); } } } } } }else{ print_r("No order selected."); } } } /** * Allows you to sort the data by the variables set in the $_GET * * @return Mixed */ private function sort_data( $a, $b ) { // Set defaults $orderby = 'ID'; $order = 'asc'; // If orderby is set, use this as the sort column if(!empty($_GET['orderby'])) { $orderby = $_GET['orderby']; } // If order is set use this as the order if(!empty($_GET['order'])) { $order = $_GET['order']; } $result = strcmp( $a[$orderby], $b[$orderby] ); if($order === 'asc') { return $result; } return -$result; } } //class
true
a010d320967cb31a4cd28b20f2eb45c8b8a536e5
PHP
xiebruce/PicUploader
/vendor/cloudinary/cloudinary_php/tests/TagTest.php
UTF-8
45,334
2.546875
3
[ "MIT" ]
permissive
<?php namespace Cloudinary\Test; use Cloudinary; use Cloudinary\Cache\Adapter\KeyValueCacheAdapter; use Cloudinary\Cache\ResponsiveBreakpointsCache; use Cloudinary\Curl; use Cloudinary\Test\Cache\Storage\DummyCacheStorage; use DOMDocument; use PHPUnit\Framework\TestCase; /** * Class TagTest */ class TagTest extends TestCase { const DEFAULT_PATH = 'http://res.cloudinary.com/test123'; const DEFAULT_UPLOAD_PATH = 'http://res.cloudinary.com/test123/image/upload/'; const VIDEO_UPLOAD_PATH = 'http://res.cloudinary.com/test123/video/upload/'; private static $public_id = 'sample.jpg'; private static $common_transformation_str = 'e_sepia'; private static $min_width = 100; private static $max_width = 399; private static $max_images; private static $custom_attributes = array('custom_attr1' => 'custom_value1', 'custom_attr2' => 'custom_value2'); private static $common_image_options = array( 'effect' => 'sepia', 'cloud_name' => 'test123', 'client_hints' => false, ); private static $fill_transformation; private static $fill_trans_str; private static $common_srcset; private static $breakpoints_arr; private static $sizes_attr; public static function setUpBeforeClass() { self::$breakpoints_arr = array(self::$min_width, 200, 300, self::$max_width); self::$max_images = count(self::$breakpoints_arr); self::$common_srcset = array('breakpoints' => self::$breakpoints_arr); self::$fill_transformation = ['width' => self::$max_width, 'height' => self::$max_width, 'crop' => 'fill']; self::$fill_trans_str = "c_fill,h_" . self::$max_width . ",w_" . self::$max_width; self::$sizes_attr = implode( ', ', array_map( function ($w) { return "(max-width: ${w}px) ${w}px"; }, self::$breakpoints_arr ) ); Curl::$instance = new Curl(); } protected function setUp() { Cloudinary::reset_config(); Cloudinary::config( array( "cloud_name" => "test123", "api_key" => "a", "api_secret" => "b", "secure_distribution" => null, "private_cdn" => false, "cname" => null ) ); } public function test_cl_image_tag() { $tag = cl_image_tag("test", array("width" => 10, "height" => 10, "crop" => "fill", "format" => "png")); $this->assertEquals( "<img src='" . self::DEFAULT_UPLOAD_PATH . "c_fill,h_10,w_10/test.png' height='10' width='10'/>", $tag ); } /** * Should create a meta tag with client hints */ public function test_cl_client_hints_meta_tag() { $doc = new DOMDocument(); $doc->loadHTML(cl_client_hints_meta_tag()); $tags = $doc->getElementsByTagName('meta'); $this->assertEquals($tags->length, 1); $this->assertEquals($tags->item(0)->getAttribute('content'), 'DPR, Viewport-Width, Width'); $this->assertEquals($tags->item(0)->getAttribute('http-equiv'), 'Accept-CH'); } /** * Check that cl_image_tag encodes special characters. */ public function test_cl_image_tag_special_characters_encoding() { $tag = cl_image_tag( "test's special < \"characters\" >", array("width" => 10, "height" => 10, "crop" => "fill", "format" => "png", "alt" => "< test's > special \"") ); $expected = "<img src='" . self::DEFAULT_UPLOAD_PATH . "c_fill,h_10,w_10/" . "test%27s%20special%20%3C%20%22characters%22%20%3E.png'" . " alt='&lt; test&#039;s &gt; special &quot;' height='10' width='10'/>"; $this->assertEquals($expected, $tag); } public function test_responsive_width() { // should add responsive width transformation $tag = cl_image_tag("hello", array("responsive_width" => true, "format" => "png")); $this->assertEquals( "<img class='cld-responsive' data-src='" . self::DEFAULT_UPLOAD_PATH . "c_limit,w_auto/hello.png'/>", $tag ); $options = array("width" => 100, "height" => 100, "crop" => "crop", "responsive_width" => true); $result = Cloudinary::cloudinary_url("test", $options); $this->assertEquals($options, array("responsive" => true)); $this->assertEquals($result, TagTest::DEFAULT_UPLOAD_PATH . "c_crop,h_100,w_100/c_limit,w_auto/test"); Cloudinary::config( array( "responsive_width_transformation" => array( "width" => "auto:breakpoints", "crop" => "pad", ), ) ); $options = array("width" => 100, "height" => 100, "crop" => "crop", "responsive_width" => true); $result = Cloudinary::cloudinary_url("test", $options); $this->assertEquals($options, array("responsive" => true)); $this->assertEquals( $result, TagTest::DEFAULT_UPLOAD_PATH . "c_crop,h_100,w_100/c_pad,w_auto:breakpoints/test" ); } public function test_width_auto() { // should support width=auto $tag = cl_image_tag("hello", array("width" => "auto", "crop" => "limit", "format" => "png")); $this->assertEquals( "<img class='cld-responsive' data-src='" . self::DEFAULT_UPLOAD_PATH . "c_limit,w_auto/hello.png'/>", $tag ); $tag = cl_image_tag("hello", array("width" => "auto:breakpoints", "crop" => "limit", "format" => "png")); $this->assertEquals( "<img class='cld-responsive' data-src='" . self::DEFAULT_UPLOAD_PATH . "c_limit,w_auto:breakpoints/hello.png'/>", $tag ); $this->cloudinary_url_assertion( "test", array("width" => "auto:20", "crop" => 'fill'), TagTest::DEFAULT_UPLOAD_PATH . "c_fill,w_auto:20/test", array('responsive' => true) ); $this->cloudinary_url_assertion( "test", array("width" => "auto:20:350", "crop" => 'fill'), TagTest::DEFAULT_UPLOAD_PATH . "c_fill,w_auto:20:350/test", array('responsive' => true) ); $this->cloudinary_url_assertion( "test", array("width" => "auto:breakpoints", "crop" => 'fill'), TagTest::DEFAULT_UPLOAD_PATH . "c_fill,w_auto:breakpoints/test", array('responsive' => true) ); $this->cloudinary_url_assertion( "test", array("width" => "auto:breakpoints_100_1900_20_15", "crop" => 'fill'), TagTest::DEFAULT_UPLOAD_PATH . "c_fill,w_auto:breakpoints_100_1900_20_15/test", array('responsive' => true) ); $this->cloudinary_url_assertion( "test", array("width" => "auto:breakpoints:json", "crop" => 'fill'), TagTest::DEFAULT_UPLOAD_PATH . "c_fill,w_auto:breakpoints:json/test", array('responsive' => true) ); } public function test_initial_width_and_height() { $options = array("crop" => "crop", "width" => "iw", "height" => "ih"); $this->cloudinary_url_assertion( "test", $options, TagTest::DEFAULT_UPLOAD_PATH . "c_crop,h_ih,w_iw/test" ); } /** * @param $options * @param string $message */ public function shared_client_hints($options, $message = '') { $tag = cl_image_tag('sample.jpg', $options); $this->assertEquals( "<img src='http://res.cloudinary.com/test/image/upload/c_scale,dpr_auto,w_auto/sample.jpg' />", $tag, $message ); $tag = cl_image_tag('sample.jpg', array_merge(array("responsive" => true), $options)); $this->assertEquals( "<img src='http://res.cloudinary.com/test/image/upload/c_scale,dpr_auto,w_auto/sample.jpg' />", $tag, $message ); } public function test_client_hints_as_option() { $this->shared_client_hints( array( "dpr" => "auto", "cloud_name" => "test", "width" => "auto", "crop" => "scale", "client_hints" => true, ), "support client_hints as an option" ); } public function test_client_hints_as_global() { Cloudinary::config(array("client_hints" => true)); $this->shared_client_hints( array( "dpr" => "auto", "cloud_name" => "test", "width" => "auto", "crop" => "scale", ), "support client hints as global configuration" ); } public function test_client_hints_false() { Cloudinary::config(array("responsive" => true)); $tag = cl_image_tag( 'sample.jpg', array( "width" => "auto", "crop" => "scale", "cloud_name" => "test123", "client_hints" => false, ) ); $this->assertEquals( "<img class='cld-responsive' data-src='" . TagTest::DEFAULT_UPLOAD_PATH . "c_scale,w_auto/sample.jpg'/>", $tag, "should use normal responsive behaviour" ); } /** * @internal * Helper method for generating expected `img` and `source` tags * * @param string $tag_name Expected tag name(img or source) * @param string $public_id Public ID of the image * @param string $common_trans_str Default transformation string to be used in all resources * @param string $custom_trans_str Optional custom transformation string to be be used inside srcset resources * If not provided, $common_trans_str is used * @param array $srcset_breakpoints Optional list of breakpoints for srcset. If not provided srcset is omitted * @param array $attributes Associative array of custom attributes to be added to the tag * * @param bool $is_void Indicates whether tag is an HTML5 void tag (does not need to be self-closed) * * @return string Resulting tag */ private function common_image_tag_helper( $tag_name, $public_id, $common_trans_str, $custom_trans_str = '', $srcset_breakpoints = array(), $attributes = array(), $is_void = false ) { if (empty($custom_trans_str)) { $custom_trans_str = $common_trans_str; } if (!empty($srcset_breakpoints)) { $single_srcset_image = function ($w) use ($custom_trans_str, $public_id) { return self::DEFAULT_UPLOAD_PATH . "{$custom_trans_str}/c_scale,w_{$w}/{$public_id} {$w}w"; }; $attributes['srcset'] = implode(', ', array_map($single_srcset_image, $srcset_breakpoints)); } $tag = "<$tag_name"; $attributes_str = implode( ' ', array_map( function ($k, $v) { return "$k='$v'"; }, array_keys($attributes), array_values($attributes) ) ); if (!empty($attributes_str)) { $tag .= " {$attributes_str}"; } $tag .= $is_void ? ">" : "/>"; // HTML5 void elements do not need to be self closed if (getenv('DEBUG')) { echo preg_replace('/([,\']) /', "$1\n ", $tag) . "\n\n"; } return $tag; } /** * @internal * Helper method for test_cl_image_tag_srcset for generating expected image tag * * @param string $public_id Public ID of the image * @param string $common_trans_str Default transformation string to be used in all resources * @param string $custom_trans_str Optional custom transformation string to be be used inside srcset resources * If not provided, $common_trans_str is used * @param array $srcset_breakpoints Optional list of breakpoints for srcset. If not provided srcset is omitted * @param array $attributes Associative array of custom attributes to be added to the tag * * @return string Resulting image tag */ private function get_expected_cl_image_tag( $public_id, $common_trans_str, $custom_trans_str = '', $srcset_breakpoints = array(), $attributes = array() ) { Cloudinary::array_unshift_assoc( $attributes, 'src', self::DEFAULT_UPLOAD_PATH . "{$common_trans_str}/{$public_id}" ); return $this->common_image_tag_helper( "img", $public_id, $common_trans_str, $custom_trans_str, $srcset_breakpoints, $attributes ); } /** * @internal * Helper method for for generating expected `source` tag * * @param string $public_id Public ID of the image * @param string $common_trans_str Default transformation string to be used in all resources * @param string $custom_trans_str Optional custom transformation string to be be used inside srcset resources * If not provided, $common_trans_str is used * @param array $srcset_breakpoints Optional list of breakpoints for srcset. If not provided srcset is omitted * @param array $attributes Associative array of custom attributes to be added to the tag * * @return string Resulting `source` tag */ private function get_expected_cl_source_tag( $public_id, $common_trans_str, $custom_trans_str = '', $srcset_breakpoints = array(), $attributes = array() ) { $attributes['srcset'] = self::DEFAULT_UPLOAD_PATH . "{$common_trans_str}/{$public_id }"; ksort($attributes); // Used here to produce output similar to Cloudinary::html_attrs return $this->common_image_tag_helper( "source", $public_id, $common_trans_str, $custom_trans_str, $srcset_breakpoints, $attributes, true ); } /** * Should create srcset attribute with provided breakpoints */ public function test_cl_image_tag_srcset() { $expected_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', self::$breakpoints_arr ); $tag_with_breakpoints = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array('srcset' => self::$common_srcset) ) ); $this->assertEquals( $expected_tag, $tag_with_breakpoints, 'Should create img srcset attribute with provided breakpoints' ); } public function test_support_srcset_attribute_defined_by_min_width_max_width_and_max_images() { $tag_min_max_count = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array( 'srcset' => array( 'min_width' => self::$min_width, 'max_width' => $x = self::$max_width, 'max_images' => count(self::$breakpoints_arr) ) ) ) ); $expected_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', self::$breakpoints_arr ); $this->assertEquals( $expected_tag, $tag_min_max_count, 'Should support srcset attribute defined by min_width, max_width, and max_images' ); // Should support 1 image in srcset $tag_one_image_by_params = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array( 'srcset' => array( 'min_width' => self::$breakpoints_arr[0], 'max_width' => self::$max_width, 'max_images' => 1 ) ) ) ); $expected_1_image_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', array(self::$max_width) ); $this->assertEquals($expected_1_image_tag, $tag_one_image_by_params); $tag_one_image_by_breakpoints = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array('srcset' => array('breakpoints' => array(self::$max_width))) ) ); $this->assertEquals($expected_1_image_tag, $tag_one_image_by_breakpoints); // Should support custom transformation for srcset items $custom_transformation = array("transformation" => array("crop" => "crop", "width" => 10, "height" => 20)); $tag_custom_transformation = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array( 'srcset' => array_merge( self::$common_srcset, $custom_transformation ) ) ) ); $custom_transformation_str = 'c_crop,h_20,w_10'; $custom_expected_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, $custom_transformation_str, self::$breakpoints_arr ); $this->assertEquals($custom_expected_tag, $tag_custom_transformation); // Should populate sizes attribute $tag_with_sizes = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array( 'srcset' => array_merge( self::$common_srcset, array('sizes' => true) ) ) ) ); $expected_tag_with_sizes = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', self::$breakpoints_arr, array('sizes' => self::$sizes_attr) ); $this->assertEquals($expected_tag_with_sizes, $tag_with_sizes); // Should support srcset string value $raw_srcset_value = "some srcset data as is"; $tag_with_raw_srcset = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array('attributes' => array('srcset' => $raw_srcset_value)) ) ); $expected_raw_srcset = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', array(), array('srcset' => $raw_srcset_value) ); $this->assertEquals($expected_raw_srcset, $tag_with_raw_srcset); // Should remove width and height attributes in case srcset is specified, but passed to transformation $tag_with_sizes = cl_image_tag( self::$public_id, array_merge( array_merge( self::$common_image_options, array('width' => 500, 'height' => 500) ), array('srcset' => self::$common_srcset) ) ); $expected_tag_without_width_and_height = self::get_expected_cl_image_tag( self::$public_id, 'e_sepia,h_500,w_500', '', self::$breakpoints_arr ); $this->assertEquals($expected_tag_without_width_and_height, $tag_with_sizes); } /** * Should omit srcset attribute on invalid values * * @throws \Exception */ public function test_srcset_invalid_values() { $invalid_breakpoints = array( array('sizes' => true), // srcset data not provided array('max_width' => 300, 'max_images' => 3), // no min_width array('min_width' => '1', 'max_width' => 300, 'max_images' => 3), // invalid min_width array('min_width' => 100, 'max_images' => 3), // no max_width array('min_width' => '1', 'max_width' => '3', 'max_images' => 3), // invalid max_width array('min_width' => 200, 'max_width' => 100, 'max_images' => 3), // min_width > max_width array('min_width' => 100, 'max_width' => 300), // no max_images array('min_width' => 100, 'max_width' => 300, 'max_images' => 0), // invalid max_images array('min_width' => 100, 'max_width' => 300, 'max_images' => -17), // invalid max_images array('min_width' => 100, 'max_width' => 300, 'max_images' => '3'), // invalid max_images array('min_width' => 100, 'max_width' => 300, 'max_images' => null), // invalid max_images ); $err_log_original_destination = ini_get('error_log'); // Suppress error messages in error log ini_set('error_log', '/dev/null'); try { foreach ($invalid_breakpoints as $value) { $tag = cl_image_tag( self::$public_id, array_merge(self::$common_image_options, array('srcset' => $value)) ); self::assertNotContains("srcset", $tag); } } catch (\Exception $e) { ini_set('error_log', $err_log_original_destination); throw $e; } ini_set('error_log', $err_log_original_destination); } public function test_cl_image_tag_responsive_breakpoints_cache() { $cache = ResponsiveBreakpointsCache::instance(); $cache->setCacheAdapter(new KeyValueCacheAdapter(new DummyCacheStorage())); $cache->set(self::$public_id, self::$common_image_options, self::$breakpoints_arr); $expected_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', self::$breakpoints_arr ); $image_tag = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, ["srcset"=> ["use_cache" => true]] ) ); $this->assertEquals($expected_tag, $image_tag); } public function test_create_a_tag_with_custom_attributes_legacy_approach() { $tag_with_custom_legacy_attribute = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, self::$custom_attributes ) ); $expected_custom_attributes_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', array(), self::$custom_attributes ); $this->assertEquals($expected_custom_attributes_tag, $tag_with_custom_legacy_attribute); } public function test_create_a_tag_with_legacy_srcset_attribute() { $srcset_attribute = ['srcset' =>'http://custom.srcset.attr/sample.jpg 100w']; $tag_with_custom_srcset_attribute = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, $srcset_attribute ) ); $expected_custom_attributes_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', array(), $srcset_attribute ); $this->assertEquals($expected_custom_attributes_tag, $tag_with_custom_srcset_attribute); } public function test_consume_custom_attributes_from_attributes_key() { $tag_with_custom_attribute = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array('attributes' => self::$custom_attributes) ) ); $expected_custom_attributes_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', array(), self::$custom_attributes ); $this->assertEquals($expected_custom_attributes_tag, $tag_with_custom_attribute); } public function test_override_existing_attributes_with_specified_by_custom_ones() { $updated_attributes = array('alt' => 'updated alt'); $tag_with_custom_overriden_attribute = cl_image_tag( self::$public_id, array_merge( self::$common_image_options, array('alt' => 'original alt', 'attributes' => $updated_attributes) ) ); $expected_overriden_attributes_tag = self::get_expected_cl_image_tag( self::$public_id, self::$common_transformation_str, '', array(), $updated_attributes ); $this->assertEquals($expected_overriden_attributes_tag, $tag_with_custom_overriden_attribute); } public function test_dpr_auto() { // should support width=auto $tag = cl_image_tag("hello", array("dpr" => "auto", "format" => "png")); $this->assertEquals( "<img class='cld-hidpi' data-src='" . self::DEFAULT_UPLOAD_PATH . "dpr_auto/hello.png'/>", $tag ); } public function test_cl_sprite_tag() { $url = cl_sprite_tag("mytag", array("crop" => "fill", "width" => 10, "height" => 10)); $this->assertEquals( "<link rel='stylesheet' type='text/css' " . "href='" . self::DEFAULT_PATH . "/image/sprite/c_fill,h_10,w_10/mytag.css'>", $url ); } public function test_cl_video_thumbnail_path() { $this->assertEquals(cl_video_thumbnail_path('movie_id'), TagTest::VIDEO_UPLOAD_PATH . "movie_id.jpg"); $this->assertEquals( cl_video_thumbnail_path('movie_id', array('width' => 100)), TagTest::VIDEO_UPLOAD_PATH . "w_100/movie_id.jpg" ); } public function test_cl_video_thumbnail_tag() { $expected_url = TagTest::VIDEO_UPLOAD_PATH . "movie_id.jpg"; $this->assertEquals( cl_video_thumbnail_tag('movie_id'), "<img src='$expected_url' />" ); $expected_url = TagTest::VIDEO_UPLOAD_PATH . "w_100/movie_id.jpg"; $this->assertEquals( cl_video_thumbnail_tag('movie_id', array('width' => 100)), "<img src='$expected_url' width='100'/>" ); } public function test_cl_video_tag() { //default $expected_url = TagTest::VIDEO_UPLOAD_PATH . "movie"; $this->assertEquals( cl_video_tag('movie'), "<video poster='$expected_url.jpg'>" . "<source src='$expected_url.webm' type='video/webm'>" . "<source src='$expected_url.mp4' type='video/mp4'>" . "<source src='$expected_url.ogv' type='video/ogg'>" . "</video>" ); } public function test_cl_video_tag_with_attributes() { //test video attributes $expected_url = TagTest::VIDEO_UPLOAD_PATH . "movie"; $this->assertEquals( cl_video_tag( 'movie', array('autoplay' => true, 'controls', 'loop', 'muted' => "true", 'preload', 'style' => 'border: 1px') ), "<video autoplay='1' controls loop muted='true' poster='$expected_url.jpg' preload style='border: 1px'>" . "<source src='$expected_url.webm' type='video/webm'>" . "<source src='$expected_url.mp4' type='video/mp4'>" . "<source src='$expected_url.ogv' type='video/ogg'>" . "</video>" ); } public function test_cl_video_tag_with_transformation() { //test video attributes $options = array( 'source_types' => "mp4", 'html_height' => "100", 'html_width' => "200", 'video_codec' => array('codec' => 'h264'), 'audio_codec' => 'acc', 'start_offset' => 3, ); $expected_url = TagTest::VIDEO_UPLOAD_PATH . "ac_acc,so_3,vc_h264/movie"; $this->assertEquals( cl_video_tag('movie', $options), "<video height='100' poster='$expected_url.jpg' src='$expected_url.mp4' width='200'></video>" ); unset($options['source_types']); $this->assertEquals( cl_video_tag('movie', $options), "<video height='100' poster='$expected_url.jpg' width='200'>" . "<source src='$expected_url.webm' type='video/webm'>" . "<source src='$expected_url.mp4' type='video/mp4'>" . "<source src='$expected_url.ogv' type='video/ogg'>" . "</video>" ); unset($options['html_height']); unset($options['html_width']); $options['width'] = 250; $expected_url = TagTest::VIDEO_UPLOAD_PATH . "ac_acc,so_3,vc_h264,w_250/movie"; $this->assertEquals( cl_video_tag('movie', $options), "<video poster='$expected_url.jpg' width='250'>" . "<source src='$expected_url.webm' type='video/webm'>" . "<source src='$expected_url.mp4' type='video/mp4'>" . "<source src='$expected_url.ogv' type='video/ogg'>" . "</video>" ); $expected_url = TagTest::VIDEO_UPLOAD_PATH . "ac_acc,c_fit,so_3,vc_h264,w_250/movie"; $options['crop'] = 'fit'; $this->assertEquals( cl_video_tag('movie', $options), "<video poster='$expected_url.jpg'>" . "<source src='$expected_url.webm' type='video/webm'>" . "<source src='$expected_url.mp4' type='video/mp4'>" . "<source src='$expected_url.ogv' type='video/ogg'>" . "</video>" ); } public function test_cl_video_tag_with_fallback() { $expected_url = TagTest::VIDEO_UPLOAD_PATH . "movie"; $fallback = "<span id='spanid'>Cannot display video</span>"; $this->assertEquals( cl_video_tag('movie', array('fallback_content' => $fallback)), "<video poster='$expected_url.jpg'>" . "<source src='$expected_url.webm' type='video/webm'>" . "<source src='$expected_url.mp4' type='video/mp4'>" . "<source src='$expected_url.ogv' type='video/ogg'>" . $fallback . "</video>" ); $this->assertEquals( cl_video_tag('movie', array('fallback_content' => $fallback, 'source_types' => "mp4")), "<video poster='$expected_url.jpg' src='$expected_url.mp4'>" . $fallback . "</video>" ); } public function test_cl_video_tag_with_source_types() { $expected_url = TagTest::VIDEO_UPLOAD_PATH . "movie"; $this->assertEquals( cl_video_tag('movie', array('source_types' => array('ogv', 'mp4'))), "<video poster='$expected_url.jpg'>" . "<source src='$expected_url.ogv' type='video/ogg'>" . "<source src='$expected_url.mp4' type='video/mp4'>" . "</video>" ); } public function test_cl_video_tag_with_source_transformation() { $expected_url = TagTest::VIDEO_UPLOAD_PATH . "q_50/w_100/movie"; $expected_ogv_url = TagTest::VIDEO_UPLOAD_PATH . "q_50/q_70,w_100/movie"; $expected_mp4_url = TagTest::VIDEO_UPLOAD_PATH . "q_50/q_30,w_100/movie"; $this->assertEquals( cl_video_tag( 'movie', array( 'width' => 100, 'transformation' => array(array('quality' => 50)), 'source_transformation' => array( 'ogv' => array('quality' => 70), 'mp4' => array('quality' => 30), ), ) ), "<video poster='$expected_url.jpg' width='100'>" . "<source src='$expected_url.webm' type='video/webm'>" . "<source src='$expected_mp4_url.mp4' type='video/mp4'>" . "<source src='$expected_ogv_url.ogv' type='video/ogg'>" . "</video>" ); $this->assertEquals( cl_video_tag( 'movie', array( 'width' => 100, 'transformation' => array(array('quality' => 50)), 'source_transformation' => array( 'ogv' => array('quality' => 70), 'mp4' => array('quality' => 30), ), 'source_types' => array('webm', 'mp4'), ) ), "<video poster='$expected_url.jpg' width='100'>" . "<source src='$expected_url.webm' type='video/webm'>" . "<source src='$expected_mp4_url.mp4' type='video/mp4'>" . "</video>" ); } public function test_cl_video_tag_with_poster() { $expected_url = TagTest::VIDEO_UPLOAD_PATH . "movie"; $expected_poster_url = 'http://image/somewhere.jpg'; $this->assertEquals( cl_video_tag('movie', array('poster' => $expected_poster_url, 'source_types' => "mp4")), "<video poster='$expected_poster_url' src='$expected_url.mp4'></video>" ); $expected_poster_url = TagTest::VIDEO_UPLOAD_PATH . "g_north/movie.jpg"; $this->assertEquals( cl_video_tag( 'movie', array('poster' => array('gravity' => 'north'), 'source_types' => "mp4") ), "<video poster='$expected_poster_url' src='$expected_url.mp4'></video>" ); $expected_poster_url = TagTest::DEFAULT_UPLOAD_PATH . "g_north/my_poster.jpg"; $this->assertEquals( cl_video_tag( 'movie', array( 'poster' => array('gravity' => 'north', 'public_id' => 'my_poster', 'format' => 'jpg'), 'source_types' => "mp4", ) ), "<video poster='$expected_poster_url' src='$expected_url.mp4'></video>" ); $this->assertEquals( cl_video_tag('movie', array('poster' => null, 'source_types' => "mp4")), "<video src='$expected_url.mp4'></video>" ); $this->assertEquals( cl_video_tag('movie', array('poster' => false, 'source_types' => "mp4")), "<video src='$expected_url.mp4'></video>" ); } /** * Check that cl_video_tag encodes special characters. */ public function test_cl_video_tag_special_characters_encoding() { $expected_url = TagTest::VIDEO_UPLOAD_PATH . "movie%27s%20id%21%40%23%24%25%5E%26%2A%28"; $this->assertEquals( "<video poster='$expected_url.jpg' src='$expected_url.mp4'></video>", cl_video_tag("movie's id!@#$%^&*(", array('source_types' => "mp4")) ); } public function test_cl_video_tag_default_sources() { $expected_url = self::VIDEO_UPLOAD_PATH . "%smovie.%s"; $this->assertEquals( "<video poster='" . sprintf($expected_url, '', 'jpg') ."'>" . "<source src='" . sprintf($expected_url, 'vc_h265/', 'mp4') . "' type='video/mp4; codecs=hev1'>" . "<source src='" . sprintf($expected_url, 'vc_vp9/', 'webm') . "' type='video/webm; codecs=vp9'>" . "<source src='" . sprintf($expected_url, 'vc_auto/', 'mp4') . "' type='video/mp4'>" . "<source src='" . sprintf($expected_url, 'vc_auto/', 'webm') . "' type='video/webm'>" . "</video>", cl_video_tag('movie', array('sources' => default_video_sources())) ); } public function test_cl_video_tag_custom_sources() { $custom_sources = [ [ "type" => "mp4", "codecs" => "vp8, vorbis", "transformations" => ["video_codec" => "auto"] ], [ "type" => "webm", "codecs" => "avc1.4D401E, mp4a.40.2", "transformations" => ["video_codec" => "auto"] ] ]; $expected_url = self::VIDEO_UPLOAD_PATH . "%smovie.%s"; $this->assertEquals( "<video poster='" . sprintf($expected_url, '', 'jpg') ."'>" . "<source src='" . sprintf($expected_url, 'vc_auto/', 'mp4') . "' type='video/mp4; codecs=vp8, vorbis'>" . "<source src='" . sprintf($expected_url, 'vc_auto/', 'webm') . "' type='video/webm; codecs=avc1.4D401E, mp4a.40.2'>" . "</video>", cl_video_tag('movie', array('sources' => $custom_sources)) ); } public function test_cl_video_tag_sources_codecs_array() { $custom_sources = [ [ "type" => "mp4", "codecs" => ["vp8", "vorbis"], "transformations" => ["video_codec" => "auto"] ], [ "type" => "webm", "codecs" => ["avc1.4D401E", "mp4a.40.2"], "transformations" => ["video_codec" => "auto"] ] ]; $expected_url = self::VIDEO_UPLOAD_PATH . "%smovie.%s"; $this->assertEquals( "<video poster='" . sprintf($expected_url, '', 'jpg') ."'>" . "<source src='" . sprintf($expected_url, 'vc_auto/', 'mp4') . "' type='video/mp4; codecs=vp8, vorbis'>" . "<source src='" . sprintf($expected_url, 'vc_auto/', 'webm') . "' type='video/webm; codecs=avc1.4D401E, mp4a.40.2'>" . "</video>", cl_video_tag('movie', array('sources' => $custom_sources)) ); } public function test_cl_video_tag_sources_with_transformation() { $options = array( 'source_types' => "mp4", 'html_height' => "100", 'html_width' => "200", 'video_codec' => array('codec' => 'h264'), 'audio_codec' => 'acc', 'start_offset' => 3, 'sources' => default_video_sources() ); $expected_url = self::VIDEO_UPLOAD_PATH . "ac_acc,so_3,%smovie.%s"; $this->assertEquals( "<video height='100' poster='" . sprintf($expected_url, 'vc_h264/', 'jpg') ."' width='200'>" . "<source src='" . sprintf($expected_url, 'vc_h265/', 'mp4') . "' type='video/mp4; codecs=hev1'>" . "<source src='" . sprintf($expected_url, 'vc_vp9/', 'webm') . "' type='video/webm; codecs=vp9'>" . "<source src='" . sprintf($expected_url, 'vc_auto/', 'mp4') . "' type='video/mp4'>" . "<source src='" . sprintf($expected_url, 'vc_auto/', 'webm') . "' type='video/webm'>" . "</video>", cl_video_tag('movie', $options) ); } public function test_upload_tag() { $pattern = "/<input class='cloudinary-fileupload' " . "data-cloudinary-field='image' " . "data-form-data='{\&quot;timestamp\&quot;:\d+,\&quot;signature\&quot;:\&quot;\w+\&quot;," . "\&quot;api_key\&quot;:\&quot;a\&quot;}' " . "data-url='http[^']+\/v1_1\/test123\/auto\/upload' " . "name='file' type='file'\/>/"; $this->assertRegExp($pattern, cl_upload_tag('image')); $this->assertRegExp($pattern, cl_image_upload_tag('image')); $pattern = "/<input class='cloudinary-fileupload' " . "data-cloudinary-field='image' " . "data-form-data='{\&quot;timestamp\&quot;:\d+,\&quot;signature\&quot;:\&quot;\w+\&quot;," . "\&quot;api_key\&quot;:\&quot;a\&quot;}' " . "data-max-chunk-size='5000000' " . "data-url='http[^']+\/v1_1\/test123\/auto\/upload' " . "name='file' type='file'\/>/"; $this->assertRegExp( $pattern, cl_upload_tag('image', array('chunk_size' => 5000000)) ); $pattern = "/<input class='classy cloudinary-fileupload' " . "data-cloudinary-field='image' " . "data-form-data='{\&quot;timestamp\&quot;:\d+,\&quot;signature\&quot;:\&quot;\w+\&quot;," . "\&quot;api_key\&quot;:\&quot;a\&quot;}' " . "data-url='http[^']+\/v1_1\/test123\/auto\/upload' " . "name='file' type='file'\/>/"; $this->assertRegExp( $pattern, cl_upload_tag('image', array("html" => array('class' => 'classy'))) ); } public function test_cl_source_tag() { $expected_tag = self::get_expected_cl_source_tag( self::$public_id, self::$common_transformation_str, '', self::$breakpoints_arr, array('sizes' => self::$sizes_attr, "media" => generate_media_attr(["max_width" =>self::$max_width])) ); $source_tag_with_srcset = cl_source_tag( self::$public_id, array_merge( self::$common_image_options, array( 'srcset' => array_merge( self::$common_srcset, array('sizes' => true) ) ), array( 'media' => array("max_width" =>self::$max_width) ) ) ); $this->assertEquals( $expected_tag, $source_tag_with_srcset, 'Should create source tag with srcset and sizes attributes with provided breakpoints' ); } public function test_cl_picture_tag() { $tag = cl_picture_tag( self::$public_id, self::$fill_transformation, [ [ "max_width" =>self::$min_width, "transformation" => ["effect" => "sepia", "angle" => 17, "width" => self::$min_width] ], [ "min_width" => self::$min_width, "max_width" => self::$max_width, "transformation" => ["effect" => "colorize", "angle" => 18, "width" => self::$max_width] ], [ "min_width" => self::$max_width, "transformation" => ["effect" => "blur", "angle" => 19, "width" => self::$max_width] ] ] ); $expected_source1 = self::get_expected_cl_source_tag( self::$public_id, self::$fill_trans_str . "/" . "a_17,e_sepia,w_" . self::$min_width, '', [], ["media" => generate_media_attr(["max_width" =>self::$min_width])] ); $expected_source2 = self::get_expected_cl_source_tag( self::$public_id, self::$fill_trans_str . "/" . "a_18,e_colorize,w_" . self::$max_width, '', [], ["media" => generate_media_attr(["min_width" => self::$min_width, "max_width" =>self::$max_width])] ); $expected_source3 = self::get_expected_cl_source_tag( self::$public_id, self::$fill_trans_str . "/" . "a_19,e_blur,w_" . self::$max_width, '', [], ["media" => generate_media_attr(["min_width" => self::$max_width])] ); $expected_img = self::get_expected_cl_image_tag( self::$public_id, self::$fill_trans_str, '', [], ['height' => self::$max_width, 'width' => self::$max_width] ); $exp = "<picture>" . $expected_source1 . $expected_source2 . $expected_source3 . $expected_img . "</picture>"; $this->assertEquals($exp, $tag); } private function cloudinary_url_assertion($source, $options, $expected, $expected_options = array()) { $url = Cloudinary::cloudinary_url($source, $options); $this->assertEquals($expected_options, $options); $this->assertEquals($expected, $url); } }
true
98b05ed17c6b2767ad5c61a6fa19ce374ab51cf7
PHP
geertvangent/ects
/Application/Discovery/Module/TrainingInfo/Implementation/Bamaflex/SubTrajectory.php
UTF-8
2,032
2.796875
3
[]
no_license
<?php namespace Ehb\Application\Discovery\Module\TrainingInfo\Implementation\Bamaflex; use Ehb\Application\Discovery\DiscoveryItem; class SubTrajectory extends DiscoveryItem { const PROPERTY_SOURCE = 'source'; const PROPERTY_TRAJECTORY_ID = 'trajectory_id'; const PROPERTY_NAME = 'name'; private $courses; /** * * @return int */ public function get_source() { return $this->get_default_property(self::PROPERTY_SOURCE); } /** * * @param int $source */ public function set_source($source) { $this->set_default_property(self::PROPERTY_SOURCE, $source); } public function get_trajectory_id() { return $this->get_default_property(self::PROPERTY_TRAJECTORY_ID); } public function set_trajectory_id($trajectory_id) { $this->set_default_property(self::PROPERTY_TRAJECTORY_ID, $trajectory_id); } public function get_name() { return $this->get_default_property(self::PROPERTY_NAME); } public function set_name($name) { $this->set_default_property(self::PROPERTY_NAME, $name); } public static function get_default_property_names($extended_property_names = array()) { $extended_property_names[] = self::PROPERTY_SOURCE; $extended_property_names[] = self::PROPERTY_TRAJECTORY_ID; $extended_property_names[] = self::PROPERTY_NAME; return parent::get_default_property_names($extended_property_names); } /** * * @return DataManagerInterface */ public function get_data_manager() { // return DataManager :: getInstance(); } public function get_courses() { return $this->courses; } public function set_courses($courses) { $this->courses = $courses; } public function has_courses() { return count($this->courses) > 0; } public function add_course($course) { $this->courses[] = $course; } }
true
dca0c6f61110f1915cc1f6da78b2e7d755eb7eed
PHP
codingmetta/webshop-plenty-planty.github.io
/scripts/registration-submit.php
UTF-8
1,466
3.203125
3
[]
no_license
<?php /**@file registration-submit.php * @brief Script connects to database and registers a * new user with submitted data. * * @author Talia Deckardt */ require'login.php'; $conn = new mysqli($servername, $username, $password, $dbname); $salt1 = "qm&h*"; $salt2 = "pg!@"; $role = 'user'; $forename = $_POST['forename']; $surname = $_POST['surname']; $email = $_POST['email']; $un = $_POST['username']; $passw = $_POST['password']; $repassw = $_POST['password-repeat']; $token = hash('ripemd128', "$salt1$passw$salt2"); $check_passed = check_password($passw, $repassw); if ($check_passed){ add_user($conn, $role, $forename, $surname, $email, $un, $token); echo 'You successfully signed up. Please <a href="../pages/loginUser.php">click here</a> to log in. '; } else { echo 'Repeated Password is incorrect. Please try again.'; } /** @fn 'Double Check Password' * @brief Checks if both entered passwords are the same */ function check_password($pw, $rpw){ if($pw == $rpw){ return true; } else { return false; } } /** @fn 'Add User' * @brief Adds user with given credentials to table 'Users' */ function add_user($conn, $rl, $fn, $sn, $em, $un, $pw) { $sql = "INSERT INTO Users (role, forename, surname, email, username, password) VALUES ('$rl','$fn','$sn','$em', '$un', '$pw')"; if ($conn->query($sql) === TRUE) { } else { echo "Error: " . $sql . "<br>" . $conn->error; } } ?>
true
2551d4cd6a250f478909d7a972051a86d892c64f
PHP
bZez/SF5-GRC
/src/Entity/Partner.php
UTF-8
1,907
2.75
3
[]
no_license
<?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\PartnerRepository") */ class Partner { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $nom; /** * @ORM\Column(type="json") */ private $produits = []; /** * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="partner") */ private $users; public function __construct() { $this->users = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getNom(): ?string { return $this->nom; } public function setNom(string $nom): self { $this->nom = $nom; return $this; } public function getProduits(): ?array { return $this->produits; } public function setProduits(array $produits): self { $this->produits = $produits; return $this; } /** * @return Collection|User[] */ public function getUsers(): Collection { return $this->users; } public function addUser(User $user): self { if (!$this->users->contains($user)) { $this->users[] = $user; $user->setPartner($this); } return $this; } public function removeUser(User $user): self { if ($this->users->contains($user)) { $this->users->removeElement($user); // set the owning side to null (unless already changed) if ($user->getPartner() === $this) { $user->setPartner(null); } } return $this; } }
true
0bfe953c03db6e83aa9c8b79ff1b592349296d95
PHP
mildphp/framework
/src/Mild/Support/Events/LocaleUpdated.php
UTF-8
320
2.640625
3
[]
no_license
<?php namespace Mild\Support\Events; use Mild\Event\Event; class LocaleUpdated extends Event { /** * @var string */ public $locale; /** * LocaleUpdated constructor. * * @param $locale */ public function __construct($locale) { $this->locale = $locale; } }
true
60cff38b1dc0ce25f5af042eab05ce7e87843af1
PHP
impact-pt/impact-ios
/PhP/createApmt.php
UTF-8
882
2.703125
3
[]
no_license
<?php //Creates appointment in database $con=mysqli_connect("db.sice.indiana.edu","i494f18_team13","my+sql=i494f18_team13","i494f18_team13"); if (!$con) { die("Failed to connect to MySQL: ".mysqli_connect_error. "\n"); } else { echo "Connected to the database"; } $userid = $_GET['userid']; $apmtDate = $_GET['apmtDate']; $apmtTime = $_GET['apmtTime']; $patientid = $_GET['patient']; echo $userid; echo '-'; echo $apmtDate; echo '-'; echo $apmtTime; echo '-'; echo $patient; echo '-'; $insertAppointment = "INSERT INTO Appointments(PhysicianID,apmtDate,apmtTime,PatientID) VALUES('$userid','$apmtDate','$apmtTime','$patientid')"; if(mysqli_query($con, $insertAppointment)) { echo 'successfully created appointment'; } else { echo 'failed to create appointment'; } ?>
true
c4994521d8f9788f619f7a2e43097b1d4e9ef1e4
PHP
kolholga/oop
/app/lib/User.php
UTF-8
2,109
3.671875
4
[]
no_license
<?php namespace Ddd\fff; //private - свойства и методы доступные только в этом/текущем классе class User { private $name; //свойство/ по умолчанию null private $age; //свойство/ по умолчанию null //private const LOGIN = 'admin'; // константа принадлежит классу /* public function __construct($n, $a) //метод КОНСТРУКТОР // всегда!!! модификатор public по умолчанию { $this->age = $a; $this->name = $n; } */ public function __construct() { echo 'Я нахожусь в пространстве имен \Ddd\fff'; } public function getAge() // ГЕТТЕР - метод для возвращения значения свойства age { //self::LOGIN; - обращаемся к константе return $this->age; } public function getName() // ГЕТТЕР - метод для возвращения значения свойства name { return $this->name; } public function setAge($age) // СЕТТЕР - метод / устанавливает возраст { if ($age > 18 && $age < 60) { $this->age = $age; } } public function setName($name) // СЕТТЕР - метод / устанавливает имя { $this->name = $name; } } //$man = new User('Vasya', '18'); // в $man присваиваем объект класса User //$man->name = 'Вася'; //$man->age = '18'; /* $man = new User; // сoздали объект User // если нет конструкторa, скобки можно не ставить $man->setAge(' 25'); $man->setName(' Petya '); echo 'My name is ' . $man->getName() . "age" . $man->getAge() . ' years old <br>'; */ //echo 'My login is ' . User::LOGIN; /* var_dump($man); echo '<br>'; $man2 = new User('Gena', '21'); //$man2->name = 'Петя'; //$man2->age = '30'; var_dump($man2); echo '<br>'; var_dump($man); */
true
ed7403019c0b50ada63c9d649535c3fd06ce9a74
PHP
pimpmypixel/confirmit-authoring
/src/StructType/QuestionFormBase.php
UTF-8
9,704
2.65625
3
[]
no_license
<?php namespace Confirmit\Authoring\StructType; use \WsdlToPhp\PackageBase\AbstractStructBase; /** * This class stands for QuestionFormBase StructType * @subpackage Structs */ abstract class QuestionFormBase extends FormBase { /** * The StartPosition * Meta informations extracted from the WSDL * - use: required * @var int */ public $StartPosition; /** * The NotPerformDataCleaningOnMasking * Meta informations extracted from the WSDL * - use: required * @var bool */ public $NotPerformDataCleaningOnMasking; /** * The Level * Meta informations extracted from the WSDL * - use: required * @var int */ public $Level; /** * The JscriptExpression * Meta informations extracted from the WSDL * - use: required * @var bool */ public $JscriptExpression; /** * The BenchmarkType * Meta informations extracted from the WSDL * - use: required * @var string */ public $BenchmarkType; /** * The Seed * Meta informations extracted from the WSDL * - use: required * @var int */ public $Seed; /** * The ValidationCode * Meta informations extracted from the WSDL * - maxOccurs: 1 * - minOccurs: 0 * @var string */ public $ValidationCode; /** * The ParentGrid3DFormName * @var string */ public $ParentGrid3DFormName; /** * Constructor method for QuestionFormBase * @uses QuestionFormBase::setStartPosition() * @uses QuestionFormBase::setNotPerformDataCleaningOnMasking() * @uses QuestionFormBase::setLevel() * @uses QuestionFormBase::setJscriptExpression() * @uses QuestionFormBase::setBenchmarkType() * @uses QuestionFormBase::setSeed() * @uses QuestionFormBase::setValidationCode() * @uses QuestionFormBase::setParentGrid3DFormName() * @param int $startPosition * @param bool $notPerformDataCleaningOnMasking * @param int $level * @param bool $jscriptExpression * @param string $benchmarkType * @param int $seed * @param string $validationCode * @param string $parentGrid3DFormName */ public function __construct($startPosition = null, $notPerformDataCleaningOnMasking = null, $level = null, $jscriptExpression = null, $benchmarkType = null, $seed = null, $validationCode = null, $parentGrid3DFormName = null) { $this ->setStartPosition($startPosition) ->setNotPerformDataCleaningOnMasking($notPerformDataCleaningOnMasking) ->setLevel($level) ->setJscriptExpression($jscriptExpression) ->setBenchmarkType($benchmarkType) ->setSeed($seed) ->setValidationCode($validationCode) ->setParentGrid3DFormName($parentGrid3DFormName); } /** * Get StartPosition value * @return int */ public function getStartPosition() { return $this->StartPosition; } /** * Set StartPosition value * @param int $startPosition * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public function setStartPosition($startPosition = null) { // validation for constraint: int if (!is_null($startPosition) && !is_numeric($startPosition)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, "%s" given', gettype($startPosition)), __LINE__); } $this->StartPosition = $startPosition; return $this; } /** * Get NotPerformDataCleaningOnMasking value * @return bool */ public function getNotPerformDataCleaningOnMasking() { return $this->NotPerformDataCleaningOnMasking; } /** * Set NotPerformDataCleaningOnMasking value * @param bool $notPerformDataCleaningOnMasking * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public function setNotPerformDataCleaningOnMasking($notPerformDataCleaningOnMasking = null) { // validation for constraint: boolean if (!is_null($notPerformDataCleaningOnMasking) && !is_bool($notPerformDataCleaningOnMasking)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a bool, "%s" given', gettype($notPerformDataCleaningOnMasking)), __LINE__); } $this->NotPerformDataCleaningOnMasking = $notPerformDataCleaningOnMasking; return $this; } /** * Get Level value * @return int */ public function getLevel() { return $this->Level; } /** * Set Level value * @param int $level * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public function setLevel($level = null) { // validation for constraint: int if (!is_null($level) && !is_numeric($level)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, "%s" given', gettype($level)), __LINE__); } $this->Level = $level; return $this; } /** * Get JscriptExpression value * @return bool */ public function getJscriptExpression() { return $this->JscriptExpression; } /** * Set JscriptExpression value * @param bool $jscriptExpression * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public function setJscriptExpression($jscriptExpression = null) { // validation for constraint: boolean if (!is_null($jscriptExpression) && !is_bool($jscriptExpression)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a bool, "%s" given', gettype($jscriptExpression)), __LINE__); } $this->JscriptExpression = $jscriptExpression; return $this; } /** * Get BenchmarkType value * @return string */ public function getBenchmarkType() { return $this->BenchmarkType; } /** * Set BenchmarkType value * @uses \Confirmit\Authoring\EnumType\BenchmarkFormType::valueIsValid() * @uses \Confirmit\Authoring\EnumType\BenchmarkFormType::getValidValues() * @throws \InvalidArgumentException * @param string $benchmarkType * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public function setBenchmarkType($benchmarkType = null) { // validation for constraint: enumeration if (!\Confirmit\Authoring\EnumType\BenchmarkFormType::valueIsValid($benchmarkType)) { throw new \InvalidArgumentException(sprintf('Value "%s" is invalid, please use one of: %s', $benchmarkType, implode(', ', \Confirmit\Authoring\EnumType\BenchmarkFormType::getValidValues())), __LINE__); } $this->BenchmarkType = $benchmarkType; return $this; } /** * Get Seed value * @return int */ public function getSeed() { return $this->Seed; } /** * Set Seed value * @param int $seed * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public function setSeed($seed = null) { // validation for constraint: int if (!is_null($seed) && !is_numeric($seed)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, "%s" given', gettype($seed)), __LINE__); } $this->Seed = $seed; return $this; } /** * Get ValidationCode value * @return string|null */ public function getValidationCode() { return $this->ValidationCode; } /** * Set ValidationCode value * @param string $validationCode * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public function setValidationCode($validationCode = null) { // validation for constraint: string if (!is_null($validationCode) && !is_string($validationCode)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($validationCode)), __LINE__); } $this->ValidationCode = $validationCode; return $this; } /** * Get ParentGrid3DFormName value * @return string|null */ public function getParentGrid3DFormName() { return $this->ParentGrid3DFormName; } /** * Set ParentGrid3DFormName value * @param string $parentGrid3DFormName * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public function setParentGrid3DFormName($parentGrid3DFormName = null) { // validation for constraint: string if (!is_null($parentGrid3DFormName) && !is_string($parentGrid3DFormName)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($parentGrid3DFormName)), __LINE__); } $this->ParentGrid3DFormName = $parentGrid3DFormName; return $this; } /** * Method called when an object has been exported with var_export() functions * It allows to return an object instantiated with the values * @see AbstractStructBase::__set_state() * @uses AbstractStructBase::__set_state() * @param array $array the exported values * @return \Confirmit\Authoring\StructType\QuestionFormBase */ public static function __set_state(array $array) { return parent::__set_state($array); } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } }
true
a8c1eecbc7f0ebc4290620f66ae3b1e7e88ecff3
PHP
MorisPae/PHPTraining
/20170508/test1.php
UTF-8
139
3.328125
3
[]
no_license
<?php $var_str = "Hello world"; $var_int = 8; $var_float = 10.5; echo $var_str . "<br>" . $var_int ."<br>". $var_float; ?>
true
b0b69ee2b1dcb7587636235c70dd5abfa6536d29
PHP
orangeShadow/pastebin-api
/src/Repositories/PastebinRepository.php
UTF-8
2,570
2.859375
3
[]
no_license
<?php declare(strict_types = 1); namespace OrangeShadow\PastebinApi\Repositories; use OrangeShadow\PastebinApi\Exceptions; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Exception\ClientException; class PastebinRepository { private $pastebin_host = "https://pastebin.com/"; private $api_dev_key; private $client; /** * PastebinApi constructor. * * @param $api_dev_key * */ public function __construct(string $api_dev_key) { $this->api_dev_key = $api_dev_key; $this->client = new Client(); } /** * Create Paste * * @param $attributes * @return string * */ public function createPaste(array $attributes):string { $attributes['api_option'] = 'paste'; return $this->sendRequest('POST', 'api/api_post.php', $attributes); } /** * Get paste list * * @param $attributes * @return string */ public function getPasteList(array $attributes):string { $attributes['api_option'] = 'list'; return $this->sendRequest('POST', 'api/api_post.php', $attributes); } /** * Get paste list * * @param $attributes * @return string */ public function deletePaste(array $attributes):string { $attributes['api_option'] = 'delete'; return $this->sendRequest('POST', 'api/api_post.php', $attributes); } /** * Get paste list * * @param $attributes * @return string */ public function getPasteRaw(array $attributes):string { $attributes['api_option'] = 'show_paste'; return $this->sendRequest('POST', 'api/api_raw.php', $attributes); } /** * Send request to the server through Guzzle Client * * @param $method * @param $path * @param $attributes * @return string * * @throws Exceptions\InvalidResponseException */ private function sendRequest(string $method, string $path, array $attributes): string { $attributes['api_dev_key'] = $this->api_dev_key; $request = new Request($method, $this->pastebin_host . $path, ['Content-Type' => 'application/x-www-form-urlencoded'], http_build_query($attributes, '', '&')); try { $response = $this->client->send($request); } catch (ClientException $e) { throw new Exceptions\InvalidResponseException($e->getMessage(), $e->getCode(), $e); } return $response->getBody()->getContents(); } }
true
9fc9c4355f07c88fe5e04a7839b35a84a69bfdf9
PHP
HaruItari/target_21
/common/components/WebUser.php
UTF-8
4,234
2.796875
3
[]
no_license
<?php /** * Базовый класс, представляющий пользователя. */ class WebUser extends CWebUser { /** * @see CWebUser::getRole() */ public function getRole() { if ($user = $this->getModel()) { return Yii::app()->db->createCommand(" SELECT t.role FROM user_group AS t, user WHERE t.id = user.group AND user.id = {$this->id} ")->queryScalar(); } } /** * Получение flash-сообщения и обрамление его в тематические блоки. * Перегрузка стандартного метода {@link parent::getFlash}. * @param string $key Ключ сообщения * @param string $type Тип возвращаемого значения * @param mixed $defaultValue Возвращаемое значение в случае отсутствия сообщения * @param boolean $delete Удалить сообщение после вывода * @return mixed or bool */ public function getFlash($key, $type = null, $defaultValue = null, $delete = true) { $return = parent::getFlash($key, $defaultValue, $delete); if (isset($return)) { switch ($type) { case 'info' : return '<div class="info">' . $return . '</div>'; break; case 'note' : return '<div class="note">' . $return . '</div>'; break; case 'error' : return '<div class="error">' . $return . '</div>'; break; default : return $return; break; } } return false; } /** * Проверка наличия flash-сообщения. * Перегрузка стандартного метода {@link parent::hasFlash}. * @param string $key Ключ сообщения * @return boolean Существование сообщения */ public function hasFlash($key) { return $this->getFlash($key, null, null, false) !== null; } /** * Установка якорной страницы, на которую в дальнейшем будет возвращен пользователь. * @params string $url Фиксируемый адрес. Если не указан, присваивается текущая страница. * @return void */ public function setAnchorUrl($url = null) { if($url === null) $url = Yii::app()->request->getRequestUri(); $this->setState('_anchorUrl', $url); } /** * Возвращает адрес якорной страницы. * @return string */ public function getAnchorUrl() { return $this->getState('_anchorUrl'); } /** * @see CWebUser::beforeLogin() */ protected function beforeLogin($id, $states, $fromCookie) { if ($fromCookie) { if(!empty($states['cookiesSolt'])) return MUser::model()->findByAttributes(array( 'id' => $states['id'], 'cookies_solt' => $states['cookiesSolt'], )); else return false; } else { return true; } } /** * Данные о пользователе (модель MUser). * @var object */ private $_model = null; /** * Получение экземпляра $this->_model. * Если он не опреелен, создание нового. * @return object */ private function getModel() { if (!$this->isGuest && $this->_model === null) { $this->_model = MUser::model()->findByPk($this->id); } return $this->_model; } }
true
043b5fbce711fc4a876aba984ccdac3894bcf3ae
PHP
jfoxworth/makstudio
/database/migrations/2019_09_03_082133_create_builds_table.php
UTF-8
982
2.921875
3
[]
no_license
<?php /* The designs table holds the overall data for each type of design. The instance represents a given instantiation of a model or design. A build is an iteration of a given instance. There can be multiple builds for each */ use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBuildsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('builds', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('user_id'); // ID of user that stored the build $table->text('build_data'); // Content of build $table->string('build_id'); // Something to identify that build - bench, fin wall, etc $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('builds'); } }
true
c0db680a174e29ef21182cb0578569f8a3cee0d0
PHP
JuanRobles2164/CustomLaravelVersion
/app/Console/Commands/Helpers/MakeViewHelper.php
UTF-8
663
2.78125
3
[]
no_license
<?php namespace App\Console\Commands\Helpers; class MakeViewHelper{ /** * @param string Cadena que representa la plantilla maestra a utilizar. Ej: Master_Layout * @param array Array que representa las secciones de las que comprenderá la vista. Ej: content,custom_scripts * @return string Cadena que representa el contenido del archivo a generar */ public static function BasicViewContent($parent_layout, array $section){ $content = "@extends('$parent_layout')\n"; foreach($section as $name){ $content = $content . " @section('$name') @endsection "; } return $content; } }
true
a7f83a270a0a9909bc5da4f133bb044f4c090aa1
PHP
divyaramanan/Server-Side-Processing---PHP
/authorize.php
UTF-8
885
2.8125
3
[]
no_license
<?php $values = array(); foreach($_POST as $item) { $item = trim($item); $values [] = $item; } $user = $values[0]; $pass = $values[1]; $rep = $values[2]; $valid = false; if(strlen($user)==0) { echo "*User Name is Required"; exit; } if(strlen($pass)==0) { echo "*Password is Required"; exit; } $raw_str = file_get_contents('pass.dat'); $data = explode("\n",$raw_str); foreach($data as $item) { $pair = explode('=',$item); if($user === $pair[0] && crypt($pass,$pair[1]) === $pair[1]) $valid = true; } if($valid) { if(!($rep=="rep1"||$rep=="rep2")) { echo "*Choose any one Report"; exit; } if($rep == "rep1") { echo '<script> $("#loginbody").load("report1.php"); </script>'; exit; } if($rep == "rep2") { echo '<script> $("#loginbody").load("report2.php"); </script>'; exit; } } else echo "Incorrect User name or password"; ?>
true
52be89f86457ce0223d902d6f455a526a1406a5e
PHP
StereoFlo/Example-Laravel
/engine/app/Models/RoleUser.php
UTF-8
1,840
2.84375
3
[]
no_license
<?php namespace RecycleArt\Models; /** * Class RoleUser * @package RecycleArt\Models */ class RoleUser extends Model { /** * @var string */ protected $table = 'role_user'; /** * @var array */ protected $fillable = [ 'role_id', 'user_id', ]; /** * @param int $userId * @param int $roleId * * @return bool */ public function enableRole(int $userId, int $roleId): bool { $role = $this->where('user_id', $userId)->where('role_id', $roleId)->get(); if (!$this->checkEmptyObject($role)) { return (bool) $this->create([ 'role_id' => $roleId, 'user_id' => $userId, ]); } return false; } /** * @param int $userId * @param string $roleId * * @return bool */ public function enableRoleByName(int $userId, string $roleId): bool { $getRole = $this->getRole()->getByName($roleId); if (empty($getRole)) { return false; } $role = $this->where('user_id', $userId)->where('role_id', $getRole['id'])->get(); if (!$this->checkEmptyObject($role)) { return (bool) $this->create([ 'role_id' => $getRole['id'], 'user_id' => $userId, ]); } return false; } /** * @param int $userId * @param int $roleId * * @return bool */ public function disableRole(int $userId, int $roleId = 0): bool { return $this->where('user_id', $userId)->where('role_id', $roleId)->delete(); } /** * @param int $userId * * @return bool */ public function disableAllRole(int $userId): bool { return $this->where('user_id', $userId)->delete(); } }
true
76737d51eeedea01987cccb61efca92af5478956
PHP
gaoxiangbo9527/php-manual
/Examples/Language Reference/Constants/Syntax/Example #1 Defining Constants.php
UTF-8
141
2.578125
3
[]
no_license
<?php define("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." echo Constant; // outputs "Constant" and issues a notice.
true
26593dacc938a077d2d31d457ec392d924d72ad6
PHP
pickupgame/pickupgame
/profilepage.php
UTF-8
1,937
2.578125
3
[ "Apache-2.0" ]
permissive
<?php session_start(); include_once('db/sql_functions.php'); if(isset($_GET['UserID']) && checkifUserExists($_GET['UserID'])) { $userID=$_GET['UserID']; $result=getUserInfo($userID); $name=$result["Name"]; $age=$result["Age"]; $username=$result["UserName"]; $imageLocation=$result["ImageLocation"]; ?> <table class='table table-striped'> <thead> <tr> <th rowspan = "5"> <?php if($imageLocation==null||$imageLocation=="") { print("<img src= 'http://kystmuseetnorveg.no/wp-content/themes/museetmidt-avd/images/default-profile-img.jpg' alt= 'Profile Picture' width=200 height=200>"); } else { print("<img src= '{$imageLocation}' alt= 'Profile Picture' width=200 height=200>"); } print("</th>"); print("<th>Name:</th>"); print("<th>{$name}</th>"); print("</tr>"); print("<tr>"); print("<th>Age:</th>"); print("<th>{$age}</th>"); print("</tr>"); print("<tr>"); print("<th>UserName:</th>"); print("<th>{$username}</th>"); print("</tr>"); print("<tr>"); print("<th>Host Rating:</th>"); $HostRating=getHostRating($userID); $TotalHostRates=getLikes($userID); $PlayerRating=getPlayerRating($userID); $TotalPlayerRates=getTotalRatingsAsPlayer($userID); print("<th>{$HostRating}/{$TotalHostRates} ({$TotalHostRates} vote(s))</th>"); print("</tr>"); print("<tr>"); print("<th>Player Rating</th>"); print("<th>{$PlayerRating}/{$TotalPlayerRates} ({$TotalPlayerRates} vote(s))</th>"); print("</tr>"); print("</thead>"); print("</table>"); if(isset($_SESSION['UserID']) AND $_SESSION['UserID'] == $userID) print("<a class='btn btn-info btn-xs' href='index.php?page=profile&UserID=$userID&action=editprofile'>Edit Profile Information</a><br>"); // getUpcomingGames($userID); } else { if(isset($_SESSION['UserID'])) { echo "<p class='text-danger'>User does not exist.</p>"; } else { } } ?>
true
d98eb5ea9d92dbc065cb468b1b09f1893d52d0aa
PHP
mctech4/mvc-php
/lib/app/util/hash.php
UTF-8
593
2.78125
3
[]
no_license
<?php namespace app\util; class hash { private static $password_algo = "whirlpool"; private static $password_salt = "passwordsalty"; private static $data_algo = "md5"; private static $data_salt = "datasalty"; public static function load($algo, $data, $salt) { $ctx = hash_init($algo, HASH_HMAC, $salt); hash_update($ctx, $data); return hash_final($ctx); } public static function password($data) { return self::load(self::$password_algo, $data, self::$password_salt); } public static function data($data) { return self::load(self::$data_algo, $data, self::$data_salt); } }
true
c870b9fec403d5748348a56e9a65e0d0142cfbd6
PHP
pengshizhong/code_repository
/php/testConstruct.php
UTF-8
117
2.875
3
[]
no_license
<?php class father{ function __construct(){ echo "father"; } } class son extends father{ } $a=new son();
true
bcbc412bb57d4e6ac9819b9d7afd249e83a2c661
PHP
echoHolaSarabia/CRM-PHP
/admin/modulos/mod_noticiasORIGINAL/ajax/recargar_planillas.php
ISO-8859-3
2,638
2.640625
3
[]
no_license
<?php include_once("../../../../configuracion.php"); include_once("../../../includes/conexion.inc.php"); if ($_POST['id_seccion'] != "nada") { if ($_POST['id_seccion'] < 0) $_POST['id_seccion'] = -$_POST['id_seccion']; if (isset($_POST['id_seccion']) && ($_POST['id_seccion'] != "")) { $c = "SELECT id_padre FROM secciones WHERE id=" . $_POST['id_seccion']; $r = mysql_query($c); $r = mysql_fetch_assoc($r); if ($r["id_padre"] == -1) { // Seccin $id_seccion = $_POST['id_seccion']; $id_subseccion = -1; } else { // Subseccin $id_seccion = $r["id_padre"]; $id_subseccion = $_POST['id_seccion']; } } $c = "SELECT id,fecha_publicacion FROM planillas WHERE seccion=" . $id_seccion . " ORDER BY fecha_publicacion DESC"; $r = mysql_query($c); if (mysql_num_rows($r)) { $enc = 0; $selected = ""; ?><optgroup label="Secci&oacute;n"><?php while ($fila = mysql_fetch_assoc($r)) { if ($enc == 0) { $fecha = explode(" ", $fila['fecha_publicacion']); $hora = $fecha[1]; $fecha = $fecha[0]; $fecha = explode("-", $fecha); $hora = explode(":", $hora); if (mktime($hora[0], $hora[1], $hora[2], $fecha[1], $fecha[2], $fecha[0]) < time()) { $enc = 1; $selected = " SELECTED "; } } else $selected = ""; ?> <option value="<?php echo $fila['id'] ?>" <?php echo $selected ?> ><?php echo $fila['id'] ?> - <?php echo $fila['fecha_publicacion'] ?></option> <?php } ?></optgroup><?php } if ($id_subseccion != -1) { $c = "SELECT id,fecha_publicacion FROM planillas WHERE seccion=" . $id_subseccion . " ORDER BY fecha_publicacion DESC"; $r = mysql_query($c); if (mysql_num_rows($r)) { $enc = 0; $selected = ""; ?><optgroup label="Subsecci&oacute;n"><?php while ($fila = mysql_fetch_assoc($r)) { if ($enc == 0) { $fecha = explode(" ", $fila['fecha_publicacion']); $hora = $fecha[1]; $fecha = $fecha[0]; $fecha = explode("-", $fecha); $hora = explode(":", $hora); if (mktime($hora[0], $hora[1], $hora[2], $fecha[1], $fecha[2], $fecha[0]) < time()) { $enc = 1; $selected = " SELECTED "; } } else $selected = ""; ?> <option value="<?php echo $fila['id'] ?>" <?php echo $selected ?> ><?php echo $fila['id'] ?> - <?php echo $fila['fecha_publicacion'] ?></option> <?php } ?></optgroup><?php } } } else echo "";
true
c38a73e00956fa69f795112d70218a1a411e8558
PHP
andrasq/quicklib
/test/lib/Quick/Rest/AppRunnerTest.php
UTF-8
9,073
2.640625
3
[ "Apache-2.0" ]
permissive
<? /** * Copyright (C) 2013 Andras Radics * Licensed under the Apache License, Version 2.0 */ class Quick_Rest_AppRunnerTest_EchoController implements Quick_Rest_Controller { public function echoAction( Quick_Rest_Request $request, Quick_Rest_Response $response ) { foreach ($request->getParams() as $k => $v) $response->setValue($k, $v); } } class Quick_Rest_AppRunnerTest extends Quick_Test_Case implements Quick_Rest_Controller { public function setUp( ) { $this->_cut = new Quick_Rest_AppRunner(); } public function testRouteCallShouldAcceptCallbacksThatAppearValid( ) { // valid $this->_cut->routeCall('GET', '/path1', 'Quick_Rest_AppRunnerTest_EchoController::echoAction'); $this->_cut->routeCall('GET', '/path2', 'function_exists'); $this->_cut->routeCall('GET', '/path3', create_function('$a,$b,$c', 'return;')); // not valid, but syntactically appear to be $this->_cut->routeCall('GET', '/path4', array("hello", "world")); $this->_cut->routeCall('GET', '/path5', "Hello, world"); } /** * @expectedException Quick_Rest_Exception */ public function testRunCallShouldThrowExceptionIfPathNotRouted( ) { $this->_cut->routeCall('GET', '/foo', 'Quick_Rest_AppRunnerTest_EchoController::echoAction'); $request = $this->_makeRequest('GET', '/bar', array(), array()); $this->_cut->runCall($request, $this->_makeResponse()); } public function invalidCallbackProvider( ) { return array( array(123), array(array(1, 2)), ); } /** * @expectedException Quick_Rest_Exception * @dataProvider invalidCallbackProvider */ public function testRouteCallShouldTrowExceptionIfCallbackNotValid( $callback ) { $this->_cut->routeCall('GET', '/call/name', $callback); } public function testRunCallShouldInvokeDoublecolonStringCallback( ) { $this->_cut->routeCall('GET|POST|OTHER', "/call/path", 'Quick_Rest_AppRunnerTest_EchoController::echoAction'); foreach (array('GET', 'POST', 'OTHER') as $method) { $id = uniqid(); $request = $this->_makeRequest($method, '/call/path', array('a' => 1), array('b' => $id)); $response = $this->_cut->runCall($request, $this->_makeResponse()); $this->assertContains($id, $response->getResponse()); } } public function testRunCallShouldInvokeArrayCallbacks( ) { $runner = $this->_makeRunner($calls = array('a', 'b', 'c')); foreach ($calls as $call) $this->_cut->routeCall('GET', "/call/$call", array($runner, $call)); foreach ($calls as $call) { $request = $this->_makeRequest('GET', "/call/$call", array(), array()); $this->_cut->runCall($request, $this->_makeResponse()); } } public function testRunCallShouldInvokeAnonymousFunctionCallbacks( ) { if (version_compare(phpversion(), "5.3.0") < 0) $this->markTestSkipped(); $runner = $this->_makeRunner($calls = array('a', 'b', 'c')); foreach ($calls as $call) $this->_cut->routeCall('GET', "/call/$call", function ($req, $resp, $app) use ($runner) { $path = $req->getPath(); $method = substr($path, strrpos($req->getPath(), '/')+1); $runner->$method($req, $resp, $app); }); foreach ($calls as $call) { $request = $this->_makeRequest('GET', "/call/$call", array(), array()); $this->_cut->runCall($request, $this->_makeResponse()); } } public function testRunCallShouldInvokeSetCallInsteadOfPath( ) { $runner = $this->_makeRunner($calls = array('a')); $this->_cut->routeCall('ALL', 'CALLS', array($runner, 'a')); $this->_cut->setCall('ALL::CALLS'); $request = $this->_makeRequest('GET', '/call/foo/bar', array(), array()); $this->_cut->runCall($request, $this->_makeResponse()); } public function testRunCallShouldPassUserAppToActionMethod( ) { $app = $this->getMock('Quick_Rest_App', array('getInstance')); $controller = $this->getMock('Quick_Rest_Controller', array('testAction')); //$this->_cut->routeCall('GET', '/test', array($controller, 'testAction')); $routes = array( 'GET::/test' => array($controller, 'testAction') ); $this->_cut->setRoutes($routes); $request = $this->_makeRequest('GET', '/test', array(), array()); $response = $this->_makeResponse(); $controller->expects($this->once())->method('testAction')->with($request, $response, $app); $this->_cut->runCall($request, $response, $app); } public function xx_testSpeed( ) { $timer = new Quick_Test_Timer(); $timer->calibrate(10000, array($this, '_testNullSpeed'), array(1, 2)); echo $timer->timeit(20000, 'empty call', array($this, '_testNullSpeed'), array(1, 2)); echo $timer->timeit(20000, 'create', array($this, '_testCreateSpeed'), array(1, 2)); $cut = new Quick_Rest_AppRunner(); for ($call = 'aa'; $call < 'ac'; $call++) $routes["GET::/$call"] = "class::$call"; $cut->setRoutes($routes); echo $timer->timeit(1000, 'set routes(5)', array($this, '_testRoutesSpeed'), array($cut, & $routes)); // 560k/s for 2, 390k/s for 4, 136k/s for 16, 34k/s for 77, 4k/s for 675 // w/o is_callable test 1.75m/sec for 675!! (by ref, or 7.7k/s by value overwrite, 11k/s first assign) // assigning an array is linear in the number of elements ?? ...even if assigned by reference ?? $globals = $this->_makeGlobalsForCall('GET', '/call/name', array(), array()); $request = $this->_makeRequest('GET', '/call/name', array(), array()); // 640k/s $cut->routeCall('GET', '/call/name', 'Quick_Rest_AppRunnerTest_EchoController::echoAction'); echo $timer->timeit(20000, 'route to string w/ request', array($this, '_testRunCallSpeed'), array($cut, $request)); // 140k/s echo $timer->timeit(20000, 'route to string w/ globals', array($this, '_testRunCallSpeedGlobals'), array($cut, $globals)); // 90k/s $cut->routeCall('GET', '/call/name', array(new Quick_Rest_AppRunnerTest_EchoController(), 'echoAction')); echo $timer->timeit(20000, 'route to callback w/ globals', array($this, '_testRunCallSpeedGlobals'), array($cut, $globals)); // 101k/s echo $timer->timeit(20000, 'oneshot, handle page hit', array($this, '_testOneshotPageHitSpeed'), array($cut, $globals)); // 65k/s (85k/s on amd 3.6 GHz) // NOTE: measuring inside apache to capture apc autoloading delays, more like ~1k (cold) to 4k/s (looped) } public function _testNullSpeed( $x, $y ) { } public function _testRoutesSpeed( $cut, & $routes ) { $cut->setRoutes($routes); } public function _testCreateSpeed( $x, $y ) { $new = new Quick_Rest_AppRunner(); } public function _testRunCallSpeed( $cut, $request ) { $cut->runCall($request, new Quick_Rest_Response_Http()); } public function _testRunCallSpeedGlobals( $cut, & $globals ) { $request = new Quick_Rest_Request_Http(); $request->setParamsFromGlobals($globals); $response = new Quick_Rest_Response_Http(); $cut->runCall($request, $response); } public function _testOneshotPageHitSpeed( $cut, & $globals ) { $cut = new Quick_Rest_AppRunner(); $request = new Quick_Rest_Request_Http(); $request->setParamsFromGlobals($globals); $response = new Quick_Rest_Response_Http(); //$cut->routeCall('GET', '/call/name', 'Quick_Rest_AppRunnerTest_EchoController::echoAction'); $cut->routeCall('GET', $request->getPath(), 'Quick_Rest_AppRunnerTest_EchoController::echoAction'); $cut->runCall($request, $response); } protected function _makeGlobalsForCall( $method, $uri, Array $getargs, Array $postargs ) { return $globals = array( '_GET' => $getargs, '_POST' => $postargs, '_SERVER' => array( 'SERVER_PROTOCOL' => 'HTTP/1.1', 'REQUEST_METHOD' => strtoupper($method), 'REQUEST_URI' => $uri, ), ); } protected function _makeRequest( $method, $uri, Array $getargs, Array $postargs ) { $request = new Quick_Rest_Request_Http(); $globals = $this->_makeGlobalsForCall($method, $uri, $getargs, $postargs); $request->setParamsFromGlobals($globals); return $request; } protected function _makeResponse( ) { return new Quick_Rest_Response_Http(); } protected function _makeRunner( Array $calls ) { $runner = $this->getMock('Quick_Rest_Controller', $calls); foreach ($calls as $call) $runner->expects($this->once())->method($call); return $runner; } }
true
44e7c93fa4d1df486888989c30b2c93c15b8108b
PHP
netzmacht/tapatalk-client-api
/src/Netzmacht/Tapatalk/Api/Users/User.php
UTF-8
1,274
2.96875
3
[]
no_license
<?php /** * @package tapatalk-client-api * @author David Molineus <[email protected]> * @copyright 2014 netzmacht creative David Molineus * @license LGPL 3.0 * @filesource * */ namespace Netzmacht\Tapatalk\Api\Users; use Netzmacht\Tapatalk\Transport\MethodCallResponse; class User { /** * @var int */ private $id; /** * @var string */ private $username; /** * @var string */ private $avatarUrl; /** * @param int $id * @param string $username * @param string $avatar */ function __construct($id, $username, $avatar) { $this->id = $id; $this->username = $username; $this->avatarUrl = $avatar; } /** * @param MethodCallResponse $response * @return User */ public static function fromResponse(MethodCallResponse $response) { return new static( $response->get('user_id'), $response->get('username', true), $response->get('icon_url') ); } /** * @return mixed */ public function getAvatarUrl() { return $this->avatarUrl; } /** * @return bool */ public function hasAvatar() { return ($this->avatarUrl != null); } /** * @return int */ public function getId() { return $this->id; } /** * @return string */ public function getUsername() { return $this->username; } }
true
b2db89ce7666651da494b824d1fa72f9e16588c9
PHP
lx1986tao16/tandyBlog
/app/Http/Controllers/Admin/TagsController.php
UTF-8
1,636
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Admin; use App\Models\Tag; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class TagsController extends Controller { public function index() { $tags = Tag::all(); return view('admin.tags.list', compact('tags')); } public function create() { return view('admin.tags.create'); } public function store(Request $request) { $this->validate($request, [ 'name' => 'required|max:255|unique:tags', ]); Tag::create([ 'name' => $request->name, ]); session()->flash('success', '创建Tag成功!'); return redirect()->back(); } public function edit($id) { $tags = Tag::findOrFail($id); return view('admin.tags.edit', compact('tags')); } public function update($id, Request $request) { $tags = Tag::findOrFail($id); $tags->name = $request->name; $tags->update(); session()->flash('success', 'Tag更新成功'); return redirect()->route('tags.index'); } public function destroy($id) { $tag = Tag::findOrFail($id); $tag->delete(); session()->flash('success', '删除tag成功'); return redirect()->back(); } public function getTags() { $tags = Tag::all(); $tags_data = []; foreach ($tags as $tag) { array_push($tags_data, [ "value" => $tag->id, "text" => $tag->name, ]); } return response()->json($tags_data); } }
true
f6526cf0af8ac918ebb9e87c8f373b3c64a8d634
PHP
wwrona/php
/powitalna.php
UTF-8
559
3.28125
3
[]
no_license
<?php $obrazki = array('1.png', '2.png', '3.png', '4.png', '5.png', '6.png'); shuffle($obrazki); ?> <html> <head> <title> Strona powitalna</title> </head> <body> <h1>Części samochodwe</h1> <div align="center"> <table width = 100%> <tr> <?php /* Poniższe wkłada obrazki w tabelę for ($i = 0; $i <3; $i++) { echo "<td align=\"center\"><img src=\""; echo $obrazki[$i]; echo "\"/></td>"; } */ // A teraz to samo, tylko przy użyciu concatenation: for ($i = 0; $i < 4; $i++) { echo "<td align=\"center\"><img src=\"" . $obrazki[$i] . "\"/></td>"; } ?>
true
6f166812d885eb0b9a553d49bf06eef21f39b141
PHP
marscore/hhvm
/hphp/test/zend/good/ext/standard/tests/strings/htmlspecialchars_decode_variation6.php
UTF-8
1,043
3.5625
4
[ "Zend-2.0", "PHP-3.01", "MIT" ]
permissive
<?php /* Prototype : string htmlspecialchars_decode(string $string [, int $quote_style]) * Description: Convert special HTML entities back to characters * Source code: ext/standard/html.c */ /* * testing whether htmlspecialchars_decode() is binary safe or not */ <<__EntryPoint>> function main() { echo "*** Testing htmlspecialchars_decode() : usage variations ***\n"; //various string inputs $strings = array ( "\tHello \$world ".chr(0)."\&!)The big brown fox jumped over the\t\f lazy dog\v\n", "\tHello \"world\"\t\v \0 This is a valid\t string", "This converts\t decimal to \$string".decbin(65)."Hello world", b"This is a binary\t \v\fstring" ); //loop through the strings array to check if htmlspecialchars_decode() is binary safe $iterator = 1; foreach($strings as $value) { echo "-- Iteration $iterator --\n"; if ($iterator < 4) { var_dump( htmlspecialchars_decode($value) ); } else { var_dump( bin2hex(htmlspecialchars_decode($value))); } $iterator++; } echo "Done"; }
true
0854c5788103ec628c79b802f09496d9beed8735
PHP
JvMolli/2DawServidor
/examenPhp/controllers/persona.php
UTF-8
961
3.296875
3
[]
no_license
<?php class Persona { public $nombre; public $apellidos; public $sexo; public $edad; public $telefono; public $imagen; public $contraseña; function __construct($nombre, $apellidos, $sexo, $edad, $telefono, $contraseña, $imagen) { $this->nombre = $nombre; $this->apellidos = $apellidos; $this->sexo = $sexo; $this->edad = $edad; $this->telefono = $telefono; $this->imagen = $imagen; $this->contraseña = $contraseña; } // function getJsonData(){ // $var = get_object_vars($this); // foreach ($var as &$value) { // if (is_object($value) && method_exists($value,'getJsonData')) { // $value = $value->getJsonData(); // } // } // return $var; // } function __toString(){ return $this->nombre . " " . $this->apellidos . " " . $this->sexo . " " . $this->edad . " " . $this->telefono . " " . $this->contraseña; } } ?>
true
db9724d43ce97b4f11e4d54e28ad08c40438f580
PHP
rozinCodes/school-management
/API/application/controllers/api/Login.php
UTF-8
1,927
2.671875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php require APPPATH.'libraries/REST_Controller.php'; class Login extends REST_Controller { public function __construct() { parent::__construct(); //load database $this->load->database(); $this->load->model(array("api/student_model")); $this->load->model(array("api/common_model")); $this->load->library(array("form_validation")); $this->load->helper("security"); } public function admin_login_post(){ $this->form_validation->set_rules("email", "Email", "required"); if ($this->form_validation->run() == NULL) { // we have some errors $this->response(array( "status" => 0, "message" => "All fields are needed or filled form is not valid" ) , REST_Controller::HTTP_OK); } else { $email = $this->security->xss_clean($this->input->post("email")); $password = $this->security->xss_clean($this->input->post("password")); $user = $this->common_model->admin_login($email, $password); if ($user) { $userdata = array( "id" => $user->ID, "email" => $user->EMAIL, "first_name" => $user->FIRST_NAME, "photo" => $user->PHOTO, //"surname" => $user->surname, "roles" => $user->ROLES_ID, "authenticated" => TRUE ); $this->response(array( "status" => 1, "message" => "Login Success" ), REST_Controller::HTTP_OK); } else { // we have some empty field $this->response(array( "status" => 0, "message" => "Login credential does not match" ), REST_Controller::HTTP_OK); } } } }
true
64e2e363e1ec47d2ea38f353e75633e09098d4b8
PHP
andreadlm/unito
/tweb/Vuvuzela/services/functions/authors.php
UTF-8
1,073
2.8125
3
[]
no_license
<?php # Selects a randomly ordered list of the :num authors that have written the most # articles and have set the profile picture const AUTHOR_QUERY = 'SELECT * FROM ( SELECT coalesce(user.complete_name, user.username) as name, user.img FROM user JOIN article ON user.id = article.author_id WHERE user.img IS NOT NULL GROUP BY user.id, user.complete_name, user.img ORDER BY COUNT(DISTINCT article.id) DESC LIMIT :num ) AS cni ORDER BY rand()'; # Returns an array of the data associated to the $num most active authors, # randomly ordered. # On error, returns false. function getAuthors(PDO $connection, int $num): bool|array { $statement = $connection->prepare(AUTHOR_QUERY); $statement->bindValue(':num', $num, PDO::PARAM_INT); $statement->execute(); return $statement->fetchAll(PDO::FETCH_ASSOC); }
true
7a9398b48162c198ba025f87637b1dc6ec76e7c0
PHP
big-javascript-fan/HyonMoo-WooCom
/hyunmoo/framework/theme/shortcodes/one_half.php
UTF-8
686
2.734375
3
[]
no_license
<?php // Column one_half shortcode ////////////////////////////////////////////////////////////////// function hyunmoo_shortcode_one_half($atts, $content = '') { $default_atts = shortcode_atts( array( 'last' => 'no', ), $atts); # Overwrite Default Attributes $atts = shortcode_atts( $default_atts, $atts ); extract( $atts ); $output=""; if($last == 'yes') { $output.= '<div class="one_half last">' .do_shortcode($content). '</div><div class="clear"></div>'; } else { $output.= '<div class="one_half">' .do_shortcode($content). '</div>'; } return $output; } add_shortcode('one_half', 'hyunmoo_shortcode_one_half'); ?>
true
a9c8407a8d2770795c860bcf971c304185a0313a
PHP
nachovazquez1990/mongril_club
/public_html/admin/model/consumo_class.php
UTF-8
4,804
2.59375
3
[]
no_license
<?php /*********************************************************** CLASE - read_by_id($id) - read_by_name($consumo) - read_all_consumos($consumo, $precio, $consumo) - create_consumo($consumo, $precio, $consumo(numero)) - delete_consumo($id) - update_consumo($consumo, $precio, $consumo(numero)) ************************************************************/ function restar_dinero_socio($socio_id, $importe){ global $link; $socio_id = (int) $socio_id; $importe = (float) $importe; $sql = "SELECT saldo FROM socios WHERE socio_id = '$socio_id'"; $query = mysqli_query($link,$sql); $ahorro = mysqli_fetch_assoc($query); $ahorro_final = $ahorro['saldo']; $saldo_restante = $ahorro_final - $importe; if ($saldo_restante < 0) { $ba_query['message_code'] = 'c107'; return false; } $sql2 = "UPDATE socios SET saldo = '$saldo_restante' WHERE socio_id = '$socio_id'"; $query2 = mysqli_query($link,$sql2); if(!mysqli_affected_rows($link)){ $ba_query['message_code'] = 'c108'; return false; } return true; } function calcular_importe($producto_id, $cantidad){ global $link; $producto_id = (int) $producto_id; $cantidad = (float) $cantidad; $sql = "SELECT precio FROM productos WHERE producto_id = '$producto_id'"; $query = mysqli_query($link,$sql); $coste = mysqli_fetch_assoc($query); $coste_final = $coste['precio']; $importe = $cantidad * $coste_final; return $importe; } function calcular_cantidad($producto_id, $importe){ global $link; $producto_id = (int) $producto_id; $importe = (float) $importe; $sql = "SELECT precio FROM productos WHERE producto_id = '$producto_id'"; $query = mysqli_query($link,$sql); $coste = mysqli_fetch_assoc($query); $coste_final = $coste['precio']; $cantidad = $importe / $coste_final; return $cantidad; } function devolver_dinero_socio($socio_id, $importe){ global $link; $socio_id = (int) $socio_id; $importe = (float) $importe; $sql = "SELECT saldo FROM socios WHERE socio_id = '$socio_id'"; $query = mysqli_query($link,$sql); $ahorro = mysqli_fetch_assoc($query); $ahorro_final = $ahorro['saldo']; $saldo_restante = $importe + $ahorro_final; $sql2 = "UPDATE socios SET saldo = '$saldo_restante' WHERE socio_id = '$socio_id'"; $query2 = mysqli_query($link,$sql2); if(mysqli_affected_rows($link)>0){ return true; } return false; } function create_consumo($socios_id, $productos_id, $cantidad, $importe, $fecha){ global $link; $socio_id = (int) $socios_id; $producto_id = (int) $productos_id; $cantidad = (float) $cantidad; $importe = (float) $importe; $fecha = $fecha; if( !$socio_id || !$producto_id || !$cantidad || !$importe || !$fecha ){ return false; } $sql = "INSERT INTO consumos(socios_id, productos_id, cantidad, importe, fecha) VALUES('$socios_id', '$producto_id', '$cantidad', '$importe', '$fecha')"; $query = mysqli_query($link,$sql); if(mysqli_insert_id($link)>0){ restar_dinero_socio($socio_id, $importe); return true; } return false; } function read_consumo_by_id( $id ){ global $link; $id = (int) $id; $sql = "SELECT consumo_id, socios_id, producto, precio, importe, fecha FROM consumos LEFT JOIN socios ON socios_id = socio_id LEFT JOIN productos ON productos_id = producto_id WHERE consumo_id = '$id'"; $query = mysqli_query($link,$sql); $num_rows = mysqli_num_rows($query); if( $num_rows > 0 ){ return mysqli_fetch_assoc($query); } return false; } function read_consumo_by_name( $producto ){ global $link; $producto = mysqli_real_escape_string($link,$producto); if(!$producto){ return false; } $sql = "SELECT consumo_id, producto, precio, fecha FROM consumos LEFT JOIN productos ON productos_id = producto_id WHERE productos.producto = '$producto'"; $query = mysqli_query($link,$sql); $num_rows = mysqli_num_rows($query); if( $num_rows > 0 ){ return mysqli_fetch_assoc($query); } return false; } function read_all_consumos(){ global $link; $sql = "SELECT consumo_id, socios_id, producto, precio, cantidad, importe, fecha FROM consumos LEFT JOIN productos ON productos_id = producto_id ORDER BY consumo_id DESC"; $query = mysqli_query($link,$sql); $num_rows = mysqli_num_rows($query); if( $num_rows > 0 ){ return $query; } return false; } function delete_consumo( $id ){ global $link; $id = (int) $id; $consumo = read_consumo_by_id($id); $socio_id = $consumo['socios_id']; $importe = $consumo ['importe']; $resultado = devolver_dinero_socio($socio_id, $importe); if ($resultado = false) { return false; } $sql = "DELETE FROM consumos WHERE consumo_id = '$id'"; $query = mysqli_query($link,$sql); $affected_rows = mysqli_affected_rows( $link ); if( $affected_rows > 0 ){ return true; } return false; }
true
144c2685e7c760594d90bcc317930f9cd4c96572
PHP
gcarneiro/sheer
/sheer/core/action/queryGenerator/Add.php
UTF-8
2,892
3.1875
3
[]
no_license
<?php namespace Sh\QueryGenerator; /** * @author guilherme * * Classe geradora de querys para inserção a partir de ActionHandlers * */ class Add { /* * Query padrão */ const QUERY_PATTERN = 'INSERT INTO {table} {fieldlist} VALUES {values}'; /** * @var \Sh\ActionHandler */ protected $actionHandler; /** * @var array */ protected $data; /* * Elementos da query */ protected $fieldlist = ''; protected $table = ''; protected $values = ''; public function __construct(\Sh\ActionHandler $actionHandler) { //SALVO O ACTIONHANDLER $this->actionHandler = $actionHandler; } /** * Método gerador da query * @param array $data * @return mixed */ public function getQuery ($data) { //EFETUO O PROCESSAMENTO DO FIELDLIST E DOS VALORES $this->createFieldListAndValuesQuery($data); //GERO O NOME DA TABLE $this->createTableQuery(); //CRIANDO A QUERY $replacement = array('{table}', '{fieldlist}', '{values}'); $value = array($this->table, $this->fieldlist, $this->values); $query = str_replace($replacement, $value, self::QUERY_PATTERN); return $query; } /** * Método para gerar o fieldList do datasource com os fields desejados */ protected function createFieldListAndValuesQuery ($data) { $queryFieldList = ''; $queryValues = ''; $first = true; $fields = $this->actionHandler->getDataSource()->getFields(false); //itero por todos os fields gerando tanto o fieldList quanto capturando o seu valor foreach ( $fields as $field ) { if( !$first ) { $queryFieldList .= ', '; $queryValues .= ', '; } //GERANDO O FIELDLIST $queryFieldList .= $field->getId(); //GERANDO O VALOR //determinando o valor enviado [considero enviado se for array ou tiver pelo menos um caracter] $valorEnviado = false; if( isset($data[$field->getId()]) && ( is_array($data[$field->getId()]) || strlen($data[$field->getId()]) > 0 ) ) { $valorEnviado = true; } //se o valor foi enviado corretamente if( $valorEnviado ) { //Removo a conversao input=>primitive daqui e jogo pro actionClass para conseguir inserir arquivos // $sqlValue = $field::formatInputDataToPrimitive($data[$field->getId()]); $sqlValue = addslashes($data[$field->getId()]); $queryValues .= '"'.$sqlValue.'"'; } //o valor não foi enviado else { if( $field->getSetNullIfBlank() ) { $queryValues .= 'NULL'; } else { $queryValues .= '""'; } } $first = false; } $queryFieldList = '('.$queryFieldList.')'; $queryValues = '('.$queryValues.')'; $this->fieldlist = $queryFieldList; $this->values = $queryValues; } /** * Método para gerar o campo "table" da query */ protected function createTableQuery () { $this->table = $this->actionHandler->getDataSource()->getTable(); } }
true
7245389bf5ad8ab0a8174c6b297e4f8e673e62e0
PHP
Ashiyro/Mon-Framework
/Components/Router/Router.php
UTF-8
1,445
2.96875
3
[ "MIT" ]
permissive
<?php namespace Components\Router; use Psr\Http\Message\ServerRequestInterface; use Zend\Expressive\Router\FastRouteRouter; use Zend\Expressive\Router\Route as ZendRoute; /** * Register and match routes */ class Router { /** * @var FastRouteRouter */ private $router; public function __construct() { $this->router = new FastRouteRouter(); } /** * @param string $path * @param string|callable $callable * @param string $name */ public function get(string $path, $callable, ?string $name = null) { $this->router->addRoute(new ZendRoute($path, $callable, ['GET'], $name)); } public function post(string $path, $callable, ?string $name = null) { $this->router->addRoute(new ZendRoute($path, $callable, ['POST'], $name)); } /** * @param ServerRequestInterface $request * @return Route|null */ public function match(ServerRequestInterface $request): ?Route { $result = $this->router->match($request); if ($result->isSuccess()) { return new Route( $result->getMatchedRouteName(), $result->getMatchedMiddleware(), $result->getMatchedParams() ); } return null; } public function generateUri(string $name, array $params): ?string { return $this->router->generateUri($name, $params); } }
true
51418500e4421e4f5773232a7df85b39db603e6f
PHP
commercetools/commercetools-sdk-php-v2
/lib/commercetools-api/src/Models/ShippingMethod/ShippingMethodAddZoneActionBuilder.php
UTF-8
1,760
2.515625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); /** * This file has been auto generated * Do not change it. */ namespace Commercetools\Api\Models\ShippingMethod; use Commercetools\Api\Models\Zone\ZoneResourceIdentifier; use Commercetools\Api\Models\Zone\ZoneResourceIdentifierBuilder; use Commercetools\Base\Builder; use Commercetools\Base\DateTimeImmutableCollection; use Commercetools\Base\JsonObject; use Commercetools\Base\JsonObjectModel; use Commercetools\Base\MapperFactory; use stdClass; /** * @implements Builder<ShippingMethodAddZoneAction> */ final class ShippingMethodAddZoneActionBuilder implements Builder { /** * @var null|ZoneResourceIdentifier|ZoneResourceIdentifierBuilder */ private $zone; /** * <p>Value to add to <code>zoneRates</code>.</p> * * @return null|ZoneResourceIdentifier */ public function getZone() { return $this->zone instanceof ZoneResourceIdentifierBuilder ? $this->zone->build() : $this->zone; } /** * @param ?ZoneResourceIdentifier $zone * @return $this */ public function withZone(?ZoneResourceIdentifier $zone) { $this->zone = $zone; return $this; } /** * @deprecated use withZone() instead * @return $this */ public function withZoneBuilder(?ZoneResourceIdentifierBuilder $zone) { $this->zone = $zone; return $this; } public function build(): ShippingMethodAddZoneAction { return new ShippingMethodAddZoneActionModel( $this->zone instanceof ZoneResourceIdentifierBuilder ? $this->zone->build() : $this->zone ); } public static function of(): ShippingMethodAddZoneActionBuilder { return new self(); } }
true
3965246462eb3b518e19185905c4c9a77144d973
PHP
mcordingley/HashBin
/src/Hasher.php
UTF-8
222
3.109375
3
[ "MIT" ]
permissive
<?php namespace mcordingley\HashBin; interface Hasher { /** * @param string $input * @return int A signed integer between PHP_INT_MIN and PHP_INT_MAX */ public function hash(string $input): int; }
true
6adc43c4acb4f8c1a1f71a56821040b086718d64
PHP
iamluc/GloomyPagerBundle
/RESTConnector/SlickGrid.php
UTF-8
1,538
2.515625
3
[ "MIT" ]
permissive
<?php namespace Gloomy\PagerBundle\RESTConnector; class SlickGrid extends RESTBase { public function __construct($request, $pager, array $config = array()) { parent::__construct($request, $pager, $config); } public function handle() { // items per page $perPage = $this->_request->get('count', 10); if ($perPage > 500) { $perPage = 500; } elseif ($perPage <= 0) { $perPage = 10; } // page number $pageNumber = ($this->_request->get('offset', 0) / $perPage) + 1; /** * Pager Configuration */ $this->_pager->setCurrentPageNumber($pageNumber); $this->_pager->setItemCountPerPage($perPage); $fields = $this->_pager->getFields(); $fieldsIndex = array_keys($fields); /** * Formatting datas */ $items = $this->_pager->getItems(); $infos = $this->_pager->getPages(); $datas = array(); foreach ($items as $obj) { $item = array(); foreach ($fields as $field) { $item[$field->getProperty()] = $field->readData($obj); } $datas[] = $item; } $response = array( "fromPage" => $this->_request->get('fromPage', 0), "total" => $infos->totalItemCount, "count" => count($datas), "stories" => $datas ); return $this->jsonResponse($response); } }
true
e241420ba1f687eb110432bd2be84b2297dabe76
PHP
hanxiao84322/coach_system
/models/Activity.php
UTF-8
5,233
2.671875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "activity". * * @property integer $id * @property string $name * @property integer $category * @property integer $level_id * @property integer $recruit_count * @property string $sign_up_begin_time * @property string $sign_up_end_time * @property integer $sign_up_status * @property string $begin_time * @property string $end_time * @property integer $status * @property string $content * @property integer $lesson * @property integer $score * @property string $address * @property string $launch * @property string $organizers * @property string $join_teams * @property string $create_time * @property string $create_user * @property string $update_time * @property string $update_user * * @property Level $level * @property ActivityUsers[] $activityUsers */ class Activity extends \yii\db\ActiveRecord { //分类 const WEEKEND = 1; const DAILY = 2; static public $categoryList = [ self::WEEKEND => '周末班', self::DAILY => '日常班' ]; //课程状态 const NEW_ADD = 1; const BEGIN_SIGN_UP = 2; const END_SIGN_UP = 3; const DOING = 4; const END = 5; static public $statusList = [ self::NEW_ADD => '未开始报名', self::BEGIN_SIGN_UP => '报名开始', self::END_SIGN_UP => '报名结束', self::DOING => '进行中', self::END => '结束', ]; public $already_recruit_count; /** * @inheritdoc */ public static function tableName() { return 'activity'; } /** * @inheritdoc */ public function rules() { return [ [['category', 'level_id', 'recruit_count', 'sign_up_status', 'status', 'lesson', 'score'], 'integer'], [['sign_up_begin_time', 'sign_up_end_time', 'begin_time', 'end_time', 'create_time', 'update_time'], 'safe'], [['content','bus','near_site'], 'string'], [['name', 'create_user', 'update_user'], 'string', 'max' => 45], [['address', 'launch', 'organizers', 'join_teams'], 'string', 'max' => 50] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => '名称', 'category' => '分类', 'level_id' => '级别', 'recruit_count' => '招收人数', 'sign_up_begin_time' => '报名开始时间', 'sign_up_end_time' => '报名结束时间', 'sign_up_status' => '报名状态', 'begin_time' => '开始时间', 'end_time' => '结束时间', 'status' => '状态', 'lesson' => '课时', 'address' => '地址', 'score' => '活动积分', 'launch' => '发起者', 'organizers' => '主办方', 'join_teams' => '参训着', 'content' => '内容', 'bus' => '公交路线', 'near_site' => '周边站点', 'create_time' => '创建时间', 'create_user' => '创建人', 'update_time' => '更新时间', 'update_user' => '更新人', ]; } /** * @return \yii\db\ActiveQuery */ public function getLevel() { return $this->hasOne(Level::className(), ['id' => 'level_id']); } /** * @return \yii\db\ActiveQuery */ public function getActivityUsers() { return $this->hasMany(ActivityUsers::className(), ['activity_id' => 'id']); } public static function getAll() { $rows = (new \yii\db\Query()) ->select(['id', 'name']) ->from(self::tableName()) ->where(['status'=>'1']) ->all(); return $rows; } public static function getCategoryName($category) { return isset(self::$categoryList[$category]) ? self::$categoryList[$category] : $category; } public static function getSignUpStatusName($signUpStatus) { return isset(self::$signUpStatusList[$signUpStatus]) ? self::$signUpStatusList[$signUpStatus] : $signUpStatus; } public static function getStatusName($status) { return isset(self::$statusList[$status]) ? self::$statusList[$status] : $status; } public static function getOneActivityNameById($activityId) { $sql = "SELECT name FROM `activity` WHERE id='" . $activityId . "'"; $result = Yii::$app->db->createCommand($sql)->queryOne(); return $result['name']; } public function beforeSave($insert = '') { if (parent::beforeSave($this->isNewRecord)) { if ($this->isNewRecord) { $this->create_time = date('Y-m-d H:i:s', time()); $this->create_user = 'admin'; $this->update_time = date('Y-m-d H:i:s', time()); $this->update_user = 'admin'; } else { $this->update_time = date('Y-m-d H:i:s', time()); $this->update_user = 'admin'; } return true; } else { return false; } } }
true
0fd6ed1f77dbe0c992f76b3fb542f199cfdef076
PHP
JayDeeJaye/anaconda-jdj-f
/apis/apiHeader.php
UTF-8
947
2.796875
3
[]
no_license
<?php // Common exception handler, returns an error response with the message in it set_exception_handler(function ($e) { $code = $e->getCode() ?: 400; header("Content-Type: application/json", NULL, $code); echo json_encode(["error" => $e->getMessage()],JSON_PRETTY_PRINT); exit; }); // Get the request verb $verb = $_SERVER['REQUEST_METHOD']; // Get the api route keys from the url for GET, PUT, and DELETE switch($verb) { case 'GET': case 'PUT': case 'DELETE': //GET, PUT, and DELETE requests have the form api.php/target $my_path_info = str_replace($_SERVER['SCRIPT_NAME'],'',$_SERVER['REQUEST_URI']); $url_pieces = explode('/', $my_path_info); } // Get the data from the PUT and POST requests switch($verb) { case 'PUT': case 'POST': $params = json_decode(file_get_contents("php://input"), true); if(!$params) { throw new Exception("Data missing or invalid"); } }
true
673f1c6173757c3db81787284e7288497f6f10c2
PHP
andrii-androshchuk/api-framework
/framework/configuration/configuration.class.php
UTF-8
7,908
2.84375
3
[]
no_license
<?php /** * Configuration * * The class that alllows to work with configuration. * All of them are loads from .cgf file from app path. * * Public methods: * @method initialize(string : name of configuration's file); * @method get(string : key); * @method instance(); * @method loadFromArray(array : keys); * @method clearCache(); * * Note. How to create .cfg file * - each new parameter must starts from new line; * - each parameter and value must be splited by ' = ' (equal with spaced by sides); * - comments must starts with '#' (sharp); these lines woun't compile; (not ' #' or '*#', just '#' must be first symbol); * - the file must ends in '#end' line; * * Example: * * # Database * database_user = root * database_password = root * database_host = host * * # Language * # the string below 'en,de' Configuration's class will return as string. You will need to parse it by yourself. * available_languages = en,de * default_language = en * * #end * * If you'll have some troubles with configuration's file, we recommend to you before * loading of configuration, clear up the compiled files by Configuration::clearCache() method. * * * @author Androschuk Andriy <[email protected]> * @copyright 2013 (c) Androschuk Andriy * * @version 0.1 */ class Configuration { // Singletone private static $p_instance; // Files private $config_file_path; private $config_file_hash; private $php_config_file_path; // Parameters private $parameters = array(); private function __construct() {} /** * @name initialize * Load configurations. * * @param string : name of configuration's file */ public function initialize($configuration_name = "main") { $this->config_file_path = APPLICATION_CONFIGURATION_PATH . $configuration_name . ".cfg"; // The .cfg file doesn't exists if (!file_exists($this->config_file_path)) { Log::error("Not found .cfg file in path: $this->config_file_path", "Configuration"); } // Get hash of file $this->config_file_hash = md5_file($this->config_file_path); // Build path to .php configuration file $this->php_config_file_path = APPLICATION_CACHE_PATH . "configuration\\" . $this->config_file_hash . ".php"; // If file doesn't exists then create new if (!file_exists($this->php_config_file_path)) { Log::notice("Not found .php (compiled) configuration file in path: $this->php_config_file_path", "Configuration"); // Load data from .cfg file $file = file($this->config_file_path); if(count($file) == 0) { Log::notice("In configuration's file $this->config_file_path is not found keys", "Configuration"); return; } // Output string to .php configuration file $configuration_str = '<?php $configuration_array = array('; // Connection name (temp value) $connection_name = ""; // Prase each of line from .cfg file foreach ( $file as $line ) { if( $line[0] == "#" || trim($line) == "") continue; $parameter = explode(" = ", $line); $key = $parameter[0]; $value = substr($parameter[1], 0, strlen($parameter[1]) - 2); // Exception for connection if($key === "connection_name") { $connection_name = $value; continue; } // Replace connection_user to local_connection_user (added name before key name) if(substr($key, 0, 11) === "connection_") { $key = $connection_name . "_" . $key; } $configuration_str = $configuration_str . "'$key'=>'$value',"; } unset($connection_name); unset($file); // Delete last coma & space in array list $configuration_str = substr($configuration_str, 0, strlen($configuration_str) - 1); $configuration_str .= '); Configuration::instance()->loadFromArray($configuration_array);'; // Put it into .php file file_put_contents($this->php_config_file_path, $configuration_str); Log::success("Created new configuration .php file: $this->php_config_file_path", "Configuration"); // Find and delete previous file of configuration from cache $files = scandir(APPLICATION_CACHE_PATH . "configuration"); foreach ($files as $file) { if(!in_array($file, array(".", "..", ".svn", $this->config_file_hash . ".php"))) { unlink(APPLICATION_CACHE_PATH . "configuration\\" . $file); Log::success("Deleted cache configuration file: " . APPLICATION_CACHE_PATH . "configuration\\" . $file, "Configuration"); } } unset($files); } // Loading configuration require_once $this->php_config_file_path; } /** * @name instance * Singletone function. * * @return instance of itself */ public static function instance() { if(!self::$p_instance) { self::$p_instance = new self(); } return self::$p_instance; } /** * @name get * The function returns value of configuration parameter. * * @param string : name of configuration key * @return value of it. */ public function _get($_key) { if(!isset($this->parameters[$_key])) { Log::error("Unknow configuration key: $_key", "Configuration"); } // If parameter is boolean the return is as boolean type. switch($this->parameters[$_key]) { case "true": { return true; } break; case "false": { return false; } break; default: { return $this->parameters[$_key]; } break; } } /** * @name loadFromArray * The function that takes parameters from array and puts it into private array. * * @param array : array of parameters */ public function loadFromArray($_arr) { $this->parameters = $_arr; Log::success("Configuration loaded from file: $this->php_config_file_path", "Configuration"); Log::success("Configuration keys count:" . count($this->parameters), "Configuration"); } /** * @name get * The function return value of paramter * * @param string : name of parameter */ public static function get($n) { return self::instance()->_get($n); } /** * @name clearCache * The function make clean up in cache directory */ public static function clearCache() { $files = scandir(APPLICATION_CACHE_PATH . "configuration"); // delete '.' & '..' unset($files[0]); unset($files[1]); foreach ($files as $file) {unlink(APPLICATION_CACHE_PATH . "configuration\\" . $file); Log::success("Deleted cache configuration file: " . APPLICATION_CACHE_PATH . "configuration\\" . $file, "Configuration"); } } }
true
cc2cb4e911a729be112a191245f99d677d7e1800
PHP
savalonso/SEVRI
/controladora/ctrUsuarios.php
UTF-8
3,286
2.734375
3
[]
no_license
<?php header("Content-Type: text/html; charset=iso-8859-1"); class ctrUsuarios { function ctrUsuarios(){} function insertarUsuarios(){ include_once ("../dominio/dUsuario.php"); include_once ("../data/dtUsuario.php"); $usuario = new dUsuario; $usuario->setCedula($_POST['cedula']); $usuario->setNombre($_POST['nombre']); $usuario->setPrimerApellido($_POST['primerApellido']); $usuario->setSegundoApellido($_POST['segundoApellido']); $usuario->setTelefono($_POST['telefono']); $usuario->setCorreo($_POST['email']); $usuario->setClave($_POST['clave']); $usuario->setCargo($_POST['cargo']); $usuario->setTipo($_POST['tipo']); $dataUsuarios = new dtUsuario; if($dataUsuarios->insertarUsuario($usuario) == true){ echo 'Se ha insertado correctamente el usuario.'; } else { echo 'No se ha insertado el usuario.'; } } function actualizarUsuarios(){ include_once ("../dominio/dUsuario.php"); include_once ("../data/dtUsuario.php"); $usuario = new dUsuario(); $usuario->setNombre($_POST['nombre']); $usuario->setPrimerApellido($_POST['primerApellido']); $usuario->setSegundoApellido($_POST['segundoApellido']); $usuario->setTelefono($_POST['telefono']); $usuario->setCorreo($_POST['email']); $usuario->setClave($_POST['clave']); $usuario->setCargo($_POST['cargo']); $usuario->setTipo($_POST['tipo']); $cedula = $_POST['cedula']; $dataUsuario = new dtUsuario(); if($dataUsuario->actualizarUsuario($usuario,$cedula) == true){ echo 'Se ha modificado correctamente el usuario.'; } else { echo 'No se ha modificado el usuario.'; } } function eliminarUsuarios(){ include_once ("../dominio/dUsuario.php"); include_once ("../data/dtUsuario.php"); $cedula = $_POST['cedula']; $dataUsuarios = new dtUsuario; if($dataUsuarios->eliminarUsuarios($cedula) == true){ echo 'Se ha eliminado correctamente el usuario.'; } else { echo 'No se ha eliminado el usuario.'; } } function marcarMensajeLeido(){ include_once ("../logica/logicaUsuario.php"); $idMensaje = $_POST['idMensaje']; $logica = new logicaUsuario; $logica->marcarMensajeLeido($idMensaje); echo "true"; } function contarMensajesNoLeidos(){ include_once ("../logica/logicaUsuario.php"); $idUsuario = $_POST['cedula']; $logica = new logicaUsuario; $cantidadMensajes = $logica->contarMensajesNuevos($idUsuario); echo $cantidadMensajes; } function ExisteUsuario(){ include_once ("../logica/logicaUsuario.php"); $usuario = $_POST['usuario']; $clave = $_POST['clave']; $logica = new logicaUsuario; $datos = $logica->ObtenerDatosUsuario($usuario,$clave); $datos = ctrUsuarios::Convertir_UTF8($datos); echo "".json_encode($datos).""; } function Convertir_UTF8($array){ foreach ($array as $key => $value) { $array[$key] = utf8_encode($value); } return $array; } } $op = $_POST['opcion']; $control = new ctrUsuarios; if($op == 1){ $control->insertarUsuarios(); } else if($op == 2){ $control->actualizarUsuarios(); } else if($op == 3){ $control->eliminarUsuarios(); } else if($op == 4){ $control->contarMensajesNoLeidos(); } else if($op == 5){ $control->marcarMensajeLeido(); } else if($op == 6){ $control->ExisteUsuario(); } ?>
true
970098632fbc6a98a0737868a77674a717fe5547
PHP
fdask/nottingham
/src/Player.class.php
UTF-8
4,372
3.40625
3
[]
no_license
<?php namespace fdask\Sheriff; /* * represents a player in the game **/ class Player { /** constants to identify which player deck one might want to access **/ const DECK_HAND = 'deckhand'; const DECK_PUBLICSTAND = 'deckpublicstand'; const DECK_HIDDENSTAND = 'deckhiddenstand'; /** @var string the name of the player **/ public $name = null; /** @var integer the players gold **/ public $gold = null; /** @var Deck representing the cards in a players hand **/ public $cardHand = null; /** @var Deck representing the cards in the players public market stand **/ public $cardPublicStand = null; /** @var Deck representing the cards in the players hidden market stand **/ public $cardHiddenStand = null; /** @var Deck an extra hand of cards used for various purposes **/ public $cardAux = null; /** @var boolean indicating the player has finished their turn **/ public $doneTurn = null; /** * initializes a new player! **/ public function __construct() { $this->cardHand = new Deck(); $this->cardHand->setName("Hand"); $this->cardHand->setState(Card::STATE_FACEDOWN); $this->cardPublicStand = new Deck(); $this->cardPublicStand->setName("Market stand"); $this->cardPublicStand->setState(Card::STATE_FACEUP); $this->cardHiddenStand = new Deck(); $this->cardHiddenStand->setName("Contraband Stash"); $this->cardHiddenStand->setState(Card::STATE_FACEDOWN); $this->cardAux = new Deck(); $this->cardAux->setName("Aux Deck"); $this->cardAux->setState(Card::STATE_FACEDOWN); } /** * returns a string representation of the player * * @return string **/ public function __toString() { $ret = $this->getName() . " [" . $this->getGold() . "]"; if ($this->getDoneTurn()) { $ret .= " - DONE"; } $ret .= "\n"; $ret .= $this->getCardHand() . "\n"; $ret .= $this->getCardPublicStand() . "\n"; $ret .= $this->getCardHiddenStand() . "\n"; if (count($this->getCardAux()) > 0) { $ret .= $this->getCardAux() . "\n"; } return $ret; } /** * sets the name property * * @param string $name **/ public function setName($name) { $this->name = $name; } /** * returns the name property * * @return string **/ public function getName() { return $this->name; } /** * sets the gold property * * @param integer $gold **/ public function setGold($gold) { $this->gold = $gold; } /** * adds an amount to the gold property * * @param integer $amount * @return integer the new gold count **/ public function addGold($amount) { $this->gold += $amount; return $this->gold; } /** * removes an amount from the gold property * * @param integer $amount * @return integer the new gold **/ public function removeGold($amount) { // don't let the level fall below 1! $this->gold = (($this->gold - $amount) >= 0) ? ($this->gold - $amount) : 0; return $this->gold; } /** * returns the gold property * * @return integer **/ public function getGold() { return $this->gold; } /** * sets the cardHand property * * @param Deck $deck **/ public function setCardHand(Deck $deck) { $this->cardHand = $deck; } /** * gets the cardHand property * * @return Deck **/ public function getCardHand() { return $this->cardHand; } /** * sets the cardPublicStand property * * @param Deck $deck **/ public function setCardPublicStand(Deck $deck) { $this->cardPublicStand = $deck; } /** * gets the cardPublicStand property * * @return Deck **/ public function getCardPublicStand() { return $this->cardPublicStand; } /** * sets the cardHiddenStand property * * @param Deck $deck **/ public function setCardHiddenStand(Deck $deck) { $this->cardHiddenStand = $deck; } /** * gets the cardHiddenStand property * * @return Deck **/ public function getCardHiddenStand() { return $this->cardHiddenStand; } /** * sets the cardAux property * * @param Deck $deck **/ public function setCardAux(Deck $deck) { $this->cardAux = $deck; } /** * gets the cardAux property * * @return Deck **/ public function getCardAux() { return $this->cardAux; } /** * sets the doneTurn property * * @param boolean $bool **/ public function setDoneTurn($bool) { $this->doneTurn = $bool; } /** * gets the doneTurn property * * @return boolean **/ public function getDoneTurn() { return $this->doneTurn; } }
true
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
135
Size of downloaded dataset files:
11.7 GB
Size of the auto-converted Parquet files:
11.7 GB
Number of rows:
9,914,478