_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q14400 | WhatsProt.debugPrint | train | public function debugPrint($debugMsg)
{
if ($this->debug) {
if (is_array($debugMsg) || is_object($debugMsg)) {
print_r($debugMsg);
} else {
echo $debugMsg;
}
return true;
}
return false;
} | php | {
"resource": ""
} |
q14401 | WhatsProt.isLoggedIn | train | public function isLoggedIn()
{
//If you aren't connected you can't be logged in! ($this->isConnected())
//We are connected - but are we logged in? (the rest)
return $this->isConnected() && !empty($this->loginStatus) && $this->loginStatus === Constants::CONNECTED_STATUS;
} | php | {
"resource": ""
} |
q14402 | WhatsProt.getMediaFile | train | protected function getMediaFile($filepath, $maxsizebytes = 5242880)
{
if (filter_var($filepath, FILTER_VALIDATE_URL) !== false) {
$this->mediaFileInfo = [];
$this->mediaFileInfo['url'] = $filepath;
$media = file_get_contents($filepath);
$this->mediaFileInfo['filesize'] = strlen($media);
if ($this->mediaFileInfo['filesize'] < $maxsizebytes) {
$this->mediaFileInfo['filepath'] = tempnam($this->dataFolder.Constants::MEDIA_FOLDER, 'WHA');
file_put_contents($this->mediaFileInfo['filepath'], $media);
$this->mediaFileInfo['filemimetype'] = get_mime($this->mediaFileInfo['filepath']);
$this->mediaFileInfo['fileextension'] = getExtensionFromMime($this->mediaFileInfo['filemimetype']);
return true;
} else {
return false;
}
} elseif (file_exists($filepath)) {
//Local file
$this->mediaFileInfo['filesize'] = filesize($filepath);
if ($this->mediaFileInfo['filesize'] < $maxsizebytes) {
$this->mediaFileInfo['filepath'] = $filepath;
$this->mediaFileInfo['fileextension'] = pathinfo($filepath, PATHINFO_EXTENSION);
$this->mediaFileInfo['filemimetype'] = get_mime($filepath);
return true;
} else {
return false;
}
}
return false;
} | php | {
"resource": ""
} |
q14403 | WhatsProt.processInboundData | train | protected function processInboundData($data)
{
$node = $this->reader->nextTree($data);
if ($node != null) {
$this->processInboundDataNode($node);
}
} | php | {
"resource": ""
} |
q14404 | WhatsProt.processMediaImage | train | protected function processMediaImage($node)
{
$media = $node->getChild('media');
if ($media != null) {
$filename = $media->getAttribute('file');
$url = $media->getAttribute('url');
//save thumbnail
file_put_contents($this->dataFolder.Constants::MEDIA_FOLDER.DIRECTORY_SEPARATOR.'thumb_'.$filename, $media->getData());
//download and save original
file_put_contents($this->dataFolder.Constants::MEDIA_FOLDER.DIRECTORY_SEPARATOR.$filename, file_get_contents($url));
}
} | php | {
"resource": ""
} |
q14405 | WhatsProt.processProfilePicture | train | protected function processProfilePicture($node)
{
$pictureNode = $node->getChild('picture');
if ($pictureNode != null) {
if ($pictureNode->getAttribute('type') == 'preview') {
$filename = $this->dataFolder.Constants::PICTURES_FOLDER.DIRECTORY_SEPARATOR.'preview_'.$node->getAttribute('from').'jpg';
} else {
$filename = $this->dataFolder.Constants::PICTURES_FOLDER.DIRECTORY_SEPARATOR.$node->getAttribute('from').'.jpg';
}
file_put_contents($filename, $pictureNode->getData());
}
} | php | {
"resource": ""
} |
q14406 | WhatsProt.processTempMediaFile | train | protected function processTempMediaFile($storeURLmedia)
{
if (!isset($this->mediaFileInfo['url'])) {
return false;
}
if ($storeURLmedia && is_file($this->mediaFileInfo['filepath'])) {
rename($this->mediaFileInfo['filepath'], $this->mediaFileInfo['filepath'].'.'.$this->mediaFileInfo['fileextension']);
} elseif (is_file($this->mediaFileInfo['filepath'])) {
unlink($this->mediaFileInfo['filepath']);
}
} | php | {
"resource": ""
} |
q14407 | WhatsProt.readStanza | train | public function readStanza()
{
$buff = '';
if ($this->isConnected()) {
$header = @socket_read($this->socket, 3); //read stanza header
// if($header !== false && strlen($header) > 1){
if ($header === false) {
$this->eventManager()->fire('onClose',
[
$this->phoneNumber,
'Socket EOF',
]
);
}
if (strlen($header) == 0) {
//no data received
return;
}
if (strlen($header) != 3) {
throw new ConnectionException('Failed to read stanza header');
}
$treeLength = (ord($header[0]) & 0x0F) << 16;
$treeLength |= ord($header[1]) << 8;
$treeLength |= ord($header[2]) << 0;
//read full length
$buff = socket_read($this->socket, $treeLength);
//$trlen = $treeLength;
$len = strlen($buff);
//$prev = 0;
while (strlen($buff) < $treeLength) {
$toRead = $treeLength - strlen($buff);
$buff .= socket_read($this->socket, $toRead);
if ($len == strlen($buff)) {
//no new data read, fuck it
break;
}
$len = strlen($buff);
}
if (strlen($buff) != $treeLength) {
throw new ConnectionException('Tree length did not match received length (buff = '.strlen($buff)." & treeLength = $treeLength)");
}
$buff = $header.$buff;
}
return $buff;
} | php | {
"resource": ""
} |
q14408 | WhatsProt.sendCheckAndSendMedia | train | protected function sendCheckAndSendMedia($filepath, $maxSize, $to, $type, $allowedExtensions, $storeURLmedia, $caption = '')
{
if ($this->getMediaFile($filepath, $maxSize) == true) {
if (in_array(strtolower($this->mediaFileInfo['fileextension']), $allowedExtensions)) {
$b64hash = base64_encode(hash_file('sha256', $this->mediaFileInfo['filepath'], true));
//request upload and get Message ID
$id = $this->sendRequestFileUpload($b64hash, $type, $this->mediaFileInfo['filesize'], $this->mediaFileInfo['filepath'], $to, $caption);
$this->processTempMediaFile($storeURLmedia);
// Return message ID. Make pull request for this.
return $id;
} else {
//Not allowed file type.
$this->processTempMediaFile($storeURLmedia);
return;
}
} else {
//Didn't get media file details.
return;
}
} | php | {
"resource": ""
} |
q14409 | WhatsProt.sendBroadcast | train | protected function sendBroadcast($targets, $node, $type)
{
if (!is_array($targets)) {
$targets = [$targets];
}
$toNodes = [];
foreach ($targets as $target) {
$jid = $this->getJID($target);
$hash = ['jid' => $jid];
$toNode = new ProtocolNode('to', $hash, null, null);
$toNodes[] = $toNode;
}
$broadcastNode = new ProtocolNode('broadcast', null, $toNodes, null);
$msgId = $this->createMsgId();
$messageNode = new ProtocolNode('message',
[
'to' => time().'@broadcast',
'type' => $type,
'id' => $msgId,
], [$node, $broadcastNode], null);
$this->sendNode($messageNode);
$this->waitForServer($msgId);
//listen for response
$this->eventManager()->fire('onSendMessage',
[
$this->phoneNumber,
$targets,
$msgId,
$node,
]);
return $msgId;
} | php | {
"resource": ""
} |
q14410 | WhatsProt.sendData | train | public function sendData($data)
{
if ($this->isConnected()) {
if (socket_write($this->socket, $data, strlen($data)) === false) {
$this->eventManager()->fire('onClose',
[
$this->phoneNumber,
'Connection closed!',
]
);
}
}
} | php | {
"resource": ""
} |
q14411 | WhatsProt.sendGetGroupsFiltered | train | protected function sendGetGroupsFiltered($type)
{
$msgID = $this->nodeId['getgroups'] = $this->createIqId();
$child = new ProtocolNode($type, null, null, null);
$node = new ProtocolNode('iq',
[
'id' => $msgID,
'type' => 'get',
'xmlns' => 'w:g2',
'to' => Constants::WHATSAPP_GROUP_SERVER,
], [$child], null);
$this->sendNode($node);
} | php | {
"resource": ""
} |
q14412 | WhatsProt.sendGroupsChangeParticipants | train | protected function sendGroupsChangeParticipants($groupId, $participant, $tag, $id)
{
$participants = new ProtocolNode('participant', ['jid' => $this->getJID($participant)], null, '');
$childHash = [];
$child = new ProtocolNode($tag, $childHash, [$participants], '');
$node = new ProtocolNode('iq',
[
'id' => $id,
'type' => 'set',
'xmlns' => 'w:g2',
'to' => $this->getJID($groupId),
], [$child], '');
$this->sendNode($node);
} | php | {
"resource": ""
} |
q14413 | WhatsProt.sendMessageNode | train | protected function sendMessageNode($to, $node, $id = null, $plaintextNode = null)
{
$msgId = ($id == null) ? $this->createMsgId() : $id;
$to = $this->getJID($to);
if ($node->getTag() == 'body' || $node->getTag() == 'enc') {
$type = 'text';
} else {
$type = 'media';
}
$messageNode = new ProtocolNode('message', [
'to' => $to,
'type' => $type,
'id' => $msgId,
't' => time(),
'notify' => $this->name,
], [$node], '');
$this->sendNode($messageNode);
if ($node->getTag() == 'enc') {
$node = $plaintextNode;
}
$this->logFile('info', '{type} message with id {id} sent to {to}', ['type' => $type, 'id' => $msgId, 'to' => ExtractNumber($to)]);
$this->eventManager()->fire('onSendMessage',
[
$this->phoneNumber,
$to,
$msgId,
$node,
]);
// $this->waitForServer($msgId);
return $msgId;
} | php | {
"resource": ""
} |
q14414 | WhatsProt.sendReceipt | train | public function sendReceipt($node, $type = 'read', $participant = null, $callId = null)
{
$messageHash = [];
if ($type == 'read') {
$messageHash['type'] = $type;
}
if ($participant != null) {
$messageHash['participant'] = $participant;
}
$messageHash['to'] = $node->getAttribute('from');
$messageHash['id'] = $node->getAttribute('id');
$messageHash['t'] = $node->getAttribute('t');
if ($callId != null) {
$offerNode = new ProtocolNode('offer', ['call-id' => $callId], null, null);
$messageNode = new ProtocolNode('receipt', $messageHash, [$offerNode], null);
} else {
$messageNode = new ProtocolNode('receipt', $messageHash, null, null);
}
$this->sendNode($messageNode);
$this->eventManager()->fire('onSendMessageReceived',
[
$this->phoneNumber,
$node->getAttribute('id'),
$node->getAttribute('from'),
$type,
]);
} | php | {
"resource": ""
} |
q14415 | WhatsProt.sendMessageRead | train | public function sendMessageRead($to, $id)
{
$listNode = null;
$idNode = $id;
if (is_array($id) && count($id > 1)) {
$idNode = array_shift($id);
foreach ($id as $itemId) {
$items[] = new ProtocolNode('item',
[
'id' => $itemId,
], null, null);
}
$listNode = new ProtocolNode('list', null, $items, null);
}
$messageNode = new ProtocolNode('receipt',
[
'type' => 'read',
't' => time(),
'to' => $this->getJID($to),
'id' => $idNode,
], [$listNode], null);
$this->sendNode($messageNode);
} | php | {
"resource": ""
} |
q14416 | WhatsProt.sendNode | train | public function sendNode($node, $encrypt = true)
{
$this->timeout = time();
$this->debugPrint($node->nodeString('tx ')."\n");
$this->sendData($this->writer->write($node, $encrypt));
} | php | {
"resource": ""
} |
q14417 | WhatsProt.sendRequestFileUpload | train | protected function sendRequestFileUpload($b64hash, $type, $size, $filepath, $to, $caption = '')
{
$id = $this->createIqId();
if (!is_array($to)) {
$to = $this->getJID($to);
}
$mediaNode = new ProtocolNode('media', [
'hash' => $b64hash,
'type' => $type,
'size' => $size,
], null, null);
$node = new ProtocolNode('iq', [
'id' => $id,
'to' => Constants::WHATSAPP_SERVER,
'type' => 'set',
'xmlns' => 'w:m',
], [$mediaNode], null);
//add to queue
$messageId = $this->createMsgId();
$this->mediaQueue[$id] = [
'messageNode' => $node,
'filePath' => $filepath,
'to' => $to,
'message_id' => $messageId,
'caption' => $caption,
];
$this->sendNode($node);
$this->waitForServer($id);
// Return message ID. Make pull request for this.
return $messageId;
} | php | {
"resource": ""
} |
q14418 | WhatsProt.sendSetPicture | train | protected function sendSetPicture($jid, $filepath)
{
$nodeID = $this->createIqId();
$data = preprocessProfilePicture($filepath);
$preview = createIconGD($filepath, 96, true);
$picture = new ProtocolNode('picture', ['type' => 'image'], null, $data);
$preview = new ProtocolNode('picture', ['type' => 'preview'], null, $preview);
$node = new ProtocolNode('iq', [
'id' => $nodeID,
'to' => $this->getJID($jid),
'type' => 'set',
'xmlns' => 'w:profile:picture',
], [$picture, $preview], null);
$this->sendNode($node);
} | php | {
"resource": ""
} |
q14419 | ProtocolNode.isCli | train | private static function isCli()
{
if (self::$cli === null) {
//initial setter
if (php_sapi_name() == 'cli') {
self::$cli = true;
} else {
self::$cli = false;
}
}
return self::$cli;
} | php | {
"resource": ""
} |
q14420 | Login.doLogin | train | public function doLogin()
{
if ($this->parent->isLoggedIn()) {
return true;
}
$this->parent->writer->resetKey();
$this->parent->reader->resetKey();
$resource = Constants::PLATFORM.'-'.Constants::WHATSAPP_VER;
$data = $this->parent->writer->StartStream(Constants::WHATSAPP_SERVER, $resource);
$feat = $this->createFeaturesNode();
$auth = $this->createAuthNode();
$this->parent->sendData($data);
$this->parent->sendNode($feat);
$this->parent->sendNode($auth);
$this->parent->pollMessage();
$this->parent->pollMessage();
$this->parent->pollMessage();
if ($this->parent->getChallengeData() != null) {
$data = $this->createAuthResponseNode();
$this->parent->sendNode($data);
$this->parent->reader->setKey($this->inputKey);
$this->parent->writer->setKey($this->outputKey);
while (!$this->parent->pollMessage()) {
};
}
if ($this->parent->getLoginStatus() === Constants::DISCONNECTED_STATUS) {
throw new LoginFailureException();
}
$this->parent->logFile('info', '{number} successfully logged in', ['number' => $this->phoneNumber]);
$this->parent->sendAvailableForChat();
$this->parent->sendGetPrivacyBlockedList();
$this->parent->sendGetClientConfig();
$this->parent->setMessageId(substr(bin2hex(mcrypt_create_iv(64, MCRYPT_DEV_URANDOM)), 0, 22)); // 11 char hex
if (extension_loaded('curve25519') || extension_loaded('protobuf')) {
if (file_exists($this->parent->dataFolder.'axolotl-'.$this->phoneNumber.'.db')) {
$pre_keys = $this->parent->getAxolotlStore()->loadPreKeys();
if (empty($pre_keys)) {
$this->parent->sendSetPreKeys();
$this->parent->logFile('info', 'Sending prekeys to WA server');
}
}
}
return true;
} | php | {
"resource": ""
} |
q14421 | Login.createAuthNode | train | protected function createAuthNode()
{
$data = $this->createAuthBlob();
$attributes = [
'user' => $this->phoneNumber,
'mechanism' => 'WAUTH-2',
];
$node = new ProtocolNode('auth', $attributes, null, $data);
return $node;
} | php | {
"resource": ""
} |
q14422 | Login.authenticate | train | protected function authenticate()
{
$keys = KeyStream::GenerateKeys(base64_decode($this->password), $this->parent->getChallengeData());
$this->inputKey = new KeyStream($keys[2], $keys[3]);
$this->outputKey = new KeyStream($keys[0], $keys[1]);
$array = "\0\0\0\0".$this->phoneNumber.$this->parent->getChallengeData().''.time().'000'.hex2bin('00').'000'.hex2bin('00')
.Constants::OS_VERSION.hex2bin('00').Constants::MANUFACTURER.hex2bin('00').Constants::DEVICE.hex2bin('00').Constants::BUILD_VERSION;
$response = $this->outputKey->EncodeMessage($array, 0, 4, strlen($array) - 4);
$this->parent->setOutputKey($this->outputKey);
return $response;
} | php | {
"resource": ""
} |
q14423 | vCard.set | train | public function set($key, $value)
{
// Check if the specified property is defined.
if (property_exists($this, $key) && $key != 'data') {
$this->{$key} = trim($value);
return $this;
} elseif (property_exists($this, $key) && $key == 'data') {
foreach ($value as $v_key => $v_value) {
$this->{$key}[$v_key] = trim($v_value);
}
return $this;
} else {
return false;
}
} | php | {
"resource": ""
} |
q14424 | Whatsapp.cleanPostInputs | train | private function cleanPostInputs()
{
$args = [
'action' => FILTER_SANITIZE_STRING,
'password' => FILTER_SANITIZE_STRING,
'from' => FILTER_SANITIZE_STRING,
'to' => [
'filter' => FILTER_SANITIZE_NUMBER_INT,
'flags' => FILTER_REQUIRE_ARRAY,
],
'message' => FILTER_UNSAFE_RAW,
'image' => FILTER_VALIDATE_URL,
'audio' => FILTER_VALIDATE_URL,
'video' => FILTER_VALIDATE_URL,
'locationname' => FILTER_SANITIZE_STRING,
'status' => FILTER_SANITIZE_STRING,
'userlat' => FILTER_SANITIZE_STRING,
'userlong' => FILTER_SANITIZE_STRING,
];
$myinputs = filter_input_array(INPUT_POST, $args);
if (!$myinputs) {
throw Exception('Problem Filtering the inputs');
}
return $myinputs;
} | php | {
"resource": ""
} |
q14425 | Whatsapp.process | train | public function process()
{
switch ($this->inputs['action']) {
case 'login':
$this->webLogin();
break;
case 'logout':
$this->webLogout();
exit($this->showWebLoginForm());
break;
case 'getContacts':
$this->getContacts();
break;
case 'updateStatus':
$this->updateStatus();
break;
case 'sendMessage':
$this->sendMessage();
break;
case 'sendBroadcast':
$this->sendBroadcast();
break;
default:
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) {
exit($this->showWebForm());
}
exit($this->showWebLoginForm());
break;
}
} | php | {
"resource": ""
} |
q14426 | Whatsapp.getContacts | train | private function getContacts()
{
try {
//Get whatsapp's Groups this user belongs to.
$this->waGroupList = [];
$this->getGroupList();
if (is_array($this->waGroupList)) {
$this->contacts = array_merge($this->contacts, $this->waGroupList);
}
//Get contacts from google if gmail account configured.
$googleContacts = [];
if (isset($this->config[$this->from]['email'])) {
$email = $this->config[$this->from]['email'];
if (stripos($email, 'gmail') !== false || stripos($email, 'googlemail') !== false) {
$google = new GoogleContacts();
$googleContacts = $google->getContacts($this->config, $this->from);
if (is_array($googleContacts)) {
$this->contacts = array_merge($this->contacts, $googleContacts);
}
}
}
if (isset($this->contacts)) {
exit(json_encode([
'success' => true,
'type' => 'contacts',
'data' => $this->contacts,
'messages' => $this->messages,
]));
}
} catch (Exception $e) {
exit(json_encode([
'success' => false,
'type' => 'contacts',
'errormsg' => $e->getMessage(),
]));
}
} | php | {
"resource": ""
} |
q14427 | Whatsapp.connectToWhatsApp | train | private function connectToWhatsApp()
{
if (isset($this->wa)) {
$this->wa->connect();
$this->wa->loginWithPassword($this->password);
return true;
}
return false;
} | php | {
"resource": ""
} |
q14428 | Whatsapp.processReceivedMessage | train | public function processReceivedMessage($phone, $from, $id, $type, $time, $name, $data)
{
$matches = null;
$time = date('Y-m-d H:i:s', $time);
if (preg_match('/\d*/', $from, $matches)) {
$from = $matches[0];
}
$this->messages[] = ['phone' => $phone, 'from' => $from, 'id' => $id, 'type' => $type, 'time' => $time, 'name' => $name, 'data' => $data];
} | php | {
"resource": ""
} |
q14429 | Whatsapp.processGroupArray | train | public function processGroupArray($phone, $groupArray)
{
$formattedGroups = [];
if (!empty($groupArray)) {
foreach ($groupArray as $group) {
$formattedGroups[] = ['name' => 'GROUP: '.$group['subject'], 'id' => $group['id']];
}
$this->waGroupList = $formattedGroups;
return true;
}
return false;
} | php | {
"resource": ""
} |
q14430 | Whatsapp.updateStatus | train | private function updateStatus()
{
if (isset($this->inputs['status']) && trim($this->inputs['status']) !== '') {
$this->connectToWhatsApp();
$this->wa->sendStatusUpdate($this->inputs['status']);
exit(json_encode([
'success' => true,
'data' => "<br />Your status was updated to - <b>{$this->inputs['status']}</b>",
'messages' => $this->messages,
]));
} else {
exit(json_encode([
'success' => false,
'errormsg' => 'There was no text in the submitted status box!',
]));
}
} | php | {
"resource": ""
} |
q14431 | Whatsapp.sendMessage | train | private function sendMessage()
{
if (is_array($this->inputs['to'])) {
$this->connectToWhatsApp();
foreach ($this->inputs['to'] as $to) {
if (trim($to) !== '') {
if (isset($this->inputs['message']) && trim($this->inputs['message'] !== '')) {
$this->wa->sendMessageComposing($to);
$this->wa->sendMessage($to, $this->inputs['message']);
}
if (isset($this->inputs['image']) && $this->inputs['image'] !== false) {
$this->wa->sendMessageImage($to, $this->inputs['image']);
}
if (isset($this->inputs['audio']) && $this->inputs['audio'] !== false) {
$this->wa->sendMessageAudio($to, $this->inputs['audio']);
}
if (isset($this->inputs['video']) && $this->inputs['video'] !== false) {
$this->wa->sendMessageVideo($to, $this->inputs['video']);
}
if (isset($this->inputs['locationname']) && trim($this->inputs['locationname'] !== '')) {
$this->wa->sendMessageLocation($to, $this->inputs['userlong'], $this->inputs['userlat'], $this->inputs['locationname'], null);
}
} else {
exit(json_encode([
'success' => false,
'errormsg' => 'A blank number was provided!',
'messages' => $this->messages,
]));
}
}
exit(json_encode([
'success' => true,
'data' => 'Message Sent!',
'messages' => $this->messages,
]));
}
exit(json_encode([
'success' => false,
'errormsg' => 'Provided numbers to send message to were not in valid format.',
]));
} | php | {
"resource": ""
} |
q14432 | Whatsapp.sendBroadcast | train | private function sendBroadcast()
{
if (isset($this->inputs['action']) && trim($this->inputs['action']) == 'sendBroadcast') {
$this->connectToWhatsApp();
if (isset($this->inputs['message']) && trim($this->inputs['message'] !== '')) {
$this->wa->sendBroadcastMessage($this->inputs['to'], $this->inputs['message']);
}
if (isset($this->inputs['image']) && $this->inputs['image'] !== false) {
$this->wa->sendBroadcastImage($this->inputs['to'], $this->inputs['image']);
}
if (isset($this->inputs['audio']) && $this->inputs['audio'] !== false) {
$this->wa->sendBroadcastAudio($this->inputs['to'], $this->inputs['audio']);
}
if (isset($this->inputs['video']) && $this->inputs['video'] !== false) {
$this->wa->sendBroadcastVideo($this->inputs['to'], $this->inputs['video']);
}
if (isset($this->inputs['locationname']) && trim($this->inputs['locationname'] !== '')) {
$this->wa->sendBroadcastPlace($this->inputs['to'], $this->inputs['userlong'], $this->inputs['userlat'], $this->inputs['locationname'], null);
}
exit(json_encode([
'success' => true,
'data' => 'Broadcast Message Sent!',
'messages' => $this->messages,
]));
}
} | php | {
"resource": ""
} |
q14433 | Whatsapp.webLogin | train | private function webLogin()
{
if ($this->inputs['password'] == $this->config['webpassword']) {
$_SESSION['logged_in'] = true;
exit($this->showWebForm());
} else {
$error = 'Sorry your password was incorrect.';
exit($this->showWebLoginForm($error));
}
} | php | {
"resource": ""
} |
q14434 | Registration.checkCredentials | train | public function checkCredentials()
{
if (!$phone = $this->dissectPhone()) {
throw new Exception('The provided phone number is not valid.');
}
$countryCode = ($phone['ISO3166'] != '') ? $phone['ISO3166'] : 'US';
$langCode = ($phone['ISO639'] != '') ? $phone['ISO639'] : 'en';
// Build the url.
$host = 'https://'.Constants::WHATSAPP_CHECK_HOST;
$query = [
'cc' => $phone['cc'],
'in' => $phone['phone'],
'lg' => $langCode,
'lc' => $countryCode,
'id' => $this->identity,
'mistyped' => '6',
'network_radio_type' => '1',
'simnum' => '1',
's' => '',
'copiedrc' => '1',
'hasinrc' => '1',
'rcmatch' => '1',
'pid' => mt_rand(100, 9999),
//'rchash' => hash('sha256', openssl_random_pseudo_bytes(20)),
//'anhash' => md5(openssl_random_pseudo_bytes(20)),
'extexist' => '1',
'extstate' => '1',
];
$this->debugPrint($query);
$response = $this->getResponse($host, $query);
$this->debugPrint($response);
if ($response->status != 'ok') {
$this->eventManager()->fire('onCredentialsBad',
[
$this->phoneNumber,
$response->status,
$response->reason,
]);
throw new Exception('There was a problem trying to request the code.');
} else {
$this->eventManager()->fire('onCredentialsGood',
[
$this->phoneNumber,
$response->login,
$response->pw,
$response->type,
$response->expiration,
$response->kind,
$response->price,
$response->cost,
$response->currency,
$response->price_expiration,
]);
}
return $response;
} | php | {
"resource": ""
} |
q14435 | Registration.codeRegister | train | public function codeRegister($code)
{
if (!$phone = $this->dissectPhone()) {
throw new Exception('The provided phone number is not valid.');
}
$code = str_replace('-', '', $code);
$countryCode = ($phone['ISO3166'] != '') ? $phone['ISO3166'] : 'US';
$langCode = ($phone['ISO639'] != '') ? $phone['ISO639'] : 'en';
// Build the url.
$host = 'https://'.Constants::WHATSAPP_REGISTER_HOST;
$query = [
'cc' => $phone['cc'],
'in' => $phone['phone'],
'lg' => $langCode,
'lc' => $countryCode,
'id' => $this->identity,
'mistyped' => '6',
'network_radio_type' => '1',
'simnum' => '1',
's' => '',
'copiedrc' => '1',
'hasinrc' => '1',
'rcmatch' => '1',
'pid' => mt_rand(100, 9999),
'rchash' => hash('sha256', openssl_random_pseudo_bytes(20)),
'anhash' => md5(openssl_random_pseudo_bytes(20)),
'extexist' => '1',
'extstate' => '1',
'code' => $code,
];
$this->debugPrint($query);
$response = $this->getResponse($host, $query);
$this->debugPrint($response);
if ($response->status != 'ok') {
$this->eventManager()->fire('onCodeRegisterFailed',
[
$this->phoneNumber,
$response->status,
$response->reason,
isset($response->retry_after) ? $response->retry_after : null,
]);
if ($response->reason == 'old_version') {
$this->update();
}
throw new Exception("An error occurred registering the registration code from WhatsApp. Reason: $response->reason");
} else {
$this->eventManager()->fire('onCodeRegister',
[
$this->phoneNumber,
$response->login,
$response->pw,
$response->type,
$response->expiration,
$response->kind,
$response->price,
$response->cost,
$response->currency,
$response->price_expiration,
]);
}
return $response;
} | php | {
"resource": ""
} |
q14436 | Registration.getResponse | train | protected function getResponse($host, $query)
{
// Build the url.
$url = $host.'?'.http_build_query($query);
// Open connection.
$ch = curl_init();
// Configure the connection.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, Constants::WHATSAPP_USER_AGENT);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: text/json']);
// This makes CURL accept any peer!
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Get the response.
$response = curl_exec($ch);
// Close the connection.
curl_close($ch);
return json_decode($response);
} | php | {
"resource": ""
} |
q14437 | Registration.dissectPhone | train | protected function dissectPhone()
{
if (($handle = fopen(dirname(__FILE__).'/countries.csv', 'rb')) !== false) {
while (($data = fgetcsv($handle, 1000)) !== false) {
if (strpos($this->phoneNumber, $data[1]) === 0) {
// Return the first appearance.
fclose($handle);
$mcc = explode('|', $data[2]);
$mcc = $mcc[0];
//hook:
//fix country code for North America
if ($data[1][0] == '1') {
$data[1] = '1';
}
$phone = [
'country' => $data[0],
'cc' => $data[1],
'phone' => substr($this->phoneNumber, strlen($data[1]), strlen($this->phoneNumber)),
'mcc' => $mcc,
'ISO3166' => @$data[3],
'ISO639' => @$data[4],
'mnc' => $data[5],
];
$this->eventManager()->fire('onDissectPhone',
[
$this->phoneNumber,
$phone['country'],
$phone['cc'],
$phone['phone'],
$phone['mcc'],
$phone['ISO3166'],
$phone['ISO639'],
$phone['mnc'],
]
);
return $phone;
}
}
fclose($handle);
}
$this->eventManager()->fire('onDissectPhoneFailed',
[
$this->phoneNumber,
]);
return false;
} | php | {
"resource": ""
} |
q14438 | Registration.detectMnc | train | protected function detectMnc($lc, $carrierName)
{
$fp = fopen(__DIR__.DIRECTORY_SEPARATOR.'networkinfo.csv', 'r');
$mnc = null;
while ($data = fgetcsv($fp, 0, ',')) {
if ($data[4] === $lc && $data[7] === $carrierName) {
$mnc = $data[2];
break;
}
}
if ($mnc == null) {
$mnc = '000';
}
fclose($fp);
return $mnc;
} | php | {
"resource": ""
} |
q14439 | Registration.buildIdentity | train | protected function buildIdentity($identity_file = false)
{
if ($identity_file === false) {
$identity_file = sprintf('%s%s%sid.%s.dat', __DIR__, DIRECTORY_SEPARATOR, Constants::DATA_FOLDER.DIRECTORY_SEPARATOR, $this->phoneNumber);
}
// Check if the provided is not a file but a directory
if (is_dir($identity_file)) {
$identity_file = sprintf('%s/id.%s.dat',
rtrim($identity_file, "/"),
$this->phoneNumber
);
}
if (is_readable($identity_file)) {
$data = urldecode(file_get_contents($identity_file));
$length = strlen($data);
if ($length == 20 || $length == 16) {
return $data;
}
}
$bytes = strtolower(openssl_random_pseudo_bytes(20));
if (file_put_contents($identity_file, urlencode($bytes)) === false) {
throw new Exception('Unable to write identity file to '.$identity_file);
}
return $bytes;
} | php | {
"resource": ""
} |
q14440 | Log.writeLog | train | public static function writeLog($priority, $tag, $msg) // [int priority, String tag, String msg]
{
$logger = AxolotlLoggerProvider::getProvider();
if (($logger != null)) {
$logger->log($priority, $tag, $msg);
}
} | php | {
"resource": ""
} |
q14441 | DataTableAbstract.rawColumns | train | public function rawColumns(array $columns, $merge = false)
{
if ($merge) {
$config = $this->config->get('datatables.columns');
$this->columnDef['raw'] = array_merge($config['raw'], $columns);
} else {
$this->columnDef['raw'] = $columns;
}
return $this;
} | php | {
"resource": ""
} |
q14442 | DataTableAbstract.with | train | public function with($key, $value = '')
{
if (is_array($key)) {
$this->appends = $key;
} elseif (is_callable($value)) {
$this->appends[$key] = value($value);
} else {
$this->appends[$key] = value($value);
}
return $this;
} | php | {
"resource": ""
} |
q14443 | DataTableAbstract.getColumnsDefinition | train | protected function getColumnsDefinition()
{
$config = $this->config->get('datatables.columns');
$allowed = ['excess', 'escape', 'raw', 'blacklist', 'whitelist'];
return array_replace_recursive(array_only($config, $allowed), $this->columnDef);
} | php | {
"resource": ""
} |
q14444 | DataTableAbstract.filter | train | public function filter(callable $callback, $globalSearch = false)
{
$this->autoFilter = $globalSearch;
$this->isFilterApplied = true;
$this->filterCallback = $callback;
return $this;
} | php | {
"resource": ""
} |
q14445 | DataTableAbstract.smartGlobalSearch | train | protected function smartGlobalSearch($keyword)
{
collect(explode(' ', $keyword))
->reject(function ($keyword) {
return trim($keyword) === '';
})
->each(function ($keyword) {
$this->globalSearch($keyword);
});
} | php | {
"resource": ""
} |
q14446 | DataTableAbstract.transform | train | protected function transform($results, $processed)
{
if (isset($this->transformer) && class_exists('Yajra\\DataTables\\Transformers\\FractalTransformer')) {
return app('datatables.transformer')->transform(
$results,
$this->transformer,
$this->serializer ?? null
);
}
return Helper::transform($processed);
} | php | {
"resource": ""
} |
q14447 | DataTableAbstract.processResults | train | protected function processResults($results, $object = false)
{
$processor = new DataProcessor(
$results,
$this->getColumnsDefinition(),
$this->templates,
$this->request->input('start')
);
return $processor->process($object);
} | php | {
"resource": ""
} |
q14448 | DataTableAbstract.errorResponse | train | protected function errorResponse(\Exception $exception)
{
$error = $this->config->get('datatables.error');
$debug = $this->config->get('app.debug');
if ($error === 'throw' || (! $error && ! $debug)) {
throw new Exception($exception->getMessage(), $code = 0, $exception);
}
$this->getLogger()->error($exception);
return new JsonResponse([
'draw' => (int) $this->request->input('draw'),
'recordsTotal' => $this->totalRecords,
'recordsFiltered' => 0,
'data' => [],
'error' => $error ? __($error) : "Exception Message:\n\n".$exception->getMessage(),
]);
} | php | {
"resource": ""
} |
q14449 | DataTableAbstract.getColumnNameByIndex | train | protected function getColumnNameByIndex($index)
{
$name = (isset($this->columns[$index]) && $this->columns[$index] != '*')
? $this->columns[$index] : $this->getPrimaryKeyName();
return in_array($name, $this->extraColumns, true) ? $this->getPrimaryKeyName() : $name;
} | php | {
"resource": ""
} |
q14450 | EloquentDataTable.addColumns | train | public function addColumns(array $names, $order = false)
{
foreach ($names as $name => $attribute) {
if (is_int($name)) {
$name = $attribute;
}
$this->addColumn($name, function ($model) use ($attribute) {
return $model->getAttribute($attribute);
}, is_int($order) ? $order++ : $order);
}
return $this;
} | php | {
"resource": ""
} |
q14451 | EloquentDataTable.resolveRelationColumn | train | protected function resolveRelationColumn($column)
{
$parts = explode('.', $column);
$columnName = array_pop($parts);
$relation = implode('.', $parts);
if ($this->isNotEagerLoaded($relation)) {
return $column;
}
return $this->joinEagerLoadedColumn($relation, $columnName);
} | php | {
"resource": ""
} |
q14452 | EloquentDataTable.isNotEagerLoaded | train | protected function isNotEagerLoaded($relation)
{
return ! $relation
|| ! array_key_exists($relation, $this->query->getEagerLoads())
|| $relation === $this->query->getModel()->getTable();
} | php | {
"resource": ""
} |
q14453 | DataTablesServiceProvider.boot | train | public function boot()
{
$engines = config('datatables.engines');
foreach ($engines as $engine => $class) {
$engine = camel_case($engine);
if (! method_exists(DataTables::class, $engine) && ! DataTables::hasMacro($engine)) {
DataTables::macro($engine, function () use ($class) {
if (! call_user_func_array([$class, 'canCreate'], func_get_args())) {
throw new \InvalidArgumentException();
}
return call_user_func_array([$class, 'create'], func_get_args());
});
}
}
} | php | {
"resource": ""
} |
q14454 | RowProcessor.rowValue | train | public function rowValue($attribute, $template)
{
if (! empty($template)) {
if (! is_callable($template) && Arr::get($this->data, $template)) {
$this->data[$attribute] = Arr::get($this->data, $template);
} else {
$this->data[$attribute] = Helper::compileContent($template, $this->data, $this->row);
}
}
return $this;
} | php | {
"resource": ""
} |
q14455 | RowProcessor.rowData | train | public function rowData($attribute, array $template)
{
if (count($template)) {
$this->data[$attribute] = [];
foreach ($template as $key => $value) {
$this->data[$attribute][$key] = Helper::compileContent($value, $this->data, $this->row);
}
}
return $this;
} | php | {
"resource": ""
} |
q14456 | Request.orderableColumns | train | public function orderableColumns()
{
if (! $this->isOrderable()) {
return [];
}
$orderable = [];
for ($i = 0, $c = count($this->request->input('order')); $i < $c; $i++) {
$order_col = (int) $this->request->input("order.$i.column");
$order_dir = strtolower($this->request->input("order.$i.dir")) === 'asc' ? 'asc' : 'desc';
if ($this->isColumnOrderable($order_col)) {
$orderable[] = ['column' => $order_col, 'direction' => $order_dir];
}
}
return $orderable;
} | php | {
"resource": ""
} |
q14457 | Request.searchableColumnIndex | train | public function searchableColumnIndex()
{
$searchable = [];
for ($i = 0, $c = count($this->request->input('columns')); $i < $c; $i++) {
if ($this->isColumnSearchable($i, false)) {
$searchable[] = $i;
}
}
return $searchable;
} | php | {
"resource": ""
} |
q14458 | Request.isColumnSearchable | train | public function isColumnSearchable($i, $column_search = true)
{
if ($column_search) {
return
(
$this->request->input("columns.$i.searchable", 'true') === 'true'
||
$this->request->input("columns.$i.searchable", 'true') === true
)
&& $this->columnKeyword($i) != '';
}
return
$this->request->input("columns.$i.searchable", 'true') === 'true'
||
$this->request->input("columns.$i.searchable", 'true') === true;
} | php | {
"resource": ""
} |
q14459 | Request.columnName | train | public function columnName($i)
{
$column = $this->request->input("columns.$i");
return isset($column['name']) && $column['name'] != '' ? $column['name'] : $column['data'];
} | php | {
"resource": ""
} |
q14460 | Request.isPaginationable | train | public function isPaginationable()
{
return ! is_null($this->request->input('start')) &&
! is_null($this->request->input('length')) &&
$this->request->input('length') != -1;
} | php | {
"resource": ""
} |
q14461 | CollectionDataTable.create | train | public static function create($source)
{
if (is_array($source)) {
$source = new Collection($source);
}
return parent::create($source);
} | php | {
"resource": ""
} |
q14462 | CollectionDataTable.count | train | public function count()
{
return $this->collection->count() > $this->totalRecords ? $this->totalRecords : $this->collection->count();
} | php | {
"resource": ""
} |
q14463 | CollectionDataTable.revertIndexColumn | train | private function revertIndexColumn($mDataSupport)
{
if ($this->columnDef['index']) {
$index = $mDataSupport ? config('datatables.index_column', 'DT_RowIndex') : 0;
$start = (int) $this->request->input('start');
$this->collection->transform(function ($data) use ($index, &$start) {
$data[$index] = ++$start;
return $data;
});
}
} | php | {
"resource": ""
} |
q14464 | CollectionDataTable.getSorter | train | protected function getSorter(array $criteria)
{
$sorter = function ($a, $b) use ($criteria) {
foreach ($criteria as $orderable) {
$column = $this->getColumnName($orderable['column']);
$direction = $orderable['direction'];
if ($direction === 'desc') {
$first = $b;
$second = $a;
} else {
$first = $a;
$second = $b;
}
if ($this->config->isCaseInsensitive()) {
$cmp = strnatcasecmp($first[$column], $second[$column]);
} else {
$cmp = strnatcmp($first[$column], $second[$column]);
}
if ($cmp != 0) {
return $cmp;
}
}
// all elements were equal
return 0;
};
return $sorter;
} | php | {
"resource": ""
} |
q14465 | QueryDataTable.prepareQuery | train | protected function prepareQuery()
{
if (! $this->prepared) {
$this->totalRecords = $this->totalCount();
if ($this->totalRecords) {
$this->filterRecords();
$this->ordering();
$this->paginate();
}
}
$this->prepared = true;
} | php | {
"resource": ""
} |
q14466 | QueryDataTable.totalCount | train | public function totalCount()
{
if ($this->skipTotalRecords) {
return true;
}
return $this->totalRecords ? $this->totalRecords : $this->count();
} | php | {
"resource": ""
} |
q14467 | QueryDataTable.filteredCount | train | protected function filteredCount()
{
$this->filteredRecords = $this->filteredRecords ?: $this->count();
if ($this->skipTotalRecords) {
$this->totalRecords = $this->filteredRecords;
}
return $this->filteredRecords;
} | php | {
"resource": ""
} |
q14468 | QueryDataTable.prepareCountQuery | train | protected function prepareCountQuery()
{
$builder = clone $this->query;
if (! $this->isComplexQuery($builder)) {
$row_count = $this->wrap('row_count');
$builder->select($this->connection->raw("'1' as {$row_count}"));
if (! $this->keepSelectBindings) {
$builder->setBindings([], 'select');
}
}
return $builder;
} | php | {
"resource": ""
} |
q14469 | QueryDataTable.getColumnSearchKeyword | train | protected function getColumnSearchKeyword($i, $raw = false)
{
$keyword = $this->request->columnKeyword($i);
if ($raw || $this->request->isRegex($i)) {
return $keyword;
}
return $this->setupKeyword($keyword);
} | php | {
"resource": ""
} |
q14470 | QueryDataTable.applyFilterColumn | train | protected function applyFilterColumn($query, $columnName, $keyword, $boolean = 'and')
{
$query = $this->getBaseQueryBuilder($query);
$callback = $this->columnDef['filter'][$columnName]['method'];
if ($this->query instanceof EloquentBuilder) {
$builder = $this->query->newModelInstance()->newQuery();
} else {
$builder = $this->query->newQuery();
}
$callback($builder, $keyword);
$query->addNestedWhereQuery($this->getBaseQueryBuilder($builder), $boolean);
} | php | {
"resource": ""
} |
q14471 | QueryDataTable.getBaseQueryBuilder | train | protected function getBaseQueryBuilder($instance = null)
{
if (! $instance) {
$instance = $this->query;
}
if ($instance instanceof EloquentBuilder) {
return $instance->getQuery();
}
return $instance;
} | php | {
"resource": ""
} |
q14472 | QueryDataTable.addTablePrefix | train | protected function addTablePrefix($query, $column)
{
if (strpos($column, '.') === false) {
$q = $this->getBaseQueryBuilder($query);
if (! $q->from instanceof Expression) {
$column = $q->from . '.' . $column;
}
}
return $this->wrap($column);
} | php | {
"resource": ""
} |
q14473 | QueryDataTable.prepareKeyword | train | protected function prepareKeyword($keyword)
{
if ($this->config->isCaseInsensitive()) {
$keyword = Str::lower($keyword);
}
if ($this->config->isWildcard()) {
$keyword = Helper::wildcardLikeString($keyword);
}
if ($this->config->isSmartSearch()) {
$keyword = "%$keyword%";
}
return $keyword;
} | php | {
"resource": ""
} |
q14474 | QueryDataTable.orderColumns | train | public function orderColumns(array $columns, $sql, $bindings = [])
{
foreach ($columns as $column) {
$this->orderColumn($column, str_replace(':column', $column, $sql), $bindings);
}
return $this;
} | php | {
"resource": ""
} |
q14475 | QueryDataTable.applyOrderColumn | train | protected function applyOrderColumn($column, $orderable)
{
$sql = $this->columnDef['order'][$column]['sql'];
$sql = str_replace('$1', $orderable['direction'], $sql);
$bindings = $this->columnDef['order'][$column]['bindings'];
$this->query->orderByRaw($sql, $bindings);
} | php | {
"resource": ""
} |
q14476 | QueryDataTable.getNullsLastSql | train | protected function getNullsLastSql($column, $direction)
{
$sql = $this->config->get('datatables.nulls_last_sql', '%s %s NULLS LAST');
return sprintf($sql, $column, $direction);
} | php | {
"resource": ""
} |
q14477 | QueryDataTable.showDebugger | train | protected function showDebugger(array $output)
{
$output['queries'] = $this->connection->getQueryLog();
$output['input'] = $this->request->all();
return $output;
} | php | {
"resource": ""
} |
q14478 | QueryDataTable.attachAppends | train | protected function attachAppends(array $data)
{
$appends = [];
foreach ($this->appends as $key => $value) {
if (is_callable($value)) {
$appends[$key] = value($value($this->getFilteredQuery()));
} else {
$appends[$key] = $value;
}
}
return array_merge($data, $appends);
} | php | {
"resource": ""
} |
q14479 | DataTables.make | train | public static function make($source)
{
$engines = config('datatables.engines');
$builders = config('datatables.builders');
$args = func_get_args();
foreach ($builders as $class => $engine) {
if ($source instanceof $class) {
return call_user_func_array([$engines[$engine], 'create'], $args);
}
}
foreach ($engines as $engine => $class) {
if (call_user_func_array([$engines[$engine], 'canCreate'], $args)) {
return call_user_func_array([$engines[$engine], 'create'], $args);
}
}
throw new \Exception('No available engine for ' . get_class($source));
} | php | {
"resource": ""
} |
q14480 | DataProcessor.process | train | public function process($object = false)
{
$this->output = [];
$indexColumn = config('datatables.index_column', 'DT_RowIndex');
foreach ($this->results as $row) {
$data = Helper::convertToArray($row);
$value = $this->addColumns($data, $row);
$value = $this->editColumns($value, $row);
$value = $this->setupRowVariables($value, $row);
$value = $this->selectOnlyNeededColumns($value);
$value = $this->removeExcessColumns($value);
if ($this->includeIndex) {
$value[$indexColumn] = ++$this->start;
}
$this->output[] = $object ? $value : $this->flatten($value);
}
return $this->escapeColumns($this->output);
} | php | {
"resource": ""
} |
q14481 | DataProcessor.addColumns | train | protected function addColumns($data, $row)
{
foreach ($this->appendColumns as $key => $value) {
$value['content'] = Helper::compileContent($value['content'], $data, $row);
$data = Helper::includeInArray($value, $data);
}
return $data;
} | php | {
"resource": ""
} |
q14482 | DataProcessor.editColumns | train | protected function editColumns($data, $row)
{
foreach ($this->editColumns as $key => $value) {
$value['content'] = Helper::compileContent($value['content'], $data, $row);
Arr::set($data, $value['name'], $value['content']);
}
return $data;
} | php | {
"resource": ""
} |
q14483 | DataProcessor.setupRowVariables | train | protected function setupRowVariables($data, $row)
{
$processor = new RowProcessor($data, $row);
return $processor
->rowValue('DT_RowId', $this->templates['DT_RowId'])
->rowValue('DT_RowClass', $this->templates['DT_RowClass'])
->rowData('DT_RowData', $this->templates['DT_RowData'])
->rowData('DT_RowAttr', $this->templates['DT_RowAttr'])
->getData();
} | php | {
"resource": ""
} |
q14484 | DataProcessor.selectOnlyNeededColumns | train | protected function selectOnlyNeededColumns(array $data)
{
if (is_null($this->onlyColumns)) {
return $data;
} else {
return array_intersect_key($data, array_flip(array_merge($this->onlyColumns, $this->exceptions)));
}
} | php | {
"resource": ""
} |
q14485 | DataProcessor.flatten | train | public function flatten(array $array)
{
$return = [];
foreach ($array as $key => $value) {
if (in_array($key, $this->exceptions)) {
$return[$key] = $value;
} else {
$return[] = $value;
}
}
return $return;
} | php | {
"resource": ""
} |
q14486 | DataProcessor.escapeColumns | train | protected function escapeColumns(array $output)
{
return array_map(function ($row) {
if ($this->escapeColumns == '*') {
$row = $this->escapeRow($row);
} elseif (is_array($this->escapeColumns)) {
$columns = array_diff($this->escapeColumns, $this->rawColumns);
foreach ($columns as $key) {
array_set($row, $key, e(array_get($row, $key)));
}
}
return $row;
}, $output);
} | php | {
"resource": ""
} |
q14487 | DataProcessor.escapeRow | train | protected function escapeRow(array $row)
{
$arrayDot = array_filter(array_dot($row));
foreach ($arrayDot as $key => $value) {
if (! in_array($key, $this->rawColumns)) {
$arrayDot[$key] = e($value);
}
}
foreach ($arrayDot as $key => $value) {
array_set($row, $key, $value);
}
return $row;
} | php | {
"resource": ""
} |
q14488 | Helper.includeInArray | train | public static function includeInArray($item, $array)
{
if (self::isItemOrderInvalid($item, $array)) {
return array_merge($array, [$item['name'] => $item['content']]);
}
$count = 0;
$last = $array;
$first = [];
foreach ($array as $key => $value) {
if ($count == $item['order']) {
return array_merge($first, [$item['name'] => $item['content']], $last);
}
unset($last[$key]);
$first[$key] = $value;
$count++;
}
} | php | {
"resource": ""
} |
q14489 | Helper.compileContent | train | public static function compileContent($content, array $data, $param)
{
if (is_string($content)) {
return static::compileBlade($content, static::getMixedValue($data, $param));
} elseif (is_callable($content)) {
return $content($param);
}
return $content;
} | php | {
"resource": ""
} |
q14490 | Helper.compileBlade | train | public static function compileBlade($str, $data = [])
{
if (view()->exists($str)) {
return view($str, $data)->render();
}
ob_start() && extract($data, EXTR_SKIP);
eval('?>' . app('blade.compiler')->compileString($str));
$str = ob_get_contents();
ob_end_clean();
return $str;
} | php | {
"resource": ""
} |
q14491 | Helper.getMixedValue | train | public static function getMixedValue(array $data, $param)
{
$casted = self::castToArray($param);
$data['model'] = $param;
foreach ($data as $key => $value) {
if (isset($casted[$key])) {
$data[$key] = $casted[$key];
}
}
return $data;
} | php | {
"resource": ""
} |
q14492 | Helper.castToArray | train | public static function castToArray($param)
{
if ($param instanceof \stdClass) {
$param = (array) $param;
return $param;
}
if ($param instanceof Arrayable) {
return $param->toArray();
}
return $param;
} | php | {
"resource": ""
} |
q14493 | Helper.getOrMethod | train | public static function getOrMethod($method)
{
if (! Str::contains(Str::lower($method), 'or')) {
return 'or' . ucfirst($method);
}
return $method;
} | php | {
"resource": ""
} |
q14494 | Helper.convertToArray | train | public static function convertToArray($row)
{
$data = $row instanceof Arrayable ? $row->toArray() : (array) $row;
foreach ($data as &$value) {
if (is_object($value) || is_array($value)) {
$value = self::convertToArray($value);
}
unset($value);
}
return $data;
} | php | {
"resource": ""
} |
q14495 | Helper.transformRow | train | protected static function transformRow($row)
{
foreach ($row as $key => $value) {
if ($value instanceof DateTime) {
$row[$key] = $value->format('Y-m-d H:i:s');
} else {
if (is_object($value)) {
$row[$key] = (string) $value;
} else {
$row[$key] = $value;
}
}
}
return $row;
} | php | {
"resource": ""
} |
q14496 | Helper.replacePatternWithKeyword | train | public static function replacePatternWithKeyword(array $subject, $keyword, $pattern = '$1')
{
$parameters = [];
foreach ($subject as $param) {
if (is_array($param)) {
$parameters[] = self::replacePatternWithKeyword($param, $keyword, $pattern);
} else {
$parameters[] = str_replace($pattern, $keyword, $param);
}
}
return $parameters;
} | php | {
"resource": ""
} |
q14497 | Helper.extractColumnName | train | public static function extractColumnName($str, $wantsAlias)
{
$matches = explode(' as ', Str::lower($str));
if (! empty($matches)) {
if ($wantsAlias) {
return array_pop($matches);
}
return array_shift($matches);
} elseif (strpos($str, '.')) {
$array = explode('.', $str);
return array_pop($array);
}
return $str;
} | php | {
"resource": ""
} |
q14498 | Helper.wildcardString | train | public static function wildcardString($str, $wildcard, $lowercase = true)
{
$wild = $wildcard;
$chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
if (count($chars) > 0) {
foreach ($chars as $char) {
$wild .= $char . $wildcard;
}
}
if ($lowercase) {
$wild = Str::lower($wild);
}
return $wild;
} | php | {
"resource": ""
} |
q14499 | MediaRepository.getCollection | train | public function getCollection(HasMedia $model, string $collectionName, $filter = []): Collection
{
return $this->applyFilterToMediaCollection($model->loadMedia($collectionName), $filter);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.