Guest User

Untitled

a guest
Oct 9th, 2015
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 189.75 KB | None | 0 0
  1. <?php
  2. /**
  3. * SocialEngine
  4. *
  5. * @category
  6. * @package
  7. * @copyright
  8. * @license
  9. * @version
  10. * @author Danilo Ronca
  11. */
  12.  
  13. /**
  14. * @category
  15. * @package
  16. * @copyright
  17. * @license
  18. */
  19. class Rest_Api_Auxiliary extends Core_Api_Abstract {
  20. static $usersCollection = "users";
  21. private static $photosColl = 'photos';
  22. private static $conversationsColl = 'conversations';
  23. private static $messagesColl = 'messages';
  24. private static $notificationsColl = 'notifications';
  25. private static $offersColl = 'offers';
  26. private static $feedsColl = 'feeds';
  27. private static $followersColl = 'user_relationships';
  28. private static $photosTaskColl = 'photos_task';
  29. private static $postsColl = 'posts';
  30. private static $photoSeeColl = 'photosee';
  31. private static $eventsColl = 'events';
  32. private static $eventMemberColl = 'event_membership';
  33. private static $offersCategoriesCollection = 'offer_categories';
  34. private static $offerCurrenciesCollection = 'offer_currencies';
  35. private static $offerLimitationTypes = 'offer_limitation_types';
  36. private static $offersTaskColl = 'offers_task';
  37.  
  38. /**
  39. * This method remove the record that has the device_id specified
  40. * in the device table.
  41. * @param $device_id deviceID to delete
  42. */
  43. public function removeDevice($device_id, $owner_id = null) {
  44. if($owner_id != null) {
  45. $where = array("_id" => $owner_id, 'devices' => array('$elemMatch' => array('id' => $device_id)));
  46. } else {
  47. $where = array('devices' => array('$elemMatch' => array('id' => $device_id)));
  48. }
  49. MyMongo_Connection::pullCollectionFields(static::$usersCollection, $where, array('devices' => array("id" => $device_id)));
  50. }
  51.  
  52.  
  53. /**
  54. * Ottiene i messaggi dell'utente nella conversazione specificata.
  55. * Setta sia la conversazione a letta, che la notifica su di essa a letta.
  56. * @param $conversation_id
  57. * @param $endDate
  58. * @param $userID
  59. * @return array dei messaggi
  60. */
  61. public function getMessagesConversation($conversation_id,$endDate,$userID,$fromWS=false, $limit=null)
  62. {
  63. //ottengo i messaggi della conversazione specificata (gli eliminati non compariranno)
  64. $messagesInConversation = Engine_Api::_ ()->getApi ( "messageutility", "messages" )->
  65. getConversationParticipantsDetails($conversation_id, $userID,-1,false,$limit,$endDate);
  66. $arrayMessages = array();
  67. $i=0;
  68. foreach ($messagesInConversation as $currMessage)
  69. {
  70. $arrayMessages[$i]['msg_id'] = !$fromWS ? $currMessage["_id"] : $currMessage["_id"]->__toString();
  71. $arrayMessages[$i]['message'] = $currMessage["body"];
  72. $arrayMessages[$i]['sender'] = $this->getUserDetails($currMessage["sender_id"]);
  73. $arrayMessages[$i]['sending_date'] = $currMessage["creation_date"]->sec;
  74. $i++;
  75. }
  76.  
  77. //Setto la conversazione a letta
  78. MyMongo_Connection::updateCollectionFields
  79. (
  80. static::$conversationsColl,
  81. array('conversation_id' => $conversation_id, 'owner_id' => $userID),
  82. array('read' => true)
  83. );
  84. //setto la notifica a true
  85. MyMongo_Connection::updateCollectionFields
  86. (
  87. static::$notificationsColl,
  88. array('user_id' => $userID, 'object_type' => 'conversation', 'object_id' => $conversation_id),
  89. array('read' => true)
  90. );
  91.  
  92. return $arrayMessages;
  93. }
  94.  
  95.  
  96. /**
  97. * Aggiunge un document nella collection dei photosee: si occupa anche del calcolo della distanza,
  98. * aggiornamento dei contatori e varie sul document relativo alla foto specificata.
  99. * @param $photo
  100. * @param $user_id
  101. * @param $latitude
  102. * @param $longitude
  103. * @return array with the id of created record and the counter of views.
  104. */
  105. public function createPhotoSeeRecord($photo, $user_id, $latitude, $longitude)
  106. {
  107. ini_set('mongo.native_long', 1);
  108. $condition = array
  109. (
  110. 'photo_id' => $photo->_id,
  111. 'lat' => $latitude,
  112. 'lon' => $longitude,
  113. );
  114.  
  115. $penultimatSeeCursor = MyMongo_Connection::find(static::$photoSeeColl, array('photo_id' => $photo->_id), array(), array('move_date' => -1), 1);
  116. //questo sarà il penultimo insieme di photosee (in ordine temporale discendente) dopo l'aggiunta di quello che si sta per creare: serve per l'eventuale aggiornamento delle distance
  117. $penultimatSeeSet = null;
  118. if($penultimatSeeCursor->hasNext())
  119. {
  120. $penultimatSeeSet = $penultimatSeeCursor->getNext();
  121. }
  122.  
  123. $geoArray = $this->Get_Address_From_Google_Maps($latitude, $longitude);
  124. $city = (sizeof($geoArray) != 0) ? $geoArray["city"] : "NULL";
  125.  
  126. //$mongoQuery = 'db.photosee.update({photo_id:"'.$photo->_id.'",lat:"'.$latitude.'",lon:"'.$longitude.'"},{$inc:{count:1}, $addToSet:{viewers:{user_id : "'.$user_id.'"}} ,$setOnInsert:{lat:"'.$latitude.'",lon:"'.$longitude.'",city:"'.$city.'",mover:"'.$user_id.'",move_date:ISODate()}},{upsert:true})';
  127. //$result = MyMongo_Connection::executeEvaluation($mongoQuery);
  128.  
  129.  
  130. $result = MyMongo_Connection::getConnection()->selectCollection("photosee")->update(
  131. array("photo_id" => $photo->_id, "lat" => $latitude, "lon" => $longitude),
  132. array(
  133. '$inc' => array("count" => 1),
  134. '$addToSet' => array("viewers" => array("user_id" => $user_id)),
  135. '$setOnInsert' => array("lat" => $latitude, "lon" => $longitude, "city" => $city, "mover" => $user_id, "move_date" => new MongoDate())
  136. ),
  137. array("upsert" => true)
  138. );
  139.  
  140. $arrayValueToInsert = array();
  141. //Se la foto non ha un uploader
  142. if(empty($photo->position_uploader))
  143. {
  144. $arrayValueToInsert["upload_position"] = array('lat'=>$latitude, 'lon' => $longitude, 'city' => $city);
  145. $arrayValueToInsert["position_uploader"] = $user_id;
  146. //salva la mappa statica e ne ottiene l'url in cui è stata salvata
  147. $arrayValueToInsert["map_upload_img_url"] = Engine_Api::_()->getApi('googleutility', 'core')->saveStaticPhotoMap($latitude, $longitude);
  148. }
  149.  
  150. $incrementArr = array('photosee_count' => 1);
  151. //se non c'era un document relativo ai photosee in queste coordinate, allora devo incrementare i move e la distanza
  152. if($result['nModified'] == 0)
  153. {
  154. $penultimateSeeLat = null;
  155. $penultimateSeeLon = null;
  156. //se è presente la posizione di upload e non ci sono photosee
  157. if(!empty($photo->position_uploader) && $photo->photosee_count === 0)
  158. {
  159. $penultimateSeeLat = $photo->upload_position['lat'];
  160. $penultimateSeeLon = $photo->upload_position['lon'];
  161. }
  162. //se invece c'è la coordinata di upload e ci sono anche photosee
  163. else if(!empty($photo->position_uploader) && $photo->photosee_count > 0)
  164. {
  165. //se c'è già un photo see si deve calcolare distanza da penultimo
  166. $penultimateSeeLat = $penultimatSeeSet['lat'];
  167. $penultimateSeeLon = $penultimatSeeSet['lon'];
  168. }
  169. if(!is_null($penultimateSeeLat) && !is_null($penultimateSeeLon))
  170. {
  171. $incrementArr['moves_count'] = 1;//incrementa di 1 i moves
  172. //the distance between lat and lon given in input and lat and lon where the last photo has seen + old distance
  173. $tmpDistance = $this->distance($penultimateSeeLat, $penultimateSeeLon, $latitude, $longitude, "M") ;
  174. $arrayValueToInsert['distance'] = $tmpDistance + $photo->distance;
  175. }
  176. }
  177. // //aggiorno le informazioni in foto
  178. MyMongo_Connection::updateAndOrIncCollectionFields
  179. (
  180. static::$photosColl,
  181. array('_id' => $photo->_id),
  182. $arrayValueToInsert,
  183. $incrementArr
  184. );
  185.  
  186.  
  187. //Invio delle notifiche inizio
  188. $isMoved = array_key_exists('moves_count', $incrementArr);//true se la foto è stata spostata ("moved")
  189. $this->addPhotoSeeNotifications($photo, $user_id, $isMoved);
  190. //Invio delle notifiche fine
  191.  
  192. return array(/*"see_id" => $photosee['photosee_id'], */"see_count" => $photo->photosee_count + 1);
  193. }
  194.  
  195. /**
  196. * Questo metodo si occupa dell'invio delle notifiche: photo_seen, photo_seen_seen, photo_moved
  197. * @param $photoObj
  198. * @param $user_id
  199. * @param $isMoved true se la foto è stata moved, false altrimenti
  200. */
  201. public function addPhotoSeeNotifications($photoObj, $user_id, $isMoved)
  202. {
  203. $photoOwnerID = $photoObj->owner_id;
  204. //ottengo la lista di tutti gli utenti che hanno visto la foto
  205. $seeUsers = Utilities_Static::getPhotoutility()->getPhotoSeeUsers($photoObj->_id);
  206. //se owner e user che richiede sono diversi
  207. if(strcasecmp($photoOwnerID, $user_id) != 0)
  208. {
  209. //invio una notifica di photoseen all'owner della foto
  210. Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification
  211. ($photoOwnerID, $user_id, $photoObj->_id, 'photo', 'photo_seen');
  212. //Se la foto è stata spostata si notifica all'owner
  213. if($isMoved)
  214. {
  215. //invio una notifica di photo moved all'owner della foto
  216. Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification
  217. ($photoOwnerID, $user_id, $photoObj->_id, 'photo', 'photo_moved');
  218. }
  219. //rimuove owner e utente corrente dalla lista se erano eventualmente presenti
  220. $seeUsers = array_diff($seeUsers, array($photoOwnerID, $user_id));
  221. }
  222. else
  223. {
  224. //rimuove owner dalla lista se eventualmente presente
  225. $seeUsers = array_diff($seeUsers, array($photoOwnerID));
  226. }
  227. //invio di notifiche di tipo photo seen seen
  228. foreach ($seeUsers as $currViewerID)
  229. {
  230. //invio la notifica al current user id dicendogli che anche $user_id ha visto una foto che lui ha visto
  231. Engine_Api::_()->getDbtable('notifications', 'activity')->addNotificationExceptPushNotification
  232. ($currViewerID, $user_id, $photoObj->_id, 'photo', 'photo_seen_seen');
  233. }
  234. //invio al push a tutti gli utenti che hanno visto gia' la foto
  235. Engine_Api::_()->getApi("activityutility","activity")->sendInstantNotificationToAllPlatformsForMultipleUsers($seeUsers);
  236. return;
  237. }
  238.  
  239. /**
  240. * This function return an array indicating the position earned(>0), lost(<0) or stable(=0) and
  241. * the days passed from latest update (including current and previous rank).
  242. * @param $user
  243. * @return array
  244. */
  245. public function getSocialmaticRanking($user) {
  246. if(!is_object($user)) {
  247. $user = (object) $user;
  248. }
  249. $dayPassedFromUpdate = $this->getDistanceDayBetweenTwoDateWithoutTimeZone(date('Y-m-d H:i:s', time()), date('Y-m-d H:i:s', $user->update_rank_date->sec));
  250.  
  251. return array(
  252. "positions" => $user->previous_rank - $user->current_rank,
  253. "dayPassedFromUpdate" => round($dayPassedFromUpdate, 2, PHP_ROUND_HALF_DOWN),
  254. "current_rank" => $user->current_rank,
  255. "previous_rank" => $user->previous_rank
  256. );
  257. }
  258.  
  259. /**
  260. * This method checks if the date of first photo passed in oldest than nDays and
  261. * if the photoDatesArray is more than kPhotos.
  262. * @param $photoDatesArray
  263. * @param $kPhotos
  264. * @param $nDays
  265. * @return boolean
  266. */
  267. public function checkMoreThanKPhotosInNDays($photoDatesArray, $kPhotos, $nDays)
  268. {
  269.  
  270. //if there are less photo than K
  271. if(sizeof($photoDatesArray) <= $kPhotos)
  272. return false;
  273.  
  274. else
  275. {
  276. $oldestDataInfo = $this->getOldestPhotoData($photoDatesArray);
  277. if( $this->getDistanceDaysFromToday($oldestDataInfo["oldestDate"]) > $nDays)
  278. return false;
  279. else return true;
  280. }
  281. }
  282.  
  283. /**
  284. * This method return the oldest data of data's array given in input
  285. * @param $array_photo_dates (each data is e.g. 2013-11-04 20:25:18+09:00)
  286. * @return mixed
  287. */
  288. public function getOldestPhotoData($array_photo_dates)
  289. {
  290.  
  291. $normalized_datas_received = array(); // @strtotime(date_format($dt, 'Y-m-d H:i:s'));
  292. $arrDatas = array();
  293. $i=0;
  294. foreach ($array_photo_dates as $currDate)
  295. {
  296. $arrDatas["".@strtotime(date_format(new DateTime($currDate), 'Y-m-d H:i:s'))] = $currDate;
  297. $normalized_datas_received[$i] = @strtotime(date_format(new DateTime($currDate), 'Y-m-d H:i:s'));
  298. $i++;
  299.  
  300. }
  301. $timeMillis = min($normalized_datas_received);
  302. $lastDate = $arrDatas[$timeMillis];
  303.  
  304. return array("time" => $timeMillis, "oldestDate" => $lastDate);
  305. }
  306. /**
  307. * This method returns the first N photos dates uploaded by the user_id
  308. * @param $userID
  309. * @param $numberLimit
  310. * @return array of last n photo shared by the user
  311. */
  312. public function getFirstNSharedPhoto($userID, $numberLimit)
  313. {
  314. $arrayLastNPhoto = array();
  315. $resultPhoto = MyMongo_Connection::find(
  316. static::$photosColl,
  317. array('owner_id'=>$userID),
  318. array('creation_date' => 1), //seleziono
  319. array('creation_date' => 1), //ordino asc
  320. $numberLimit);
  321. foreach ($resultPhoto as $currPhotoRecord)
  322. {
  323. array_push($arrayLastNPhoto, $currPhotoRecord['creation_date']);
  324. }
  325.  
  326. return $arrayLastNPhoto;
  327. }
  328. /**
  329. * This method return the day passed from the last photo to now.
  330. * @param $array_photo_dates array of dates
  331. * @return distance from the latest date today
  332. */
  333. public function getDaysFromLastPhoto($array_photo_dates)
  334. {
  335. $lastDataInfo = $this->getLastPhotoData($array_photo_dates);
  336. return $this->getDistanceDaysFromToday($lastDataInfo["lastDate"]);
  337. }
  338.  
  339.  
  340. /**
  341. * This method return the last date of date's array given in input
  342. * @param $array_photo_dates (each data is e.g. 2013-11-04 20:25:18+09:00)
  343. * @return array with the currentMillis and normalized string (e.g. 2013-11-04 20:25:18) of last date
  344. */
  345. public function getLastPhotoData($array_photo_dates)
  346. {
  347.  
  348. $normalized_datas_received = array(); // @strtotime(date_format($dt, 'Y-m-d H:i:s'));
  349. $arrDatas = array();
  350. $i=0;
  351. foreach ($array_photo_dates as $currDate)
  352. {
  353. $arrDatas["".@strtotime(date_format(new DateTime($currDate), 'Y-m-d H:i:s'))] = $currDate;
  354. $normalized_datas_received[$i] = @strtotime(date_format(new DateTime($currDate), 'Y-m-d H:i:s'));
  355. $i++;
  356.  
  357. }
  358. $timeMillis = max($normalized_datas_received);
  359. $lastDate = $arrDatas[$timeMillis];
  360.  
  361. return array("time" => $timeMillis, "lastDate" => $lastDate);
  362. }
  363.  
  364. /**
  365. * This method returns the days passed from today's date to the date on input.
  366. * It considers the timezone, hence it compute the day passed in that
  367. * time zone .
  368. * @param $timeReceived is a string representing a time (e.g. $timeReceived='2013-11-04 19:20:18+09:00')
  369. * @return the distance in day between timeReceived and today.
  370. */
  371. public function getDistanceDaysFromToday($timeReceived)
  372. {
  373. /*Time information about server current zone*/
  374. $now = date('Y-m-d H:i:s', time());
  375. $timeHere = new DateTime($now, new DateTimeZone(ini_get('date.timezone')));
  376. //echo $timeHere->format('Y-m-d H:i:sP') . "<br />";
  377. /*Time information about server current zone*/
  378.  
  379.  
  380. /*Time information about remote zone*/
  381. $dt = new DateTime($timeReceived);
  382. $nowtimeInThatTZ=$timeHere->setTimezone(new DateTimeZone($this->myGetTimeZone($dt->getTimezone()->getName())));
  383. //echo $nowtimeInThatTZ->format('Y-m-d H:i:sP') . "<br />";
  384. /*Time information about remote zone*/
  385.  
  386.  
  387. $normalized_data_received = @strtotime(date_format($dt, 'Y-m-d H:i:s'));
  388. $normalized_nowtimeInThatTZ = @strtotime(date_format($nowtimeInThatTZ, 'Y-m-d H:i:s'));
  389. //compute the difference in days between the dates
  390. $datediff = $normalized_nowtimeInThatTZ - $normalized_data_received;
  391.  
  392. return $datediff/(60*60*24);
  393. }
  394.  
  395. /**
  396. * This method return the difference in day from date1 and date2. It doesn't consider the time zone.
  397. * @param $date1
  398. * @param $date2
  399. * @return difference in day between $date1 and $date2 ($date1 - $date2)
  400. */
  401. public function getDistanceDayBetweenTwoDateWithoutTimeZone($date1, $date2)
  402. {
  403. $dt1 = new DateTime($date1);
  404. $dt2 = new DateTime($date2);
  405.  
  406. $normalized_data1 = @strtotime(date_format($dt1, 'Y-m-d H:i:s'));
  407. $normalized_data2 = @strtotime(date_format($dt2, 'Y-m-d H:i:s'));
  408. //compute the difference in days between the dates
  409. $datediff = $normalized_data1 - $normalized_data2;
  410. return $datediff/(60*60*24);
  411.  
  412. }
  413.  
  414. /**
  415. * Get the user's info.
  416. *
  417. * @param $arrayUserID
  418. * @return array representing the user's information.
  419. */
  420. public function getUserDetails($arrayUserID, $interestWithCategory=false)
  421. {
  422. //se è un id
  423. if(is_string($arrayUserID))
  424. {
  425. $user = MyMongo_Connection::findOne(static::$usersCollection, array('_id' => $arrayUserID));
  426. if(!is_null($user))
  427. {
  428. return $this->buildUserArr((array)$user, $interestWithCategory);
  429. }
  430. else
  431. {
  432. return array();
  433. }
  434. }
  435. else
  436. {
  437. if (sizeof($arrayUserID) > 0)
  438. {
  439. $arrayUsersInfo = MyMongo_Connection::find(static::$usersCollection, array('_id' => array('$in' => $arrayUserID)));
  440. $userInfo = array();
  441. $element = null;
  442. foreach ($arrayUsersInfo as $user)
  443. {
  444. $element = $this->buildUserArr($user, $interestWithCategory);
  445. $userInfo[] = $element;
  446. }
  447. if(is_null($element))
  448. {
  449. return $this->buildDetedUser();
  450. }
  451. if(sizeof($userInfo) == 1)
  452. return $element;
  453. else
  454. {
  455. return $userInfo;
  456. }
  457. }
  458. else
  459. {
  460. return array();
  461. }
  462. }
  463. }
  464. /**
  465. * Costruisce un item utente sotto forma di array
  466. * @param $user array dell'utente restituito dalla query
  467. * @param $interestWithCategory se è vero restituisce anche la ce
  468. */
  469. public function buildUserArr($user, $interestWithCategory=false)
  470. {
  471. $element = array(
  472. 'user_id' => $user["_id"],
  473. 'nickname' => $user["username"],
  474. 'status' => $user["status"],
  475. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . Zend_Registry::get ( 'Zend_View' )->baseUrl () . "/" . "profile/" . $user["username"],
  476. 'ranking' => $user["current_rank"],
  477. );
  478. $element["positions_ranking"] = $user["current_rank"] - $user["previous_rank"];
  479.  
  480. $interests = !$interestWithCategory ? Utilities_Static::getUserutility()->getUserInterests((object)$user, false) : $user['interests'];
  481. $element["interests"] = is_null($interests) ? array() : $interests;
  482. $element["user_cities"] = Utilities_Static::getPhotoutility()->getUploadCitiesForUser($user["_id"]);
  483. $element["photo_profile_url"] = Utilities_Static::getProfilePhotoURL($user, true);
  484. $userType = ucfirst($user["type"]);
  485. $element["user_type"] = $userType;
  486. if (strcasecmp($userType, "personal") == 0)
  487. {
  488. $element["user_gender"] = $user["gender"];
  489. }
  490. return $element;
  491. }
  492.  
  493. /**
  494. * Get the user's info.
  495. *
  496. * @param $arrayUserIDs
  497. * @return array representing the user's information.
  498. */
  499. public function getUserDetailsToArray($arrayUserIDs, $viewerID=null)
  500. {
  501. if (sizeof($arrayUserIDs) > 0)
  502. {
  503. $userUtility = Engine_Api::_()->getApi ( 'userutility', 'core' );
  504. $userInfo = array();
  505. foreach ($arrayUserIDs as $user)
  506. {
  507. $element = array(
  508. 'user_id' => $user["_id"],
  509. 'display_name' => $userUtility->getNameOrCompanyOfUser($user),
  510. 'nickname' => $user["username"],
  511. 'status' => $user["status"],
  512. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . Zend_Registry::get ( 'Zend_View' )->baseUrl () . "/" . "profile/" . $user["username"],
  513. 'ranking' => $user["current_rank"],
  514. );
  515. $element["positions_ranking"] = $user["current_rank"] - $user["previous_rank"];
  516. $element["interests"] = array();
  517. if(!is_null($user["interests"]))
  518. {
  519. $element["interests"] = $user["interests"];
  520. $dimInterests = sizeof($element["interests"]);
  521. for($i=0; $i<$dimInterests;$i++)
  522. {
  523. $element["interests"][$i] = substr($element["interests"][$i], strpos($element["interests"][$i], "_")+1);
  524. }
  525. }
  526. $element["user_cities"] = Utilities_Static::getPhotoutility()->getUploadCitiesForUser($user["_id"]);
  527. $element["photo_profile_url"] = Utilities_Static::getProfilePhotoURL($user, true);
  528. $element["user_type"] = ucfirst($user['type']);
  529. if (strcasecmp($user['type'], "personal") == 0)
  530. {
  531. $element["user_gender"] = ucfirst($user['gender']);
  532. }
  533. if(!is_null($viewerID))
  534. {
  535. $isFollowing = $userUtility->isFollowing($viewerID, $user["_id"]);
  536. $element["already_followed"] = $isFollowing ? "true" : "false";
  537. $element["can_send_message"] = ($isFollowing || $userUtility->isFollowing($user["_id"], $viewerID)) ? "true" : "false";
  538. }
  539. $userInfo[] = $element;
  540. }
  541. if(in_array(0, $arrayUserIDs))
  542. {
  543. array_push($userInfo, $this->buildDetedUser());
  544. }
  545. return $userInfo;
  546. }
  547. else
  548. {
  549. return array();
  550. }
  551. }
  552. /**
  553. * This method builds a deleted user.
  554. */
  555. private function buildDetedUser()
  556. {
  557. $userDeleted = array();
  558. $userDeleted["user_id"] = 0;
  559. $userDeleted["display_name"] = "Deleted User";
  560. $userDeleted["nickname"] = "Deleted User";
  561. $userDeleted["status"] = "";
  562. $userDeleted["qr_details"] = 'https://' . $_SERVER ['HTTP_HOST'] . Zend_Registry::get ( 'Zend_View' )->baseUrl () ;
  563. $userDeleted["ranking"] = 0;
  564. $userDeleted["positions_ranking"] = 0;
  565. $userDeleted["interest"] = array();
  566. $userDeleted["cities"] = array();
  567. $userDeleted["photo_profile_url"] = "";
  568. $userDeleted["user_type"] = "Personal";
  569. $userDeleted["user_gender"] = "M";
  570. $userDeleted["already_followed"] = "false";
  571. $userDeleted["can_send_message"] = "false";
  572. return $userDeleted;
  573. }
  574.  
  575. private function getUserTypeFieldValues($arrayFieldsValues){
  576. $userType = null;
  577. foreach ($arrayFieldsValues as $value) {
  578. if ($value["field_id"] == 1){
  579. $userType = ($value["value"] == 1) ? "Personal" : "Business";
  580. }
  581. }
  582. if (strcasecmp($userType,"Personal") == 0){
  583. foreach ($arrayFieldsValues as $value) {
  584. if ($value["field_id"] == 5){
  585. $userGender = $value["value"] == 2 ? "M" : "W";
  586. }
  587. if (isset($userGender))
  588. break;
  589. }
  590. }
  591. $element = array();
  592. $element["user_type"] = $userType;
  593. if (isset($userGender))
  594. $element["user_gender"] = $userGender;
  595. return $element;
  596. }
  597.  
  598. /**
  599. * Get the user's friend in paginated way.
  600. *
  601. * @param $userID of the user who want to get the friends list.
  602. * @param $lastReceivedUserID
  603. * @return array representing the friends.
  604. */
  605. public function getSearchedUserFriends($userID, $search_string) {
  606. $limit = 20;
  607. $user = Engine_Api::_()->user()->getUser($userID);
  608. $membership = Engine_Api::_()->getDbtable('membership', 'user');
  609. $select = $user->membership()->getMembershipsOfSelect($user);
  610. /* Da completare */
  611. }
  612.  
  613. /**
  614. * Get the user's friend that matches $valuetosearch. limit 20
  615. *
  616. * @param $userID of
  617. * the user who want to get the friends list.
  618. * @return array representing the friends.
  619. */
  620. public function getUserFriends($userID,$valueToSearch)
  621. {
  622. //la regex per cercare l'utente
  623. $searchRegex = new MongoRegex('/' . $valueToSearch . '/i');
  624. //ottengo sia i follower che i following dell'utente corrente
  625. $friendships = MyMongo_Connection::find(static::$followersColl,
  626. array(
  627. '$or' => array(
  628. array("follower" => $userID),
  629. array("following" => $userID)
  630. )
  631. ),
  632. array(
  633. "follower" => 1,
  634. "following" => 1
  635. )
  636. );
  637. //array che conterrà tutti gli id dei follower e following
  638. $friend_ids = array();
  639. foreach ($friendships as $fs)
  640. {
  641. if($fs['follower'] === $userID)
  642. {
  643. array_push($friend_ids, $fs['following']);
  644. }
  645. else if($fs['following'] === $userID)
  646. {
  647. array_push($friend_ids, $fs['follower']);
  648. }
  649. }
  650. //elimino i duplicati
  651. $friend_ids = array_unique($friend_ids);
  652. //riordino la numerazione dell'array
  653. $friend_ids = array_values($friend_ids);
  654.  
  655. //cerco tra i follower/following coloro che corrispondono alla chiave di ricerca digitata (limite a 10)
  656. $friends_cursor = MyMongo_Connection::find(
  657. static::$usersCollection,
  658. array(
  659. "_id" => array('$in' => $friend_ids),
  660. "level" => 4,
  661. '$or' => array(
  662. array("username" => $searchRegex),
  663. array("name" => $searchRegex),
  664. array("surname" => $searchRegex),
  665. array("company" => $searchRegex)
  666. )
  667. ),
  668. array(),
  669. array(),
  670. 10
  671. );
  672. $followersFollowing = array();
  673. //serve per prevenire inserimento di doppioni
  674. $temp = array ();
  675. foreach ($friends_cursor as $currFriend)
  676. {
  677. if (!array_key_exists ( $currFriend ['username'], $temp ))
  678. {
  679. $temp [$currFriend ['username']] = 1;
  680. array_push($followersFollowing, $currFriend);
  681. }
  682. }
  683. $friends = $this->getUserDetailsToArray($followersFollowing);
  684. return $friends;
  685. }
  686.  
  687. /**
  688. * This method returns the path of social matic application.
  689. * @return social matic full path
  690. */
  691. public function getSocialMaticPath()
  692. {
  693. $pathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
  694. return $this->getPropertyArray($pathConfFile)['socialmaticFullpath'];
  695. }
  696.  
  697. /**
  698. * This function checks if a device_type is valid
  699. * @param $codeArray the array of valid codes
  700. * @param $device_type the code need to verify
  701. * @return boolean
  702. */
  703. public function checkAllowedDeviceType($codeArray, $device_type)
  704. {
  705. $found = false;
  706. foreach ($codeArray as $value) {
  707. if($value == $device_type)
  708. $found = true;
  709. }
  710.  
  711. return $found;
  712. }
  713. /**
  714. * Questo metodo crea un array di tag facendo le verifiche/modifiche per ognuno
  715. * @param $freeTags
  716. * @return array di tag "puliti"
  717. */
  718. public function createTag($freeTags)
  719. {
  720. $arrayTags = explode(",",$freeTags);
  721. $arrayTags=$this->array_iunique($arrayTags);
  722. //check if there are tags
  723. if($dim=sizeof($arrayTags) > 0)
  724. {
  725. for($i = 0; $i < $dim; $i++)
  726. {
  727. $currTag = (strlen($arrayTags[$i]) > 30) ? mb_substr($arrayTags[$i], 0, 30, 'utf-8') : $arrayTags[$i];
  728. $currTag = htmlspecialchars($currTag,ENT_NOQUOTES);
  729. $arrayTags[$i] = $currTag;
  730. }
  731. }
  732. return $arrayTags;
  733. }
  734. /**
  735. * Fa l'array unique case insensitive
  736. * @param $array
  737. * @return multitype:
  738. */
  739. private function array_iunique($array) {
  740. return array_intersect_key(
  741. $array,
  742. array_unique(array_map("StrToLower",$array))
  743. );
  744. }
  745.  
  746. /**
  747. * This method sets the default permission (friends of friends) to the album given in input
  748. * @param $album_id
  749. */
  750. public function setDefaultPermissionAlbum($album)
  751. {
  752. $auth = Engine_Api::_()->authorization()->context;
  753. //$roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
  754.  
  755. $auth->setAllowed($album, 'owner', 'view', true);
  756. $auth->setAllowed($album, 'owner_member', 'view', true);
  757. $auth->setAllowed($album, 'owner_member_member', 'view', true);
  758.  
  759.  
  760. $auth->setAllowed($album, 'owner', 'comment', true);
  761. $auth->setAllowed($album, 'owner_member', 'comment', true);
  762. $auth->setAllowed($album, 'owner_member_member', 'comment', true);
  763.  
  764. $auth->setAllowed($album, 'owner', 'tag', true);
  765.  
  766. }
  767. /**
  768. * This method return photo's orientation: vertical or horizontal
  769. * @param unknown $filepath
  770. */
  771. public function getFileImageOrientation($filepath)
  772. {
  773. $image = Engine_Image::factory();
  774. $image->open($filepath);
  775. $orientation = "vertical";
  776. if($image->width > $image->height)
  777. {
  778. $orientation = "horizontal";
  779. }
  780. $image->destroy();
  781. return $orientation;
  782. }
  783. public function createPhotoRecord
  784. (
  785. $userID, $deviceID, $fullpathFile, $username, $extension,
  786. $compliantName,$fileSize, $description, $timestampID, $tagsArray, $coordinates, $creation_date
  787. )
  788. {
  789. $orientation = $this->getFileImageOrientation($fullpathFile);
  790. $imgInfos = $this->createFiles($extension, $compliantName);
  791.  
  792. $_id = hash("md5", $description . $creation_date->__toString());
  793.  
  794. $arrayValueToInsert = array
  795. (
  796. "_id" => $_id,
  797. "title" => $description,
  798. "timestamp_id" => $timestampID,
  799. "creation_date" => $creation_date,
  800. "modified_date" => $creation_date,
  801. "owner_id" => $userID,
  802. "owner_username" => $username,
  803. "fullsize_img" => $imgInfos['fullsize_img'],
  804. "thumb_img" => $imgInfos['thumb_img'],
  805. "img_orientation" => $orientation,
  806. "comments_count" => 0,
  807. "cools_count" => 0,
  808. "device_id" => $deviceID,
  809. "is_public" => true,
  810. "distance" => 0,
  811. "moves_count" => 0,
  812. "offers_count" => 0,
  813. "photosee_count" => 0,
  814. "deleted" => false
  815. );
  816. if(!is_null($coordinates))
  817. {
  818. $geoArray = $this->Get_Address_From_Google_Maps($coordinates['lat'], $coordinates['lon']);
  819. $city = (sizeof($geoArray) != 0) ? $geoArray["city"] : "NULL";
  820. $arrayValueToInsert["upload_position"] = array('lat'=>$coordinates['lat'], 'lon' => $coordinates['lon'], 'city' => $city);
  821. $arrayValueToInsert["position_uploader"] = $userID;
  822. //salva la mappa statica e ne ottiene l'url in cui è stata salvata
  823. $arrayValueToInsert["map_upload_img_url"] = Engine_Api::_()->getApi('googleutility', 'core')->saveStaticPhotoMap($coordinates['lat'], $coordinates['lon']);
  824. }
  825. if(!is_null($tagsArray))
  826. {
  827. $arrayValueToInsert["tags"] = $tagsArray;
  828. }
  829. MyMongo_Connection::addDocument(static::$photosColl, $arrayValueToInsert);
  830. return array("photoID" => $_id) ;
  831. }
  832.  
  833. /**
  834. * Salva una immagine su s3 ed eventualmente anche il thumb se $noResize è false
  835. * @param $extension
  836. * @param $compliantName
  837. * @param $fileName
  838. * @param string $noResize
  839. * @return multitype:multitype:string unknown
  840. */
  841. public function createFiles($extension, $compliantName, $noResize = false)
  842. {
  843. //ottengo il path del file che contiene le proprietà relative ai paths
  844. $fullpathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
  845. $arrProp = $this->getPropertyArray($fullpathConfFile);
  846.  
  847. //local path che sarà usato in amazon s3
  848. $storagePath = $arrProp['localPathImage'].$compliantName."_m.".$extension;
  849. //hash foto originale
  850. $hashOriginal = hash_file('md5', $arrProp['localPathImage'].$compliantName."_m.".$extension);
  851. //file size originale
  852. $originalFileSize = filesize($arrProp['localPathImage'].$compliantName."_m.".$extension);
  853. //salvo su amazon immagine dimensioni originali
  854. $this->uploadOnS3($arrProp['temporaryPath'].$compliantName."_m.".$extension, $storagePath);
  855. $toRet = array('fullsize_img' => array('url' => $storagePath,'hash' => $hashOriginal, 'size' => $originalFileSize));
  856. if(!$noResize)
  857. {
  858. //local path che sarà usato in amazon s3
  859. $storagePathThumb = $arrProp['localPathImage'].$compliantName."_in.".$extension;
  860. //hash foto thumbl
  861. $hashThumb = hash_file('md5', $arrProp['localPathImage'].$compliantName."_in.".$extension);
  862. //file size thumb
  863. $thumbFileSize = filesize($arrProp['localPathImage'].$compliantName."_in.".$extension);
  864. //salvo su amazon immagine thumb
  865. $this->uploadOnS3($arrProp['temporaryPath'].$compliantName."_in.".$extension, $storagePathThumb);
  866. $toRet['thumb_img'] = array('url' => $storagePathThumb, 'hash' => $hashThumb, 'size' => $thumbFileSize);
  867. }
  868. return $toRet;
  869. }
  870.  
  871. /**
  872. * Effettua l'upload di una foto su s3.
  873. * @param $filepath
  874. * @param $filepathToSaveInS3
  875. * @return path relativo salvato su amazonS3|NULL
  876. */
  877. public function uploadOnS3($filepath, $filepathToSaveInS3)
  878. {
  879. $s3 = new s3upload_S3(awsAccessKey, awsSecretKey);
  880. if ($s3->putObjectFile($filepath, bucket, $filepathToSaveInS3, s3upload_S3::ACL_PUBLIC_READ))
  881. {
  882. @unlink($filepath);
  883. return $final_img_name;
  884. }
  885. else
  886. {
  887. @unlink($filepath);
  888. Utilities_Static::log("ERROR while uploading file: " . $img_full_name);
  889. return null;
  890. }
  891. }
  892.  
  893. /**
  894. * This method read a conf file ini and return an array
  895. * key-value.
  896. * @param $fullpathIniFile
  897. * @return multitype:
  898. */
  899. public function getPropertyArray($fullpathIniFile)
  900. {
  901. return parse_ini_file($fullpathIniFile);
  902. }
  903.  
  904. /**
  905. * This method create a single file from a base64 string.
  906. * @param $byte base64 string
  907. * @param $pathToSave path to save the file
  908. * @param $imgName image's name
  909. * @return array containing the extension and size of created file.
  910. */
  911. public function createFileFromBase64String($byte, $pathToSave, $filename)
  912. {
  913.  
  914. //decode the base64
  915. $isOK = $decodedData=base64_decode($byte, true);
  916. if($isOK) {
  917. //get the mime type array (0 is major (e.g. image) and 1 is minor (e.g. jpeg))
  918. $mime_arr = $this->getFileMIME($decodedData);
  919.  
  920. $fullpathFile=$pathToSave.$filename;
  921. @file_put_contents( $fullpathFile."_m.".$mime_arr[1], $decodedData );
  922. chmod($fullpathFile."_m.".$mime_arr[1], 0777);
  923.  
  924.  
  925. return array("extension" => $mime_arr[1], "filesize" => strlen($decodedData));
  926. }
  927. return null;
  928. }
  929.  
  930. /**
  931. * This method create a image from a base64 string and save it
  932. * in the specified path.
  933. * @param $byte the BASE64 string
  934. * @param $pathToSave path to save image
  935. * @param $imgName the image's name
  936. * @return file info created
  937. */
  938. public function createImageFromBase64String($byte, $pathToSave, $imgName)
  939. {
  940. //decode the base64
  941. $decodedImage=base64_decode($byte);
  942.  
  943. //get the mime type array (0 is major (e.g. image) and 1 is minor (e.g. jpeg))
  944. $mime_arr = $this->getFileMIME($decodedImage);
  945.  
  946. //create one photo resized
  947. $this->resizeAndCreatePhoto($decodedImage, $pathToSave, $imgName, $mime_arr[1] );
  948.  
  949.  
  950. return array("extension" => $mime_arr[1], "filesize" => strlen($decodedImage));
  951. }
  952.  
  953. /**
  954. * This method create from a photo input a new photo resized.
  955. * @param $decodedData
  956. * @param $pathToSave
  957. * @param $imgName
  958. * @param $filetype
  959. */
  960. public function resizeAndCreatePhoto($decodedData, $pathToSave, $imgName, $filetype) {
  961. $fullpathFile = $pathToSave . $imgName;
  962. $main_photo_full_path = $fullpathFile . "_m." . $filetype;
  963.  
  964. @file_put_contents($main_photo_full_path, $decodedData);
  965. chmod($main_photo_full_path, 0777);
  966.  
  967. $name = basename($fullpathFile);
  968. $path = dirname($fullpathFile);
  969.  
  970. $image = Engine_Image::factory();
  971. $image->open($main_photo_full_path);
  972.  
  973. // Create resized image
  974. $iMainPath = $path . '/' . $name . "_in." . $filetype;
  975. if($image->width > $image->height) {
  976. $image->resize(381, 254)->write($iMainPath)->destroy();
  977. } else {
  978. $image->resize(254, 381)->write($iMainPath)->destroy();
  979. }
  980. chmod($iMainPath, 0777);
  981.  
  982. if($filetype == "jpg" || $filetype == "jpeg") {
  983. $im = imagecreatefromjpeg($main_photo_full_path);
  984. imageinterlace($im , true);
  985. imagejpeg($im , $main_photo_full_path, 100);
  986.  
  987. $im = imagecreatefromjpeg($iMainPath);
  988. imageinterlace($im , true);
  989. imagejpeg($im , $iMainPath, 100);
  990. imagedestroy($im);
  991. }
  992.  
  993. $image->destroy();
  994. }
  995.  
  996. /**
  997. * This method return the file's MIME Type (array[0] -> mime_major, array[1] -> mime_minor) given in input (e.g. image/jpeg)
  998. * @param $base64Decoded
  999. */
  1000. public function getFileMIME($base64Decoded)
  1001. {
  1002. $f = finfo_open();
  1003. return explode("/",finfo_buffer($f, $base64Decoded, FILEINFO_MIME_TYPE));
  1004. }
  1005.  
  1006. /**
  1007. * Aggiunge un item al feed del creatore dell'item ed a tutti i suoi follower
  1008. * @param $userID
  1009. * @param $type
  1010. * @param $idItem
  1011. */
  1012. public function addActivity($userID, $type, $idItem, $creation_date = null) {
  1013. if($creation_date == null) {
  1014. $now = new MongoDate();
  1015. } else {
  1016. $now = $creation_date;
  1017. }
  1018. $flowItem = array('item_id'=>$idItem,'item_type'=>$type,'poster_id'=>$userID,'post_date'=>$now);
  1019. //aggiungo nel flow del poster
  1020. MyMongo_Connection::addInFeed($userID, array($flowItem), 128);
  1021. //oggetto utente
  1022. $userObj = MyMongo_Connection::findOne(static::$usersCollection, array('_id' => $userID));
  1023. //se è pubblico l'utente allora si aggiunge la foto creata nei post dei suoi follower
  1024. if($userObj->is_public)
  1025. {
  1026. /*
  1027. * Aggiungo a tutti i follower il post creato mediante task temporizzato: INIZIO
  1028. */
  1029. $followersIDsArr = array();
  1030. $cursor = MyMongo_Connection::find(static::$followersColl, array('following' => $userID));
  1031. foreach ($cursor as $curr)
  1032. {
  1033. array_push($followersIDsArr, $curr['follower']);
  1034. }
  1035. //se l'utente ha followers
  1036. if(sizeof($followersIDsArr) > 0)
  1037. {
  1038. //aggiungo il document che sarà letto dal task di aggiornamento
  1039. MyMongo_Connection::addDocument(static::$photosTaskColl, array(
  1040. 'photo_id' => $idItem,
  1041. 'owner_id' => $userID,
  1042. 'taskcreation_date' => $now,
  1043. 'remaining_users' => $followersIDsArr,
  1044. 'active' => true
  1045. ));
  1046. }
  1047. /*
  1048. * Aggiungo a tutti i follower il post creato mediante task temporizzato: FINE
  1049. */
  1050. }
  1051.  
  1052. //aggiungo il post nella collection generale dei post
  1053. MyMongo_Connection::addDocument(static::$postsColl, $flowItem);
  1054. }
  1055.  
  1056. /* OLD METHOD */
  1057. /**
  1058. * This method generate a full deviceID for a socialmatic device
  1059. * @param $partialDeviceID
  1060. * @return string
  1061. */
  1062. public function otherDeviceIdGenerator($partialDeviceID)
  1063. {
  1064. $realAlphaChar =
  1065. (
  1066. $this->decimalConversionIfNotANumber($partialDeviceID[0]) +
  1067. $this->decimalConversionIfNotANumber($partialDeviceID[1]) +
  1068. $this->decimalConversionIfNotANumber($partialDeviceID[2]) +
  1069. $this->decimalConversionIfNotANumber($partialDeviceID[3]) +
  1070. $this->decimalConversionIfNotANumber($partialDeviceID[4]) +
  1071. $this->decimalConversionIfNotANumber($partialDeviceID[5]) +
  1072. $this->decimalConversionIfNotANumber($partialDeviceID[6]) +
  1073. $this->decimalConversionIfNotANumber($partialDeviceID[7])
  1074. ) % 9;
  1075.  
  1076. $realBetaChar =
  1077. (
  1078. $this->decimalConversionIfNotANumber($partialDeviceID[9]) +
  1079. $this->decimalConversionIfNotANumber($partialDeviceID[10]) +
  1080. $this->decimalConversionIfNotANumber($partialDeviceID[11]) +
  1081. $this->decimalConversionIfNotANumber($partialDeviceID[12]) +
  1082. $this->decimalConversionIfNotANumber($partialDeviceID[14]) +
  1083. $this->decimalConversionIfNotANumber($partialDeviceID[15]) +
  1084. $this->decimalConversionIfNotANumber($partialDeviceID[16]) +
  1085. $this->decimalConversionIfNotANumber($partialDeviceID[17])
  1086. ) % 9;
  1087.  
  1088. $realGammaChar =
  1089. (
  1090. $this->decimalConversionIfNotANumber($partialDeviceID[19]) +
  1091. $this->decimalConversionIfNotANumber($partialDeviceID[20]) +
  1092. $this->decimalConversionIfNotANumber($partialDeviceID[21]) +
  1093. $this->decimalConversionIfNotANumber($partialDeviceID[22])
  1094. ) % 9;
  1095.  
  1096. $realDeltaChar =
  1097. (
  1098. $this->decimalConversionIfNotANumber($partialDeviceID[24]) +
  1099. $this->decimalConversionIfNotANumber($partialDeviceID[25]) +
  1100. $this->decimalConversionIfNotANumber($partialDeviceID[26]) +
  1101. $this->decimalConversionIfNotANumber($partialDeviceID[27]) +
  1102. $this->decimalConversionIfNotANumber($partialDeviceID[28]) +
  1103. $this->decimalConversionIfNotANumber($partialDeviceID[29]) +
  1104. $this->decimalConversionIfNotANumber($partialDeviceID[30]) +
  1105. $this->decimalConversionIfNotANumber($partialDeviceID[31]) +
  1106. $this->decimalConversionIfNotANumber($partialDeviceID[32]) +
  1107. $this->decimalConversionIfNotANumber($partialDeviceID[33]) +
  1108. $this->decimalConversionIfNotANumber($partialDeviceID[34]) +
  1109. $this->decimalConversionIfNotANumber($partialDeviceID[35])
  1110. ) % 9;
  1111.  
  1112. return $partialDeviceID."-".$realAlphaChar.$realBetaChar.$realGammaChar.$realDeltaChar;
  1113. }
  1114. /**
  1115. * This method check if the deviceID given in input is valid for a socialmatic device
  1116. * @param $deviceID
  1117. * @return boolean
  1118. */
  1119. public function checkOtherDeviceIDCorrectness($deviceID)
  1120. {
  1121. //check pattern deviceID
  1122. $pattern = "/^[A-Z0-9]{8}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{12}[-]{1}[A-Z0-9]{4}$/";
  1123. if(preg_match($pattern,$deviceID) == 0)
  1124. {
  1125. return false;
  1126. }
  1127. else
  1128. {
  1129. $alphaChar = $deviceID[37];
  1130. $betaChar = $deviceID[38];
  1131. $gammaChar = $deviceID[39];
  1132. $deltaChar = $deviceID[40];
  1133.  
  1134. $realAlphaChar =
  1135. (
  1136. $this->decimalConversionIfNotANumber($deviceID[0]) +
  1137. $this->decimalConversionIfNotANumber($deviceID[1]) +
  1138. $this->decimalConversionIfNotANumber($deviceID[2]) +
  1139. $this->decimalConversionIfNotANumber($deviceID[3]) +
  1140. $this->decimalConversionIfNotANumber($deviceID[4]) +
  1141. $this->decimalConversionIfNotANumber($deviceID[5]) +
  1142. $this->decimalConversionIfNotANumber($deviceID[6]) +
  1143. $this->decimalConversionIfNotANumber($deviceID[7])
  1144. ) % 9;
  1145.  
  1146. $realBetaChar =
  1147. (
  1148. $this->decimalConversionIfNotANumber($deviceID[9]) +
  1149. $this->decimalConversionIfNotANumber($deviceID[10]) +
  1150. $this->decimalConversionIfNotANumber($deviceID[11]) +
  1151. $this->decimalConversionIfNotANumber($deviceID[12]) +
  1152. $this->decimalConversionIfNotANumber($deviceID[14]) +
  1153. $this->decimalConversionIfNotANumber($deviceID[15]) +
  1154. $this->decimalConversionIfNotANumber($deviceID[16]) +
  1155. $this->decimalConversionIfNotANumber($deviceID[17])
  1156. ) % 9;
  1157.  
  1158. $realGammaChar =
  1159. (
  1160. $this->decimalConversionIfNotANumber($deviceID[19]) +
  1161. $this->decimalConversionIfNotANumber($deviceID[20]) +
  1162. $this->decimalConversionIfNotANumber($deviceID[21]) +
  1163. $this->decimalConversionIfNotANumber($deviceID[22])
  1164. ) % 9;
  1165.  
  1166. $realDeltaChar =
  1167. (
  1168. $this->decimalConversionIfNotANumber($deviceID[24]) +
  1169. $this->decimalConversionIfNotANumber($deviceID[25]) +
  1170. $this->decimalConversionIfNotANumber($deviceID[26]) +
  1171. $this->decimalConversionIfNotANumber($deviceID[27]) +
  1172. $this->decimalConversionIfNotANumber($deviceID[28]) +
  1173. $this->decimalConversionIfNotANumber($deviceID[29]) +
  1174. $this->decimalConversionIfNotANumber($deviceID[30]) +
  1175. $this->decimalConversionIfNotANumber($deviceID[31]) +
  1176. $this->decimalConversionIfNotANumber($deviceID[32]) +
  1177. $this->decimalConversionIfNotANumber($deviceID[33]) +
  1178. $this->decimalConversionIfNotANumber($deviceID[34]) +
  1179. $this->decimalConversionIfNotANumber($deviceID[35])
  1180. ) % 9;
  1181.  
  1182. if (
  1183. (($alphaChar==$realAlphaChar)) &&
  1184. (($betaChar==$realBetaChar) ) &&
  1185. (($gammaChar==$realGammaChar) ) &&
  1186. (($deltaChar==$realDeltaChar) )
  1187. )
  1188. {
  1189. //the deviceID is valid
  1190. return true;
  1191. }
  1192.  
  1193. else return false;
  1194. }
  1195. }
  1196.  
  1197.  
  1198. /**
  1199. * This method generate a full deviceID for a socialmatic device
  1200. * @param $partialDeviceID
  1201. * @return string
  1202. */
  1203. public function socialMaticDeviceIdGenerator($partialDeviceID)
  1204. {
  1205. $realAlphaChar =
  1206. (
  1207. $this->decimalConversionIfNotANumber($partialDeviceID[0]) +
  1208. $this->decimalConversionIfNotANumber($partialDeviceID[10]) +
  1209. $this->decimalConversionIfNotANumber($partialDeviceID[14]) +
  1210. $this->decimalConversionIfNotANumber($partialDeviceID[26])
  1211. ) % 9;
  1212.  
  1213. $realBetaChar =
  1214. (
  1215. $this->decimalConversionIfNotANumber($partialDeviceID[11]) +
  1216. $this->decimalConversionIfNotANumber($partialDeviceID[15]) +
  1217. $this->decimalConversionIfNotANumber($partialDeviceID[19]) +
  1218. $this->decimalConversionIfNotANumber($partialDeviceID[25])
  1219. ) % 9;
  1220.  
  1221. $realGammaChar = (($realAlphaChar + $realBetaChar)/9) % 9;
  1222.  
  1223. $realDeltaChar = ( ($realGammaChar + $realAlphaChar) * ($realGammaChar + $realBetaChar) ) % 5 ;
  1224.  
  1225. return $partialDeviceID."-".$realAlphaChar.$realBetaChar.$realGammaChar.$realDeltaChar;
  1226. }
  1227. /**
  1228. * Verifica se l'utente specificato possiede un dispositivo di tipo socialmatic camera
  1229. * @param $user (array o oggetto rappresentante un utente)
  1230. */
  1231. public function checkIfUserHasASocialmaticCamera($user)
  1232. {
  1233. if(is_object($user))
  1234. {
  1235. $user = (array)$user;
  1236. }
  1237. else if(!is_array($user))
  1238. {
  1239. return true; //errore
  1240. }
  1241. return $this->checkIfThereIsASMCamera($user['devices']);
  1242. }
  1243. /**
  1244. * Verifica se nell'array di device ce n'è uno che è di tipo socialmatic camera.
  1245. * @param $devicesArr
  1246. * @return boolean
  1247. */
  1248. public function checkIfThereIsASMCamera($devicesArr)
  1249. {
  1250. $hasSocialmaticCamera = false;
  1251. //scandisco tutti i device
  1252. foreach ($devicesArr as $currDevice)
  1253. {
  1254. //se il device corrente è di tipo socialmatic
  1255. if($this->checkSocialMaticDeviceIDCorrectness($currDevice['id']))
  1256. {
  1257. $hasSocialmaticCamera = true;
  1258. break;
  1259. }
  1260. }
  1261. return $hasSocialmaticCamera;
  1262. }
  1263.  
  1264. /**
  1265. * This method check if the deviceID given in input is valid for a socialmatic device
  1266. * @param $deviceID
  1267. * @return boolean
  1268. */
  1269. public function checkSocialMaticDeviceIDCorrectness($deviceID)
  1270. {
  1271. //check pattern deviceID
  1272. $pattern = "/^[A-Z0-9]{8}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{12}[-]{1}[A-Z0-9]{4}$/";
  1273. if(preg_match($pattern,$deviceID) == 0)
  1274. {
  1275. return FALSE;
  1276. }
  1277. else
  1278. {
  1279.  
  1280. $alphaChar = $deviceID[37];
  1281. $betaChar = $deviceID[38];
  1282. $gammaChar = $deviceID[39];
  1283. $deltaChar = $deviceID[40];
  1284.  
  1285. $realAlphaChar =
  1286. (
  1287. $this->decimalConversionIfNotANumber($deviceID[0]) +
  1288. $this->decimalConversionIfNotANumber($deviceID[10]) +
  1289. $this->decimalConversionIfNotANumber($deviceID[14]) +
  1290. $this->decimalConversionIfNotANumber($deviceID[26])
  1291. ) % 9;
  1292.  
  1293. $realBetaChar =
  1294. (
  1295. $this->decimalConversionIfNotANumber($deviceID[11]) +
  1296. $this->decimalConversionIfNotANumber($deviceID[15]) +
  1297. $this->decimalConversionIfNotANumber($deviceID[19]) +
  1298. $this->decimalConversionIfNotANumber($deviceID[25])
  1299. ) % 9;
  1300.  
  1301. $realGammaChar = (($realAlphaChar + $realBetaChar)/9) % 9;
  1302.  
  1303. $realDeltaChar = ( ($realGammaChar + $realAlphaChar) * ($realGammaChar + $realBetaChar) ) % 5 ;
  1304.  
  1305. if (
  1306. (($alphaChar==$realAlphaChar)) &&
  1307. (($betaChar==$realBetaChar) ) &&
  1308. (($gammaChar==$realGammaChar) ) &&
  1309. (($deltaChar==$realDeltaChar) )
  1310. )
  1311. {
  1312. //the deviceID is valid
  1313. return TRUE;
  1314. }
  1315.  
  1316. else return FALSE;
  1317. }
  1318. }
  1319.  
  1320. /**
  1321. * This method convert the char given in input into matched decimal ASCII. Whether input
  1322. * is a number will be not converted.
  1323. * @param $char
  1324. * @return decimal representation of $char.
  1325. */
  1326. public function decimalConversionIfNotANumber($char)
  1327. {
  1328. $dec=0;
  1329. if(!is_numeric($char))
  1330. {
  1331. $dec = $this->ascii_to_dec($char)[0];
  1332. }
  1333. else $dec = $char;
  1334.  
  1335. return $dec;
  1336. }
  1337.  
  1338. /**
  1339. * This method convert a string in respectively decimal ascii for each char
  1340. * @param $str
  1341. * @return number
  1342. */
  1343. public function ascii_to_dec($str)
  1344. {
  1345. for ($i = 0, $j = strlen($str); $i < $j; $i++) {
  1346. $dec_array[] = ord($str{$i});
  1347. }
  1348. return $dec_array;
  1349. }
  1350.  
  1351. /**
  1352. * This method create an authtoken
  1353. * @return string
  1354. */
  1355. public function getAuthToken() {
  1356. $charid = strtoupper(md5(uniqid(rand(), true)));
  1357.  
  1358. $auth_token = substr($charid, 0, 8) . '-' .
  1359. substr($charid, 8, 8) . '-' .
  1360. substr($charid, 16, 8) . '-' .
  1361. substr($charid, 24, 8);
  1362. return $auth_token;
  1363. }
  1364.  
  1365.  
  1366. public function myGetTimeZone($differenceFromGreenwich)
  1367. {
  1368. $timezones = array(
  1369. '-11:00'=>'Pacific/Midway',
  1370. '-11:00'=>'US/Samoa',
  1371. '-10:00'=>'US/Hawaii',
  1372. '-09:00'=>'US/Alaska',
  1373. '-08:00'=>'US/Pacific',
  1374. '-08:00'=>'America/Tijuana',
  1375. '-07:00'=>'US/Arizona',
  1376. '-07:00'=>'US/Mountain',
  1377. '-07:00'=>'America/Chihuahua',
  1378. '-07:00'=>'America/Mazatlan',
  1379. '-06:00'=>'America/Mexico_City',
  1380. '-06:00'=>'America/Monterrey',
  1381. '-06:00'=>'Canada/Saskatchewan',
  1382. '-06:00'=>'US/Central',
  1383. '-05:00'=>'US/Eastern',
  1384. '-05:00'=>'US/East-Indiana',
  1385. '-05:00'=>'America/Bogota',
  1386. '-05:00'=>'America/Lima',
  1387. '-04:30'=>'America/Caracas',
  1388. '-04:00'=>'Canada/Atlantic',
  1389. '-04:00'=>'America/La_Paz',
  1390. '-04:00'=>'America/Santiago',
  1391. '-03:30'=>'Canada/Newfoundland',
  1392. '-03:00'=>'America/Buenos_Aires',
  1393. '-03:00'=>'Greenland',
  1394. '-02:00'=>'Atlantic/Stanley',
  1395. '-01:00'=>'Atlantic/Azores',
  1396. '-01:00'=>'Atlantic/Cape_Verde',
  1397. '+00:00'=>'Africa/Casablanca',
  1398. '+00:00'=>'Europe/Dublin',
  1399. '+00:00'=>'Europe/Lisbon',
  1400. '+00:00'=>'Europe/London',
  1401. '+00:00'=>'Africa/Monrovia',
  1402. '+01:00'=>'Europe/Amsterdam',
  1403. '+01:00'=>'Europe/Belgrade',
  1404. '+01:00'=>'Europe/Berlin',
  1405. '+01:00'=>'Europe/Bratislava',
  1406. '+01:00'=>'Europe/Brussels',
  1407. '+01:00'=>'Europe/Budapest',
  1408. '+01:00'=>'Europe/Copenhagen',
  1409. '+01:00'=>'Europe/Ljubljana',
  1410. '+01:00'=>'Europe/Madrid',
  1411. '+01:00'=>'Europe/Paris',
  1412. '+01:00'=>'Europe/Prague',
  1413. '+01:00'=>'Europe/Rome',
  1414. '+01:00'=>'Europe/Sarajevo',
  1415. '+01:00'=>'Europe/Skopje',
  1416. '+01:00'=>'Europe/Stockholm',
  1417. '+01:00'=>'Europe/Vienna',
  1418. '+01:00'=>'Europe/Warsaw',
  1419. '+01:00'=>'Europe/Zagreb',
  1420. '+02:00'=>'Europe/Athens',
  1421. '+02:00'=>'Europe/Bucharest',
  1422. '+02:00'=>'Africa/Cairo',
  1423. '+02:00'=>'Africa/Harare',
  1424. '+02:00'=>'Europe/Helsinki',
  1425. '+02:00'=>'Europe/Istanbul',
  1426. '+02:00'=>'Asia/Jerusalem',
  1427. '+02:00'=>'Europe/Kiev',
  1428. '+02:00'=>'Europe/Minsk',
  1429. '+02:00'=>'Europe/Riga',
  1430. '+02:00'=>'Europe/Sofia',
  1431. '+02:00'=>'Europe/Tallinn',
  1432. '+02:00'=>'Europe/Vilnius',
  1433. '+03:00'=>'Asia/Baghdad',
  1434. '+03:00'=>'Asia/Kuwait',
  1435. '+03:00'=>'Africa/Nairobi',
  1436. '+03:00'=>'Asia/Riyadh',
  1437. '+03:00'=>'Asia/Tehran',
  1438. '+04:00'=>'Europe/Moscow',
  1439. '+04:00'=>'Asia/Baku',
  1440. '+04:00'=>'Europe/Volgograd',
  1441. '+04:00'=>'Asia/Muscat',
  1442. '+04:00'=>'Asia/Tbilisi',
  1443. '+04:00'=>'Asia/Yerevan',
  1444. '+04:30'=>'Asia/Kabul',
  1445. '+05:00'=>'Asia/Karachi',
  1446. '+05:00'=>'Asia/Tashkent',
  1447. '+05:30'=>'Asia/Kolkata',
  1448. '+05:45'=>'Asia/Kathmandu',
  1449. '+06:00'=>'Asia/Yekaterinburg',
  1450. '+06:00'=>'Asia/Almaty',
  1451. '+06:00'=>'Asia/Dhaka',
  1452. '+07:00'=>'Asia/Novosibirsk',
  1453. '+07:00'=>'Asia/Bangkok',
  1454. '+07:00'=>'Asia/Jakarta',
  1455. '+08:00'=>'Asia/Krasnoyarsk',
  1456. '+08:00'=>'Asia/Chongqing',
  1457. '+08:00'=>'Asia/Hong_Kong',
  1458. '+08:00'=>'Asia/Kuala_Lumpur',
  1459. '+08:00'=>'Australia/Perth',
  1460. '+08:00'=>'Asia/Singapore',
  1461. '+08:00'=>'Asia/Taipei',
  1462. '+08:00'=>'Asia/Ulaanbaatar',
  1463. '+08:00'=>'Asia/Urumqi',
  1464. '+09:00'=>'Asia/Irkutsk',
  1465. '+09:00'=>'Asia/Seoul',
  1466. '+09:00'=>'Asia/Tokyo',
  1467. '+09:30'=>'Australia/Adelaide',
  1468. '+09:30'=>'Australia/Darwin',
  1469. '+10:00'=>'Asia/Yakutsk',
  1470. '+10:00'=>'Australia/Brisbane',
  1471. '+10:00'=>'Australia/Canberra',
  1472. '+10:00'=>'Pacific/Guam',
  1473. '+10:00'=>'Australia/Hobart',
  1474. '+10:00'=>'Australia/Melbourne',
  1475. '+10:00'=>'Pacific/Port_Moresby',
  1476. '+10:00'=>'Australia/Sydney',
  1477. '+11:00'=>'Asia/Vladivostok',
  1478. '+12:00'=>'Asia/Magadan',
  1479. '+12:00'=>'Pacific/Auckland',
  1480. '+12:00'=>'Pacific/Fiji'
  1481. );
  1482.  
  1483. return $timezones[$differenceFromGreenwich];
  1484. }
  1485. /**************************************** SECTION REFERS GOOGLE MAPS API: BEGIN ********************************/
  1486.  
  1487. /*
  1488. * Given longitude and latitude in North America, return the address using The Google Geocoding API V3
  1489. *
  1490. */
  1491. /**
  1492. * This method returns an array representing information about latitude and longitude given in input.
  1493. * @param $lat
  1494. * @param $lon
  1495. * @return information array about latitude and longitude.
  1496. */
  1497. public function Get_Address_From_Google_Maps($lat, $lon) {
  1498.  
  1499. $url = "http://maps.google.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";
  1500. $googleUtility = Engine_Api::_()->getApi("googleutility","core");
  1501. $url = $googleUtility->getSMSignedURL($url,false);
  1502. /*$log = Zend_Registry::get('Zend_Log');
  1503. $log->log("**********".$url."************".$query, Zend_Log::CRIT);*/
  1504. // Make the HTTP request
  1505. $data = @file_get_contents($url);
  1506. // Parse the json response
  1507. $jsondata = json_decode($data,true);
  1508.  
  1509. // If the json data is invalid, return empty array
  1510. if (!$this->check_status($jsondata)) return array();
  1511.  
  1512. $address = array(
  1513. 'country' => $this->google_getCountry($jsondata),
  1514. 'province' => $this->google_getProvince($jsondata),
  1515. 'city' => $this->google_getCity($jsondata),
  1516. 'street' => $this->google_getStreet($jsondata),
  1517. 'postal_code' => $this->google_getPostalCode($jsondata),
  1518. 'country_code' => $this->google_getCountryCode($jsondata),
  1519. 'formatted_address' => $this->google_getAddress($jsondata),
  1520. );
  1521.  
  1522. return $address;
  1523. }
  1524.  
  1525. /*
  1526. * Check if the json data from Google Geo is valid
  1527. */
  1528.  
  1529. public function check_status($jsondata) {
  1530. if ($jsondata["status"] == "OK") return true;
  1531. return false;
  1532. }
  1533.  
  1534. /*
  1535. * Given Google Geocode json, return the value in the specified element of the array
  1536. */
  1537.  
  1538. public function google_getCountry($jsondata) {
  1539. return $this->Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"]);
  1540. }
  1541. public function google_getProvince($jsondata) {
  1542. return $this->Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
  1543. }
  1544. /* OLD */
  1545. /*
  1546. public function google_getCity($jsondata) {
  1547. return $this->Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
  1548. }*/
  1549. public function google_getCity($jsondata) {
  1550. $city = $this->Find_Long_Name_Given_Type("sublocality", $jsondata["results"][0]["address_components"]);
  1551. if(empty($city))
  1552. {
  1553. $city = $this->Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
  1554. if(empty($city))
  1555. {
  1556. $city = $this->Find_Long_Name_Given_Type("administrative_area_level_3", $jsondata["results"][0]["address_components"], true);
  1557. if(empty($city))
  1558. {
  1559. $city = $this->Find_Long_Name_Given_Type("administrative_area_level_2", $jsondata["results"][0]["address_components"], true);
  1560. if(empty($city))
  1561. {
  1562. $city = $this->Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
  1563. }
  1564. }
  1565. }
  1566. }
  1567. return $city;
  1568. }
  1569. public function google_getStreet($jsondata) {
  1570. return $this->Find_Long_Name_Given_Type("street_number", $jsondata["results"][0]["address_components"]) . ' ' . $this->Find_Long_Name_Given_Type("route", $jsondata["results"][0]["address_components"]);
  1571. }
  1572. public function google_getPostalCode($jsondata) {
  1573. return $this->Find_Long_Name_Given_Type("postal_code", $jsondata["results"][0]["address_components"]);
  1574. }
  1575. public function google_getCountryCode($jsondata) {
  1576. return $this->Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"], true);
  1577. }
  1578. public function google_getAddress($jsondata) {
  1579. return $jsondata["results"][0]["formatted_address"];
  1580. }
  1581.  
  1582. /*
  1583. * Searching in Google Geo json, return the long name given the type.
  1584. * (If long_name is true, return short name)
  1585. */
  1586.  
  1587. public function Find_Long_Name_Given_Type($type, $array, $long_name = false) {
  1588. foreach( $array as $value) {
  1589. if (in_array($type, $value["types"])) {
  1590. return $value["long_name"];
  1591. }
  1592. }
  1593. }
  1594.  
  1595. /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
  1596. /*:: :*/
  1597. /*:: This routine calculates the distance between two points (given the :*/
  1598. /*:: latitude/longitude of those points). It is being used to calculate :*/
  1599. /*:: the distance between two locations using GeoDataSource(TM) Products :*/
  1600. /*:: :*/
  1601. /*:: Definitions: :*/
  1602. /*:: South latitudes are negative, east longitudes are positive :*/
  1603. /*:: :*/
  1604. /*:: Passed to function: :*/
  1605. /*:: lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees) :*/
  1606. /*:: lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees) :*/
  1607. /*:: unit = the unit you desire for results :*/
  1608. /*:: where: 'M' is statute miles :*/
  1609. /*:: 'K' is kilometers (default) :*/
  1610. /*:: 'N' is nautical miles :*/
  1611. /*:: Worldwide cities and other features databases with latitude longitude :*/
  1612. /*:: are available at http://www.geodatasource.com :*/
  1613. /*:: :*/
  1614. /*:: For enquiries, please contact sales@geodatasource.com :*/
  1615. /*:: :*/
  1616. /*:: Official Web site: http://www.geodatasource.com :*/
  1617. /*:: :*/
  1618. /*:: GeoDataSource.com (C) All Rights Reserved 2013 :*/
  1619. /*:: :*/
  1620. /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
  1621. public function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  1622.  
  1623. $theta = (float)$lon1 - (float)$lon2;
  1624. $dist = sin(deg2rad((float)$lat1)) * sin(deg2rad((float)$lat2)) + cos(deg2rad((float)$lat1)) * cos(deg2rad((float)$lat2)) * cos(deg2rad($theta));
  1625. $dist = acos($dist);
  1626. $dist = rad2deg($dist);
  1627. $miles = $dist * 60 * 1.1515;
  1628. $unit = strtoupper($unit);
  1629.  
  1630. if ($unit == "K") {
  1631. return ($miles * 1.609344);
  1632. } else if ($unit == "M") {
  1633. return ($miles * 0.8684);
  1634. } else {
  1635. return $miles;
  1636. }
  1637. }
  1638.  
  1639. /**************************************** SECTION REFERS GOOGLE MAPS API: END ********************************/
  1640.  
  1641. public function base64_encode_image ($filename) {
  1642. if ($filename) {
  1643. $imgbinary = fread(fopen($filename, "r"), filesize($filename));
  1644. return base64_encode($imgbinary);
  1645. }
  1646. }
  1647.  
  1648. /***RELEASE 2************************************************************/
  1649. /**
  1650. * method which returns information of user in input
  1651. * @param $user who want to get the friends list.
  1652. * @return array representing user information
  1653. */
  1654. public function getUserInfo($user, $requestUserID) {
  1655. if(!is_object($user)) {
  1656. $user = (object) $user;
  1657. }
  1658.  
  1659. $userUtility = Engine_Api::_()->getApi('userutility','core');
  1660. $photoUtility = Engine_Api::_()->getApi('photoutility','core');
  1661. $citiesAndMiles = $this->getAllCitiesAndTotalMiles($user->_id, $photoUtility);
  1662.  
  1663. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  1664. $gr_details = 'https://' . $_SERVER['HTTP_HOST'] . $appName . "profile/" . $user->username;
  1665.  
  1666. $interests = array();
  1667. foreach ($user->interests as $int) {
  1668. $interest = array(
  1669. "interest_id" => $int,
  1670. "content" => $int
  1671. );
  1672. array_push($interests, $interest);
  1673. }
  1674.  
  1675. $canSendMessage = $userUtility->checkFriendshipChannelBetweenTwoUsers($user->_id,$requestUserID) ? "true" : "false";
  1676. $membershipTable = Engine_Api::_()->getDbTable('membership','user');
  1677.  
  1678. $alreadyFollowed = $userUtility->isFollowing($requestUserID, $user->_id) ? "true" : "false";
  1679.  
  1680. if (strcasecmp ( $user->type, "Business" ) == 0) {
  1681. $info = array (
  1682. 'user_id' => $user->_id,
  1683. 'email' => $user->email,
  1684. 'nickname' => $user->username,
  1685. 'name' => $user->name,
  1686. 'surname' => $user->surname,
  1687. 'status_msg' => $user->status,
  1688. 'account_type' => ucfirst($user->type),
  1689. 'company_name' => $user->company,
  1690. 'country' => $user->country,
  1691. 'vat' => $user->vat,
  1692. 'professional_work_fld' => $user->workfield,
  1693. 'location' => $user->location,
  1694. 'cities' => array_values($citiesAndMiles['cities']),
  1695. 'is_authentic' => $user->authentic ? "1" : "0",
  1696. 'rank' => $this->getSocialmaticRanking($user),
  1697. 'miles' => $citiesAndMiles['miles'],
  1698. 'profile_photo_url' => isset($user->cropped_profilephoto_url) ? SM_BUCKET . $user->cropped_profilephoto_url : "",
  1699. 'qr_details' => $gr_details,
  1700. 'flow_photo_url' => isset($user->cropped_flowphoto_url) ? SM_BUCKET . $user->cropped_flowphoto_url : "",
  1701. 'user_interests' => $interests,
  1702. 'following_number' => $user->following_count,
  1703. 'follower_number' => $user->followers_count,
  1704. 'can_send_message' => $canSendMessage,
  1705. 'already_followed' => $alreadyFollowed,
  1706. 'is_public' => $user->is_public
  1707. );
  1708. } else {
  1709. $info = array (
  1710. 'user_id' => $user->_id,
  1711. 'email' => $user->email,
  1712. 'nickname' => $user->username,
  1713. 'name' => $user->name,
  1714. 'surname' => $user->surname,
  1715. 'status_msg' => $user->status,
  1716. 'account_type' => ucfirst($user->type),
  1717. 'birthday' => $user->birthdate->sec,
  1718. 'gender' => ucfirst($user->gender),
  1719. 'location' => $user->location,
  1720. 'cities' => array_values($citiesAndMiles['cities']),
  1721. 'rank' => $this->getSocialmaticRanking($user),
  1722. 'miles' => $citiesAndMiles['miles'],
  1723. 'is_authentic' => $user->authentic ? "1" : "0",
  1724. 'profile_photo_url' => isset($user->cropped_profilephoto_url) ? SM_BUCKET . $user->cropped_profilephoto_url : "",
  1725. 'qr_details' => $gr_details,
  1726. 'flow_photo_url' => isset($user->cropped_flowphoto_url) ? SM_BUCKET . $user->cropped_flowphoto_url : "",
  1727. 'user_interests' => $interests,
  1728. 'following_number' => $user->following_count,
  1729. 'follower_number' => $user->followers_count,
  1730. 'can_send_message' => $canSendMessage,
  1731. 'already_followed' => $alreadyFollowed,
  1732. 'is_public' => $user->is_public
  1733. );
  1734. }
  1735. return $info;
  1736.  
  1737. }
  1738.  
  1739. private function getAllCitiesAndTotalMiles($userID, $photoUtility) {
  1740. // get all photo records
  1741. $allPhotoRecords = $photoUtility->getAlbumPhotos($userID);
  1742.  
  1743. $citiesArray = array();
  1744. $milesArray = array();
  1745. $i = 0;
  1746. foreach($allPhotoRecords as $currPhotoRecord) {
  1747. // if the first photo's coordinates (upload coordinates or first photo see coordinates) isn't null
  1748. if (!$currPhotoRecord['deleted'] && !is_null($photoUtility->getCoordinates($currPhotoRecord['_id']))) {
  1749. $milesArray[$i] = (int) $photoUtility->getPhotoMiles($currPhotoRecord['_id']);
  1750. $citiesArray[$i] = $photoUtility->getPhotoCities($currPhotoRecord['_id'], 1)[0]['city'];
  1751. $i ++;
  1752. }
  1753. }
  1754. return $i == 0 ? null : array (
  1755. "cities" => array_unique($citiesArray),
  1756. "miles" => array_sum($milesArray)
  1757. );
  1758. }
  1759.  
  1760.  
  1761. /**
  1762. * method which returns the album's photos of a registered user
  1763. * @param $albumOwnerID userID owner or object owner of album
  1764. * @return array representing album's photos:
  1765. */
  1766. public function getAlbum($userID, $albumOwnerID, $lastReceivedID,$numOfPhoto) {
  1767. $albumOwner = null;
  1768. if(is_object($albumOwnerID) || is_array($albumOwnerID)) {
  1769. $albumOwner = (object) $albumOwnerID;
  1770. $albumOwnerID = $albumOwner->_id;
  1771. }
  1772. $photoUtility = Engine_Api::_()->getApi('photoutility','core');
  1773.  
  1774. // it get the reference to the table engine4_album_photos
  1775. if (strcasecmp($userID, $albumOwnerID) != 0)
  1776. $resultAlbumOwnerID = $photoUtility->getAlbumPhotos($albumOwnerID, null, null, $lastReceivedID, $numOfPhoto, true);
  1777. else
  1778. $resultAlbumOwnerID = $photoUtility->getAlbumPhotos($albumOwnerID, null, null, $lastReceivedID, $numOfPhoto, false);
  1779.  
  1780. $album = array();
  1781. $i = 0;
  1782.  
  1783. foreach ($resultAlbumOwnerID as $photo) {
  1784. $photo_id = $photo["_id"];
  1785.  
  1786. $upload_date = $photo['creation_date']->sec;
  1787.  
  1788. $arrayCities = $photoUtility->getPhotoCities($photo);
  1789. $uploadCity = $arrayCities[0]["city"];
  1790.  
  1791. $photoURLThumb = SM_BUCKET . $photo['thumb_img']['url'];
  1792. $photoURL = SM_BUCKET . $photo['fullsize_img']['url'];
  1793. $fileID = $photoFileRecord ["file_id"];
  1794.  
  1795.  
  1796. $photoTags = $photoUtility->getPhotoTags ($photo);
  1797. if($photoTags == null) {
  1798. $photoTags = array();
  1799. }
  1800.  
  1801. $appName = Zend_Registry::get ( 'Zend_View' )->baseUrl () . "/";
  1802.  
  1803. $textUtility = Engine_Api::_()->getApi('textutility', 'core');
  1804. $qrDetails = 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "user/photodetail/view?p=" . $photo_id;
  1805.  
  1806. $photoArray = array (
  1807. 'photo_id' => $photo_id,
  1808. 'photo_description' => $photo['title'],
  1809. 'photo_see_counter' => $photo['photosee_count'],
  1810. 'photo_tags' => $photoTags,
  1811. 'photo_miles' => round($photo['distance'],2),
  1812. 'photo_cools_number' => $photo['cools_count'],
  1813. 'photo_movers_counter' => $photo['moves_count'],
  1814. 'upload_city' => $uploadCity,
  1815. 'upload_date' => $upload_date,
  1816. 'map_upload_img_url' => SM_BUCKET . $photo['map_upload_img_url'],
  1817. 'photo_url_thumb' => $photoURLThumb,
  1818. 'photo_url' => $photoURL,
  1819. "pin_counter" => isset($photo['upload_position']) ? $photo['moves_count'] + 1 : 0,
  1820. 'qr_details' => $qrDetails,
  1821. 'image_orientation' => $photo['img_orientation'],
  1822. 'comment_counter' => $photo['comments_count']
  1823. );
  1824. $album [$i] = $photoArray;
  1825. $i ++;
  1826. }
  1827.  
  1828. if($albumOwner == null) {
  1829. return array(
  1830. 'photos' => $album,
  1831. 'owner' => $this->getUserDetails($albumOwnerID)
  1832. );
  1833. } else {
  1834. $owner = array(
  1835. 'user_id' => $albumOwner->_id,
  1836. 'nickname' => $albumOwner->username,
  1837. 'status' => $albumOwner->status,
  1838. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . Zend_Registry::get('Zend_View')->baseUrl() . "/" . "profile/" . $albumOwner->username,
  1839. 'ranking' => $albumOwner->current_rank,
  1840. 'positions_ranking' => $albumOwner->current_rank - $albumOwner->previous_rank,
  1841.  
  1842. );
  1843.  
  1844. $interests = array();
  1845. foreach ($albumOwner->interests as $int) {
  1846. $interest = explode("_", $int)[1];
  1847. array_push($interests, $interest);
  1848. }
  1849.  
  1850. $owner["interests"] = $interests;
  1851. $owner["user_cities"] = Utilities_Static::getPhotoutility()->getUploadCitiesForUser($albumOwner->_id);
  1852. $owner["photo_profile_url"] = Utilities_Static::getProfilePhotoURL($albumOwner);
  1853. $owner["user_type"] = ucfirst($albumOwner->type);
  1854. if (isset($albumOwner->gender)) {
  1855. $owner["user_gender"] = ucfirst($albumOwner->gender);
  1856. }
  1857. return array(
  1858. 'photos' => $album,
  1859. 'owner' => $owner
  1860. );
  1861. }
  1862. }
  1863.  
  1864.  
  1865. /**
  1866. * add comment for specified photo
  1867. * @param $objectID as a photo
  1868. * @param $objectType as a type of object
  1869. * @param $userID user of author post
  1870. * @param $comment text comment
  1871. * @return if response code is 200 returns json string format as {"Response":"Request OK"}
  1872. */
  1873. public function postComment($objectID, $objectType, $owner_id, $userID, $comment)
  1874. {
  1875. $viewer = MyMongo_Connection::findOne("users", array("_id" => $userID));
  1876.  
  1877. $comment = htmlspecialchars($comment,ENT_NOQUOTES);
  1878.  
  1879. $commentUtility = Engine_Api::_ ()->getApi ( "commentutility", "core" );
  1880. $hashtagUtility = Engine_Api::_ ()->getApi ( "hashtagutility", "core" );
  1881.  
  1882. $hashtagArray = $hashtagUtility->replaceHashTag($comment);
  1883. $arrayUserMention = $hashtagUtility->replaceMention($comment);
  1884. foreach (array_keys($arrayUserMention, $viewer->username) as $key) {
  1885. unset($arrayUserMention[$key]);
  1886. }
  1887.  
  1888. $collection_name = Engine_Api::_()->getApi("coolutility", "core")->getItemCollection($objectType);
  1889. $comment_id = null;
  1890. $mentioned = null;
  1891. if (strcasecmp($objectType, 'photo') == 0 || strcasecmp($objectType, 'offer') == 0 || strcasecmp($objectType, 'event') == 0)
  1892. {
  1893. /* Add new comment */
  1894. $creation_date = new MongoDate();
  1895. $_id = hash("md5", $userID. $objectID . $objectType . $creation_date->__toString());
  1896.  
  1897. $params = array();
  1898. $params['_id'] = $_id;
  1899. $params['object_type'] = $objectType;
  1900. $params['object_id'] = $objectID;
  1901. $params['poster_id'] = $userID;
  1902. $params['body'] = $comment;
  1903. $params['creation_date'] = $creation_date;
  1904. MyMongo_Connection::addDocument("comments", $params);
  1905.  
  1906. /* Update "comments_count" in photo */
  1907. //MyMongo_Connection::updateAndOrIncCollectionFields($collection_name, array("_id" => $objectID), array(), array("comments_count" => 1));
  1908. $result = MyMongo_Connection::findAndModify($collection_name, array("_id" => $objectID), array('$inc' => array("comments_count" => 1)), array("comments_count" => 1));
  1909.  
  1910. /* Add Notifications */
  1911. $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
  1912. $object = new stdClass();
  1913. $object->_id = $objectID;
  1914. if($owner_id !== $userID)
  1915. {
  1916. $notifyApi->addNotification($owner_id, $viewer, $object, $objectType, 'commented', array('label' => $objectType));
  1917. }
  1918. //ottengo tutti gli userID degli utenti che hanno commentato l'oggetto corrente
  1919. $arrayUserID = $commentUtility->getAllCommentUsers($objectType, $objectID);
  1920. $pushUserIDs = array(); //conterrà tutti gli utenti a cui inviare la push notification
  1921. foreach($arrayUserID as $userToNotification)
  1922. {
  1923. if (($userToNotification !== $owner_id) && ($userToNotification !== $userID))
  1924. {
  1925. $notifyApi->addNotificationExceptPushNotification($userToNotification, $viewer, $object, $objectType, 'commented_commented', array (
  1926. 'label' => $objectType
  1927. ));
  1928. array_push($pushUserIDs, $userToNotification);
  1929. }
  1930. }
  1931. //se ci sono utenti che hanno commentato
  1932. if(sizeof($pushUserIDs) > 0)
  1933. {
  1934. //invio push notification agli utenti che hanno commentato l'oggetto corrente
  1935. Engine_Api::_()->getApi("activityutility","activity")->sendInstantNotificationToAllPlatformsForMultipleUsers($pushUserIDs);
  1936. }
  1937.  
  1938. if(sizeof($arrayUserMention) == 1) {
  1939. $mentioned = MyMongo_Connection::find("users", array("username" => $arrayUserMention[0]), array("_id" => 1));
  1940. } else if(sizeof($arrayUserMention) > 1) {
  1941. $mentioned = MyMongo_Connection::find("users", array("username" => array('$in' => $arrayUserMention)), array("_id" => 1));
  1942. }
  1943.  
  1944. $pushUserIDs = array(); //conterrà tutti gli utenti a cui inviare la push notification
  1945. foreach ($mentioned as $userMention)
  1946. {
  1947. $notifyApi->addNotificationExceptPushNotification($userMention['_id'], $viewer, $object, $objectType, 'commented_mention', array(
  1948. 'label' => $objectType
  1949. ));
  1950. array_push($pushUserIDs, $userMention['_id']);
  1951. }
  1952. //se ci sono utenti che hanno commentato
  1953. if(sizeof($pushUserIDs) > 0)
  1954. {
  1955. //invio push notification agli utenti che hanno commentato l'oggetto corrente
  1956. Engine_Api::_()->getApi("activityutility","activity")->sendInstantNotificationToAllPlatformsForMultipleUsers($pushUserIDs);
  1957. }
  1958. }
  1959. $comment_id = $params['_id'];
  1960. //aggiungi mapping utente menzionato - commento
  1961. if($mentioned != null && $mentioned->count() > 0)
  1962. {
  1963. $commentUtility->addCommentMappingMentions($mentioned, $comment_id);
  1964. }
  1965. return array (
  1966. 'Response' => 'Request OK' ,
  1967. 'object_type' => Engine_Api::_()->getApi("activityutility","activity")->getOldTypesName($objectType)['object_type'],
  1968. 'comment_id' => $comment_id,
  1969. 'comment_count' => $result['comments_count'] + 1
  1970. );
  1971. }
  1972.  
  1973. /**
  1974. * returns all the available interests formatted as {{"interests_id":"1", "content":"music_rock"},...}
  1975. */
  1976. public function getAvailableInterests() {
  1977. $interestsArray = array();
  1978. $interests = MyMongo_Connection::find("interests");
  1979. foreach ($interests as $int) {
  1980. $interest = array(
  1981. "interest_id" => $int['_id'],
  1982. "content" => $int['_id']
  1983. );
  1984. array_push($interestsArray, $interest);
  1985. }
  1986.  
  1987. return $interestsArray;
  1988. }
  1989.  
  1990. /**
  1991. * returns all the available professionale work field formatted as {{"interests_id":"16", "content":"Advertising"},...}
  1992. */
  1993. public function getAvailableWorkField(){
  1994. $workfieldsArray = array();
  1995. $workfields = MyMongo_Connection::find("workfields");
  1996. foreach ($workfields as $wrk) {
  1997. $workfield = array(
  1998. "id" => $wrk['_id'],
  1999. "text" => $wrk['_id']
  2000. );
  2001. array_push($workfieldsArray, $workfield);
  2002. }
  2003.  
  2004. return $workfieldsArray;
  2005.  
  2006. }
  2007.  
  2008. /**
  2009. * make a COOL for a specified photo
  2010. * @param $objectID as a object
  2011. * @param $objectType as a type of object
  2012. * @param $userID user of author COOL
  2013. * @return if response code is 200 returns json string format as {"numOfCool":"13"}
  2014. */
  2015. public function makeCool($objectID, $objectType, $ownerID, $userID){
  2016. $coolUtility = Engine_Api::_()->getApi('coolutility','core');
  2017. //populate params array
  2018. $params = Array();
  2019. $params['object_type'] = $objectType;
  2020. $params['object_id'] = $objectID;
  2021. $params['cooler_id'] = $userID;
  2022. $params['creation_date'] = new MongoDate();
  2023.  
  2024. MyMongo_Connection::addDocument("cools", $params);
  2025.  
  2026. $collection_name = $coolUtility->getItemCollection($objectType);
  2027.  
  2028. // Add notification for owner of activity (if user and not viewer)
  2029. if ($ownerID !== $userID) {
  2030. Engine_Api::_ ()->getDbtable('notifications', 'activity')->addNotification($ownerID, $userID, $objectID, $objectType, 'liked', array(
  2031. 'label' => $objectType
  2032. ));
  2033. }
  2034. //MyMongo_Connection::updateAndOrIncCollectionFields($collection_name, array("_id" => $objectID), array(), array("cools_count" => 1));
  2035. $result = MyMongo_Connection::findAndModify($collection_name, array("_id" => $objectID), array('$inc' => array("cools_count" => 1)), array("cools_count" => 1));
  2036.  
  2037. // Stats
  2038. Engine_Api::_()->getDbtable('statistics', 'core')->increment('core.likes');
  2039. return array(
  2040. 'numOfCool' => $result['cools_count'] + 1
  2041. );
  2042. }
  2043.  
  2044. /**
  2045. * make an UnCOOL for a specified object
  2046. * @param $objectID as a object
  2047. * @param $objectType as a type of object
  2048. * @param $userID user of author COOL
  2049. * @return if response code is 200 returns json string format as {"numOfCool":"12"}
  2050. */
  2051. public function makeUnCool($objectID, $objectType, $userID) {
  2052. $coolUtility = Engine_Api::_()->getApi('coolutility','core');
  2053.  
  2054. $collection_name = $coolUtility->getItemCollection($objectType);
  2055.  
  2056. $params = Array();
  2057. $params['object_type'] = $objectType;
  2058. $params['object_id'] = $objectID;
  2059. $params['cooler_id'] = $userID;
  2060.  
  2061. MyMongo_Connection::removeDocument("cools", $params);
  2062. $result = MyMongo_Connection::findAndModify($collection_name, array("_id" => $objectID), array('$inc' => array("cools_count" => -1)), array("cools_count" => 1));
  2063.  
  2064. return array(
  2065. 'numOfCool' => $result['cools_count'] -1
  2066. );
  2067. }
  2068.  
  2069. /**
  2070. * send an email to the user's email adress whith link to reset account password.
  2071. * @param $userID
  2072. * @return if response code is 200 returns json string format as {"Response":"Request OK"}
  2073. */
  2074. public function forgotPassword($user) {
  2075. try {
  2076. MyMongo_Connection::removeDocument("user_forgot", array("user_id" => $user->_id));
  2077.  
  2078. // Create a new reset password code
  2079. $code = base_convert(md5($user->salt . $user->email . $user->_id . uniqid(time(), true)), 16, 36);
  2080. MyMongo_Connection::addDocument("user_forgot", array("user_id" => $user->_id, "code" => $code, "creation_date" => new MongoDate()));
  2081.  
  2082. $params =array(
  2083. 'route' => 'user_profile',
  2084. 'reset' => true,
  2085. 'id' => $user->username,
  2086. );
  2087. $route = $params['route'];
  2088. $reset = $params['reset'];
  2089. unset($params['route']);
  2090. unset($params['reset']);
  2091. $recipient_link = Zend_Controller_Front::getInstance()->getRouter()->assemble($params, $route, $reset);
  2092.  
  2093. $appName = Zend_Registry::get('Zend_View')->baseUrl(). "/";
  2094. $gender = "B";
  2095. if(isset($user->gender)) {
  2096. $gender = $user->gender;
  2097. }
  2098.  
  2099. // Send user an email
  2100. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  2101. $objectLink = $appName . "user/auth/reset/code/" . $code . "/uid/" . $user->_id;
  2102. Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, 'core_lostpassword', array(
  2103. 'host' => $_SERVER['HTTP_HOST'],
  2104. 'email' => $user->email,
  2105. 'date' => time(),
  2106. 'recipient_title' => $user->username,
  2107. 'recipient_link' => $recipient_link,
  2108. 'recipient_photo' => $appName."application/modules/User/externals/images/nophoto_user_thumb_profile_".$gender.".jpg",
  2109. 'object_link' => $objectLink,
  2110. 'queue' => false,
  2111. ));
  2112.  
  2113. return array(
  2114. 'Response' => 'Request OK'
  2115. );
  2116. } catch( Exception $e ) {
  2117. $errorArray = array('error', $e);
  2118. return $errorArray;
  2119. }
  2120. }
  2121.  
  2122. /**
  2123. * it allows user to set new password.
  2124. * @param $user
  2125. * @param $newPsw the new password choosen for account authentication
  2126. * @return if response code is 200 returns json string format as {"Response":"Request OK"}
  2127. */
  2128. public function setNewPassword($user, $newPsw){
  2129. !isset($user->salt) ? $salt = (string)rand(1000000, 9999999) : $salt = $user->salt;
  2130. $hashed_psw = md5(
  2131. Engine_Api::_()->getApi('settings', 'core')->getSetting('core.secret', 'staticSalt') .
  2132. $newPsw .
  2133. $salt
  2134. );
  2135.  
  2136. try {
  2137. MyMongo_Connection::removeDocument("user_forgot", array("user_id" => $user->_id));
  2138. MyMongo_Connection::updateCollectionFields("users", array("_id" => $user->_id), array("password" => $hashed_psw, "salt" => $salt));
  2139.  
  2140. return array(
  2141. 'Response' => 'Request OK'
  2142. );
  2143.  
  2144. } catch( Exception $e ) {
  2145. $errorArray = array('error', $e);
  2146. return $errorArray;
  2147. }
  2148. }
  2149.  
  2150. /**
  2151. * Updates the user information
  2152. *
  2153. * @param
  2154. * $userID
  2155. * @param $updated_fields a
  2156. * JSON string that contains all the updated fields
  2157. * @return if response code is 200 returns json string format as {"Response":"Request OK"}
  2158. */
  2159. public function updateUserInfo($userID, $updated_fields) {
  2160. $updatedArrays = Zend_Json_Decoder::decode($updated_fields, true); // decode JSON to associative array
  2161. $userUtility = Engine_Api::_()->getApi('userutility', 'core');
  2162.  
  2163. $userObject = $userUtility->getUser($userID);
  2164. $accountType = $userObject->type;
  2165. $update = $updatedArrays[0];
  2166.  
  2167. if (array_key_exists("gender", $update) && (strcasecmp($accountType, "business") == 0)) {
  2168. return array (
  2169. "error",
  2170. "gender parameter is not allowed for business account"
  2171. );
  2172. } elseif (array_key_exists("gender", $update)) {
  2173. $genderchar = $update['gender'];
  2174. if ($genderchar !== "M" && $genderchar !== "W") {
  2175. return (array (
  2176. "error" , "admitted values for gender parameter are M value for man, W value for woman"
  2177. ));
  2178. }
  2179. }
  2180. if (array_key_exists("birthday", $update) && (strcasecmp($accountType, "business") == 0)) {
  2181. return array (
  2182. "error",
  2183. "birthday parameter is not allowed for business account"
  2184. );
  2185. } elseif (array_key_exists("birthday", $update)){
  2186. $resultCheckDate = $this->checkFormatDate($update['birthday']);
  2187. if (!$resultCheckDate[0]){
  2188. return (array ("error" , $resultCheckDate[1]));
  2189. }
  2190. }
  2191. if (array_key_exists("company_name", $update) && (strcasecmp($accountType, "personal") == 0)) {
  2192. return array (
  2193. "error",
  2194. "company_name parameter is not allowed for personal account"
  2195. );
  2196. }
  2197. if (array_key_exists("country", $update) && (strcasecmp($accountType, "personal") == 0)) {
  2198. return array (
  2199. "error",
  2200. "country parameter is not allowed for personal account"
  2201. );
  2202. }
  2203. if (array_key_exists("vat", $update) && (strcasecmp($accountType, "personal") == 0)) {
  2204. return array (
  2205. "error",
  2206. "vat parameter is not allowed for personal account"
  2207. );
  2208. }
  2209. if (array_key_exists("professional_work_fld", $update) && (strcasecmp($accountType, "personal") == 0)) {
  2210. return array(
  2211. "error",
  2212. "professional_work_fld parameter is not allowed for personal account"
  2213. );
  2214. }
  2215. if (array_key_exists("professional_work_fld", $update)) {
  2216. $count = MyMongo_Connection::count("workfields", array("_id" => $update['professional_work_fld']));
  2217. if($count <= 0) {
  2218. return array(
  2219. "error",
  2220. "professional_work_fld value sent is not valid"
  2221. );
  2222. }
  2223. }
  2224. if (array_key_exists("profile_photo", $update) && (!(array_key_exists("profile_photo_rsz", $update)))) {
  2225. return (array (
  2226. "error" ,
  2227. "both or neither parameters (profile_photo, profile_photo_rsz) must be provided"
  2228. ));
  2229. }
  2230. if (!(array_key_exists("profile_photo", $update)) && array_key_exists ( "profile_photo_rsz", $update )) {
  2231. return (array (
  2232. "error" ,
  2233. "both or neither parameters (profile_photo, profile_photo_rsz) must be provided"
  2234. ));
  2235. }
  2236. if (array_key_exists("flow_photo", $update) && (!(array_key_exists ( "flow_photo_rsz", $update )))) {
  2237. return (array (
  2238. "error" ,
  2239. "both or neither parameters (flow_photo, flow_photo_rsz) must be provided"
  2240. ));
  2241. }
  2242. if (! (array_key_exists("flow_photo", $update)) && array_key_exists ( "flow_photo_rsz", $update )) {
  2243. return (array (
  2244. "error" ,
  2245. "both or neither parameters (flow_photo, flow_photo_rsz) must be provided"
  2246. ));
  2247. }
  2248.  
  2249. try {
  2250. $updateArray = array();
  2251.  
  2252. if (array_key_exists ( "name", $update )) {
  2253. $updateArray['name'] = $update ['name'];
  2254. }
  2255. if (array_key_exists ( "surname", $update )) {
  2256. $updateArray['surname'] = $update ['surname'];
  2257. }
  2258. if (array_key_exists ( "gender", $update )) {
  2259. $updateArray['gender'] = ucfirst($update['gender']);
  2260. }
  2261. if (array_key_exists ( "birthday", $update )) {
  2262. $updateArray['birthdate'] = new MongoDate(strtotime($update['birthday']));
  2263. }
  2264.  
  2265. if (array_key_exists("location", $update )) {
  2266. $updateArray['location'] = $update['location'];
  2267. }
  2268. if (array_key_exists("company_name", $update)) {
  2269. $updateArray['company'] = $update['company_name'];
  2270. }
  2271. if (array_key_exists ( "country", $update )) {
  2272. $updateArray['country'] = $update['country'];
  2273. }
  2274. if (array_key_exists ( "vat", $update )) {
  2275. $updateArray['vat'] = $update['vat'];
  2276. }
  2277. if (array_key_exists ( "personal_status", $update )) {
  2278. $updateArray['status'] = htmlspecialchars($update['personal_status'],ENT_NOQUOTES);
  2279. }
  2280. if (array_key_exists ( "professional_work_fld", $update )) {
  2281. $updateArray['workfield'] = $update['professional_work_fld'];
  2282. }
  2283.  
  2284. if (array_key_exists ( "interests", $update )) {
  2285. $updateArray['interests'] = explode(',',$update ['interests']);
  2286. }
  2287. if (array_key_exists("profile_photo", $update) && array_key_exists("profile_photo_rsz", $update)) {
  2288. // the configuration (ini) file where are written paths
  2289. $fullpathConfFile = dirname ( dirname ( __FILE__ ) ) . "/settings/paths.ini";
  2290. // get the array with property refers paths (it reads path.ini)
  2291. $arrayPathProp = $this->getPropertyArray ( $fullpathConfFile );
  2292. $temporaryPath = $arrayPathProp ['temporaryPath'];
  2293.  
  2294. // this is the photo name compliant to SocialEngine
  2295. $photoCompliantName = md5 ( uniqid ( microtime () ) );
  2296.  
  2297. // create the phisically image in the specified path
  2298. $imagebase64 = $update ['profile_photo'];
  2299. $imagebase64 = str_replace ( " ", "+", $imagebase64 );
  2300. if (strlen($imagebase64) == 0) {
  2301. $updateArray['fullsize_profilephoto_url'] = "";
  2302. $updateArray['cropped_profilephoto_url'] = "";
  2303. } else {
  2304. list($x, $y, $w, $h) = explode(':', $update['profile_photo_rsz']);
  2305. $createFile = $this->createImageProfileAndFlowFromBase64String ( $imagebase64, $temporaryPath, $photoCompliantName );
  2306. $extension = $createFile['extension'];
  2307. $filesize = $createFile['filesize'];
  2308. $pathImage = $createFile['pathimage'];
  2309.  
  2310. if(isset($createFile['pathimage']) && $createFile['pathimage'] != null && $createFile['pathimage'] != "") {
  2311. $imgExpl = explode("/", $pathImage);
  2312. $img = $imgExpl[sizeof($imgExpl)-1];
  2313. $img_name = explode(".", $img)[0];
  2314.  
  2315. $final_img_name = "public/user/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
  2316. $s3 = new s3upload_S3(awsAccessKey, awsSecretKey);
  2317.  
  2318. // Convert main photo to Progressive JPEG if img type is .jpg or .jpeg
  2319. if($extension == "jpg" || $extension == "jpeg") {
  2320. $im = imagecreatefromjpeg($pathImage);
  2321. imageinterlace($im , true);
  2322. imagejpeg($im , $pathImage, 100);
  2323. imagedestroy($im);
  2324. }
  2325.  
  2326. if ($s3->putObjectFile($pathImage, bucket, $final_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
  2327. $updateArray['fullsize_profilephoto_url'] = $final_img_name;
  2328. // handle cropped photo
  2329. $iProfilePath = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'temporary' . DIRECTORY_SEPARATOR . uniqid($img_name) . '_is.' . $extension;
  2330. $final_croppped_img_name = "public/user/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
  2331. $imageOriginal = Engine_Image::factory();
  2332. $imageOriginal->open($pathImage)->resample($x, $y, $w, $h, 120, 120)->write($iProfilePath)->destroy();
  2333.  
  2334. // Convert main photo to Progressive JPEG if img type is .jpg or .jpeg
  2335. if($extension == "jpg" || $extension == "jpeg") {
  2336. $im = imagecreatefromjpeg($iProfilePath);
  2337. imageinterlace($im , true);
  2338. imagejpeg($im , $iProfilePath, 100);
  2339. imagedestroy($im);
  2340. }
  2341.  
  2342. if ($s3->putObjectFile($iProfilePath, bucket, $final_croppped_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
  2343. $val = unlink($iProfilePath);
  2344. if(!$val) {
  2345. Utilities_Static::log("ERROR on unlink file: ".$iProfilePath);
  2346. }
  2347. $updateArray['cropped_profilephoto_url'] = $final_croppped_img_name;
  2348. } else {
  2349. Utilities_Static::log("ERROR while uploading file: " . $iProfilePath);
  2350. @unlink($iProfilePath);
  2351. $errorArray = array (
  2352. 'error',
  2353. 'db error'
  2354. );
  2355. return $errorArray;
  2356. }
  2357. @unlink($pathImage);
  2358. } else {
  2359. Utilities_Static::log("ERROR while uploading file: " . $iMainPath);
  2360. @unlink($pathImage);
  2361. $errorArray = array (
  2362. 'error',
  2363. 'db error'
  2364. );
  2365. return $errorArray;
  2366. }
  2367. } else {
  2368. $errorArray = array (
  2369. 'error',
  2370. 'db error'
  2371. );
  2372. return $errorArray;
  2373. }
  2374. }
  2375. }
  2376.  
  2377. if (array_key_exists ( "flow_photo", $update ) && array_key_exists ( "flow_photo_rsz", $update )) {
  2378. // the configuration (ini) file where are written paths
  2379. $fullpathConfFile = dirname ( dirname ( __FILE__ ) ) . "/settings/paths.ini";
  2380. // get the array with property refers paths (it reads path.ini)
  2381. $arrayPathProp = $this->getPropertyArray ( $fullpathConfFile );
  2382. $temporaryPath = $arrayPathProp ['temporaryPathFlowPhoto'];
  2383.  
  2384. // this is the photo name compliant to SocialEngine
  2385. $photoCompliantName = md5 ( uniqid ( microtime () ) );
  2386.  
  2387. // create the phisically image in the specified path
  2388. $imagebase64 = $update ['flow_photo'];
  2389. $imagebase64 = str_replace ( " ", "+", $imagebase64 );
  2390.  
  2391. if (strlen ( $imagebase64 ) == 0) {
  2392. $updateArray['fullsize_flowphoto_url'] = "";
  2393. $updateArray['cropped_flowphoto_url'] = "";
  2394. } else {
  2395. list($x, $y, $w, $h) = explode(':', $update['flow_photo_rsz']);
  2396. $createFile = $this->createImageProfileAndFlowFromBase64String ( $imagebase64, $temporaryPath, $photoCompliantName );
  2397. $extension = $createFile ['extension'];
  2398. $filesize = $createFile ['filesize'];
  2399. $pathImage = $createFile ['pathimage'];
  2400.  
  2401. if(isset($createFile['pathimage']) && $createFile['pathimage'] != null && $createFile['pathimage'] != "") {
  2402. $imgExpl = explode("/", $pathImage);
  2403. $img = $imgExpl[sizeof($imgExpl)-1];
  2404. $img_name = explode(".", $img)[0];
  2405.  
  2406. // create a photo and file record
  2407. $final_img_name = "public/user_ext/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
  2408. $s3 = new s3upload_S3(awsAccessKey, awsSecretKey);
  2409. if ($s3->putObjectFile($pathImage, bucket, $final_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
  2410. $updateArray['fullsize_flowphoto_url'] = $final_img_name;
  2411. // handle cropped photo
  2412. $iFlowPath = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'temporary' . DIRECTORY_SEPARATOR . uniqid($img_name) . '_is.' . $extension;
  2413. $final_croppped_img_name = "public/user_ext/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
  2414. $imageOriginal = Engine_Image::factory();
  2415. $imageOriginal->open($pathImage)->resample($x, $y, $w, $h, 790, 140)->write($iFlowPath)->destroy();
  2416. if ($s3->putObjectFile($iFlowPath, bucket, $final_croppped_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
  2417. $val = unlink($iFlowPath);
  2418. if(!$val) {
  2419. Utilities_Static::log("ERROR on unlink file: ".$iFlowPath);
  2420. }
  2421. $updateArray['cropped_flowphoto_url'] = $final_croppped_img_name;
  2422. } else {
  2423. Utilities_Static::log("ERROR while uploading file: " . $iFlowPath);
  2424. @unlink($iFlowPath);
  2425. $errorArray = array (
  2426. 'error',
  2427. 'db error'
  2428. );
  2429. return $errorArray;
  2430. }
  2431. @unlink($pathImage);
  2432. } else {
  2433. Utilities_Static::log("ERROR while uploading file: " . $pathImage);
  2434. @unlink($pathImage);
  2435. $errorArray = array (
  2436. 'error',
  2437. 'db error'
  2438. );
  2439. return $errorArray;
  2440. }
  2441. } else {
  2442. $errorArray = array (
  2443. 'error',
  2444. 'db error'
  2445. );
  2446. return $errorArray;
  2447. }
  2448. }
  2449. }
  2450.  
  2451. // Update user document
  2452. $unsetArray = array();
  2453. if(isset($updateArray['fullsize_profilephoto_url']) && $updateArray['fullsize_profilephoto_url'] === "") {
  2454. // unset profile photo
  2455. $unsetArray['fullsize_profilephoto_url'] = 1;
  2456. $unsetArray['cropped_profilephoto_url'] = 1;
  2457. unset($updateArray['fullsize_profilephoto_url']);
  2458. unset($updateArray['cropped_profilephoto_url']);
  2459. }
  2460. if(isset($updateArray['fullsize_flowphoto_url']) && $updateArray['fullsize_flowphoto_url'] === "") {
  2461. //unset flow photo
  2462. $unsetArray['fullsize_flowphoto_url'] = 1;
  2463. $unsetArray['cropped_flowphoto_url'] = 1;
  2464. unset($updateArray['fullsize_flowphoto_url']);
  2465. unset($updateArray['cropped_flowphoto_url']);
  2466. }
  2467. if(sizeof($updateArray) > 0)
  2468. {
  2469. MyMongo_Connection::setAndUnsetFields("users", array("_id" => $userID), $updateArray, $unsetArray);
  2470. }
  2471. else
  2472. {
  2473. if(sizeof($unsetArray) > 0)
  2474. {
  2475. MyMongo_Connection::unsetFields("users", array("_id" => $userID), $unsetArray);
  2476. }
  2477. }
  2478.  
  2479. } catch(Exception $e) {
  2480. $errorArray = array (
  2481. 'error',
  2482. 'db error'
  2483. );
  2484. return $errorArray;
  2485. }
  2486. return array (
  2487. 'Response' => 'Request OK'
  2488. );
  2489. }
  2490.  
  2491. private function generateRandomValue() {
  2492. $rand = dechex(rand(0,99));
  2493. if(strlen($rand) == 1) {
  2494. $rand = "0" . $rand;
  2495. }
  2496. return $rand;
  2497. }
  2498.  
  2499. /**
  2500. * This method gets field_id associated to the label ($param) in record given ($metaInf)
  2501. * @param $param label
  2502. * @param $metaInf record
  2503. * @return field_id
  2504. */
  2505. public function getFieldIdMetaInfoUser($param, $metaInf){
  2506. foreach ($metaInf as $inf){
  2507. if (strcasecmp($inf["label"], $param) == 0){
  2508. return $inf["field_id"];
  2509. }
  2510. }
  2511. }
  2512. /**
  2513. * This method return number associate to the gender given ($genderString could be m[male] or w[female])
  2514. * @param $genderString
  2515. * @return a number (2,3)
  2516. */
  2517. public function getGender($genderString){
  2518. //$log = Zend_Registry::get ( 'Zend_Log' );
  2519. $queryMale = "SELECT option_id FROM `engine4_user_fields_options` WHERE label='M' AND field_id=5";
  2520. $queryFemale = "SELECT option_id FROM `engine4_user_fields_options` WHERE label='W' AND field_id=5";
  2521. if (strcasecmp("m",$genderString) == 0){
  2522. $adapter = Zend_Db_Table_Abstract::getDefaultAdapter ();
  2523. $stmt = $adapter->query ( $queryMale );
  2524. $code = $stmt->fetchAll ();
  2525. return $code[0]['option_id'];
  2526. }
  2527. if (strcasecmp("w",$genderString) == 0){
  2528. $adapter = Zend_Db_Table_Abstract::getDefaultAdapter ();
  2529. $stmt = $adapter->query ( $queryFemale );
  2530. $code = $stmt->fetchAll ();
  2531. return $code[0]['option_id'];
  2532. }
  2533. return null;
  2534. }
  2535.  
  2536. /**
  2537. * This method check if a data is valid and if birth date is a valid date
  2538. * for socialmatic policy
  2539. * @param $date
  2540. * @return array(boolean,string) [string is a message]
  2541. */
  2542. public function checkFormatDate($date) {
  2543. // value string must be in the form of yyyy-mm-dd
  2544. if (preg_match ( "/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date )) {
  2545. $minAge = 12;
  2546.  
  2547. // Validate for users over X years only
  2548. $date = strtotime ($date);
  2549. // The age to be over, over +18
  2550. $min = strtotime("+" . $minAge . " years", $date);
  2551. if (time() < $min) {
  2552. return array(false,"you are too young");
  2553. }
  2554. return array(true,"");
  2555. } else {
  2556. return array(false,"birthday field is incorrect. Birthday field value string must be in the form of yyyy-mm-dd");
  2557. }
  2558. }
  2559.  
  2560. /**
  2561. * Create a record in DB for table file storage to store info about profile photo.
  2562. * @param $userID
  2563. * @param $extension
  2564. * @param $photoCompliantName
  2565. * @param $filesize
  2566. * @param $photoCompliantName
  2567. * @return file_id for created file
  2568. */
  2569. public function createFileRecordProfilePhoto($userID, $extension, $photoCompliantName, $filesize, $coordinates, $pathImage, $temporaryPath) {
  2570. $storage_service = Engine_Api::_()->getDbTable('services','storage')->getService(Engine_Api::_()->getDbTable('services','storage')->getDefaultServiceIdentity());
  2571. $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
  2572. $fullpathConfFile = dirname ( dirname ( __FILE__ ) ) . "/settings/paths.ini";
  2573. $arrProp = $this->getPropertyArray ( $fullpathConfFile );
  2574. $storagePath = $arrProp ['localPathImage'] . $photoCompliantName . "_m." . $extension;
  2575. $storageThumbPath = $arrProp ['localPathImage'] . $photoCompliantName . "_s." . $extension;
  2576.  
  2577. $paramsMain = array(
  2578. 'parent_type' => "user",
  2579. 'parent_id' => $userID,
  2580. 'user_id' => $userID,
  2581. 'name' => $photoCompliantName."_m.".$extension,
  2582. );
  2583. $iMain = $filesTable->createFile($storagePath, $paramsMain);
  2584.  
  2585. $iProfilePath = $temporaryPath . $photoCompliantName . '_s.' . $extension;
  2586. list($myx, $myy, $myw, $myh) = explode(':', $coordinates);
  2587. $image = Engine_Image::factory();
  2588. $image->open($pathImage);
  2589. $image->resample($myx, $myy, $myw, $myh, 120, 120)->write($iProfilePath)->destroy();
  2590.  
  2591. $paramsThumb = array(
  2592. 'parent_type' => "user",
  2593. 'parent_id' => $userID,
  2594. 'user_id' => $userID,
  2595. 'name' => $photoCompliantName."_s.".$extension,
  2596. );
  2597.  
  2598.  
  2599. $iProfile = $filesTable->createFile($storageThumbPath, $paramsThumb);
  2600.  
  2601. $iMain->bridge($iProfile, 'thumb.profile');
  2602.  
  2603. if($storage_service->getType() == "s3") {
  2604. // Remove temp files
  2605. @unlink($storagePath);
  2606. @unlink($storageThumbPath);
  2607. }
  2608.  
  2609.  
  2610. return $iMain->file_id;
  2611. }
  2612.  
  2613. /**
  2614. * Create a record for table file storage to store info about flow photo.
  2615. * @param $userID
  2616. * @param $extension
  2617. * @param $photoCompliantName
  2618. * @param $filesize
  2619. * @param $photoCompliantName
  2620. * @return unknown
  2621. */
  2622. public function createFileRecordFlowPhoto($userID, $extension, $photoCompliantName, $filesize, $coordinates, $pathImage, $temporaryPath){
  2623. $storage_service = Engine_Api::_()->getDbTable('services','storage')->getService(Engine_Api::_()->getDbTable('services','storage')->getDefaultServiceIdentity());
  2624. $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
  2625. $fullpathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
  2626. $arrProp = $this->getPropertyArray($fullpathConfFile);
  2627. $storagePath = $arrProp['localPathFlowPhoto'].$photoCompliantName."_m.".$extension;
  2628. $storageThumbPath = $arrProp ['localPathFlowPhoto'] . $photoCompliantName . "_s." . $extension;
  2629.  
  2630. $paramsMain = array(
  2631. 'parent_type' => "user_ext",
  2632. 'parent_id' => $userID,
  2633. 'user_id' => $userID,
  2634. 'name' => $photoCompliantName."_m.".$extension,
  2635. );
  2636. $iMain = $filesTable->createFile($storagePath, $paramsMain);
  2637.  
  2638. $iProfilePath = $temporaryPath . $photoCompliantName . '_s.' . $extension;
  2639. list($myx, $myy, $myw, $myh) = explode(':', $coordinates);
  2640. $image = Engine_Image::factory();
  2641. $image->open($pathImage);
  2642. $image->resample($myx, $myy, $myw, $myh, 790, 140)->write($iProfilePath)->destroy();
  2643.  
  2644. $paramsThumb = array(
  2645. 'parent_type' => "user_ext",
  2646. 'parent_id' => $userID,
  2647. 'user_id' => $userID,
  2648. 'name' => $photoCompliantName."_s.".$extension,
  2649. );
  2650.  
  2651.  
  2652. $iProfile = $filesTable->createFile($storageThumbPath, $paramsThumb);
  2653.  
  2654. $iMain->bridge($iProfile, 'thumb.flow');
  2655.  
  2656. if($storage_service->getType() == "s3") {
  2657. // Remove temp files
  2658. @unlink($storagePath);
  2659. @unlink($storageThumbPath);
  2660. }
  2661.  
  2662.  
  2663. return $iMain->file_id;
  2664.  
  2665.  
  2666.  
  2667.  
  2668.  
  2669. }
  2670.  
  2671. /**
  2672. * Create a record for table file storage to store info about cropped photo.
  2673. * @param $coordinates
  2674. * @param $pathImage
  2675. * @param $temporaryPath
  2676. * @param $photoCompliantName
  2677. * @param $idFileParent
  2678. * @param $extension
  2679. * @param $userID
  2680. */
  2681. public function createFileRecordPhotoCrop($coordinates,$pathImage,$temporaryPath,$photoCompliantName,$idFileParent,$extension, $userID){
  2682. $fullpathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
  2683. $arrProp = $this->getPropertyArray($fullpathConfFile);
  2684. $storagePath = $arrProp['localPathImage'].$photoCompliantName."_s.".$extension;
  2685.  
  2686. $iProfilePath = $temporaryPath . $photoCompliantName . '_s.' . $extension;
  2687. list($myx, $myy, $myw, $myh) = explode(':', $coordinates);
  2688. $image = Engine_Image::factory();
  2689. $image->open($pathImage);
  2690. $image->resample($myx, $myy, $myw, $myh, 120, 120)->write($iProfilePath);
  2691. /*resized (thumb) PHOTO*/
  2692. $params['type']= "thumb.profile";
  2693. $params['parent_type'] = "user";
  2694. $params['parent_file_id']= $idFileParent;
  2695. $params['storage_path'] = $storagePath;
  2696. $params['name'] = $photoCompliantName."_s.".$extension;
  2697. $params['parent_id'] = $userID;
  2698. $params['user_id'] = $userID;
  2699. $params['service_id'] = "1";
  2700. $params['extension'] = $extension;
  2701. $params['mime_major'] = "image";
  2702. $params['mime_minor'] = $extension;
  2703. $params['size'] = filesize($pathImage);
  2704. $params['hash'] = md5($photoCompliantName."_s.".$extension);
  2705.  
  2706. //create a record (for thumb) in the albums table
  2707. $file = Engine_Api::_()->getDbtable('files', 'storage')->createRow();
  2708. //insert values
  2709. $file->setFromArray($params);
  2710. //commit
  2711. $file->save();
  2712. }
  2713.  
  2714.  
  2715. /**
  2716. * Create a record for table file storage to store info about cropped flow photo.
  2717. * @param $coordinates
  2718. * @param $pathImage
  2719. * @param $temporaryPath
  2720. * @param $photoCompliantName
  2721. * @param $idFileParent
  2722. * @param $extension
  2723. * @param $userID
  2724. */
  2725. public function createFileRecordFlowCrop($coordinates,$pathImage,$temporaryPath,$photoCompliantName,$idFileParent,$extension, $userID){
  2726. $fullpathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
  2727. $arrProp = $this->getPropertyArray($fullpathConfFile);
  2728. $storagePath = $arrProp['localPathFlowPhoto'].$photoCompliantName."_s.".$extension;
  2729.  
  2730. $iProfilePath = $temporaryPath . $photoCompliantName . '_s.' . $extension;
  2731. list($myx, $myy, $myw, $myh) = explode(':', $coordinates);
  2732. $image = Engine_Image::factory();
  2733. $image->open($pathImage);
  2734. $image->resample($myx, $myy, $myw, $myh, 120, 120)->write($iProfilePath);
  2735. /*resized (thumb) PHOTO*/
  2736. $params['type']= "thumb.flow";
  2737. $params['parent_type'] = "user_ext";
  2738. $params['parent_file_id']= $idFileParent;
  2739. $params['storage_path'] = $storagePath;
  2740. $params['name'] = $photoCompliantName."_s.".$extension;
  2741. $params['parent_id'] = $userID;
  2742. $params['user_id'] = $userID;
  2743. $params['service_id'] = "1";
  2744. $params['extension'] = $extension;
  2745. $params['mime_major'] = "image";
  2746. $params['mime_minor'] = $extension;
  2747. $params['size'] = filesize($pathImage);
  2748. $params['hash'] = md5($photoCompliantName."_s.".$extension);
  2749.  
  2750. //create a record (for thumb) in the albums table
  2751. $file = Engine_Api::_()->getDbtable('files', 'storage')->createRow();
  2752. //insert values
  2753. $file->setFromArray($params);
  2754. //commit
  2755. $file->save();
  2756. }
  2757.  
  2758. /**
  2759. * This method create a image from a base64 string and save it
  2760. * in the specified path.
  2761. * @param $byte the BASE64 string
  2762. * @param $pathToSave path to save image
  2763. * @param $imgName the image's name
  2764. * @return file info created
  2765. */
  2766. public function createImageProfileAndFlowFromBase64String($byte, $pathToSave, $imgName)
  2767. {
  2768. //decode the base64
  2769. $decodedImage=base64_decode($byte);
  2770.  
  2771. //get the mime type array (0 is major (e.g. image) and 1 is minor (e.g. jpeg))
  2772. $mime_arr = $this->getFileMIME($decodedImage);
  2773. //create one photo
  2774. $this->createPhoto($decodedImage, $pathToSave, $imgName, $mime_arr[1] );
  2775. $fullpathFile=$pathToSave.$imgName;
  2776. return array("extension" => $mime_arr[1], "filesize" => strlen($decodedImage), "pathimage" => $fullpathFile."_m.".$mime_arr[1]);
  2777. }
  2778.  
  2779. /**
  2780. * This method create from a photo input a new photo resized.
  2781. * @param $decodedData
  2782. * @param $pathToSave
  2783. * @param $imgName
  2784. * @param $filetype
  2785. */
  2786. public function createPhoto($decodedData, $pathToSave, $imgName, $filetype )
  2787. {
  2788. $fullpathFile=$pathToSave.$imgName;
  2789. @file_put_contents( $fullpathFile."_m.".$filetype, $decodedData );
  2790. chmod($fullpathFile."_m.".$filetype, 0777);
  2791.  
  2792. $name = basename($fullpathFile);
  2793. $path = dirname($fullpathFile);
  2794.  
  2795. $image = Engine_Image::factory();
  2796. $image->open($fullpathFile."_m.".$filetype)->write($fullpathFile."_m.".$filetype)->destroy();
  2797.  
  2798. }
  2799.  
  2800.  
  2801. /**
  2802. * this method allows user to register to Socialmatic Photo Network using mobile app
  2803. * @param $deviceID
  2804. * @param $deviceType
  2805. * @param $registration_fields
  2806. */
  2807. public function userRegistration($deviceID,$deviceType,$registration_fields,$locale) {
  2808. $registrationFields = Zend_Json_Decoder::decode($registration_fields, true); // decode JSON to associative array
  2809. $userUtility = Engine_Api::_()->getApi('userutility', 'core');
  2810. $textUtility = Engine_Api::_()->getApi('textutility', 'core');
  2811. $user_table = Engine_Api::_()->getDbtable('users', 'user');
  2812. $registration = $registrationFields [0];
  2813.  
  2814. $errors = array();
  2815. if (!(array_key_exists("email", $registration)))
  2816. $errors["email"] = "email is mandatory parameter";
  2817. if (!(array_key_exists("nickname", $registration)))
  2818. $errors["nickname"] = "nickname is mandatory parameter";
  2819. if (!(array_key_exists("password", $registration)))
  2820. $errors["password"] = "password is mandatory parameter";
  2821. if (! (array_key_exists("account_type", $registration)))
  2822. $errors["account_type"] = "account_type is mandatory parameter";
  2823. else if (!is_string($registration ['account_type'])) {
  2824. $errors["account_type"] = "account_type value admitted is string";
  2825. return array (
  2826. "Response" => "Request KO",
  2827. "errors" => $errors
  2828. );
  2829. } else if (!((strcasecmp($registration['account_type'], "0" ) == 0) || (strcasecmp($registration['account_type'], "1" ) == 0))) {
  2830. $errors["account_type"] = "account_type value admitted are 0 or 1";
  2831. return array (
  2832. "Response" => "Request KO",
  2833. "errors" => $errors
  2834. );
  2835. } else {
  2836. $account_type = $registration ['account_type'];
  2837. }
  2838. if (! array_key_exists("name", $registration)) {
  2839. $errors["name"] = "name is mandatory parameter";
  2840. } elseif (strlen($registration["name"]) == 0) {
  2841. $errors["name"] = "name cannot be empty";
  2842. } elseif(!preg_match('/^[a-zA-Z]+[a-zA-Z ]+$/', $registration["name"])) {
  2843. $errors["name"] = "name is not valid";
  2844. }
  2845. if (! array_key_exists("surname", $registration)) {
  2846. $errors["surname"] = "surname is mandatory parameter";
  2847. } elseif (strlen($registration["surname"]) == 0) {
  2848. $errors["surname"] = "surname cannot be empty";
  2849. } elseif(!preg_match('/^[a-zA-Z]+[a-zA-Z ]+$/', $registration["surname"])) {
  2850. $errors["surname"] = "surname is not valid";
  2851. }
  2852.  
  2853. $genderchar = $registration['gender'];
  2854. if (strcasecmp($account_type, "0") == 0 && (! array_key_exists("gender", $registration))) {
  2855. $errors["gender"] = "gender parameter is mandatory for personal account";
  2856. } elseif (strcasecmp($account_type, "1") == 0 && (array_key_exists("gender", $registration))) {
  2857. $errors["gender"] = "gender parameter is not allowed for business account";
  2858. }elseif (strcasecmp($account_type, "0") == 0 && array_key_exists("gender", $registration) && $genderchar != "M" && $genderchar != "W") {
  2859. $errors["gender"] = "admitted values for gender parameter are M value for man, W value for woman";
  2860. }
  2861.  
  2862. $resultCheckDate = $this->checkFormatDate ( $registration ['birthday'] );
  2863. if (array_key_exists ( "birthday", $registration ) && (strcasecmp ( $account_type, "1" ) == 0)) {
  2864. $errors["birthday"] = "parameter birthday is not allowed for business account" ;
  2865. } elseif (!(array_key_exists ( "birthday", $registration )) && ( strcasecmp ( $account_type, "0" ) == 0)) {
  2866. $errors["birthday"] = "birthday parameter is mandatory for personal account";
  2867. } elseif ((array_key_exists ( "birthday", $registration )) && ( strcasecmp ( $account_type, "0" ) == 0) && !($resultCheckDate [0])) {
  2868. $errors["birthday"] = $resultCheckDate [1] ;
  2869. }
  2870.  
  2871. if (! array_key_exists("location", $registration)) {
  2872. $errors["location"] = "location is mandatory parameter";
  2873. } elseif (strlen($registration["location"]) == 0) {
  2874. $errors["location"] = "location cannot be empty";
  2875. } elseif($textUtility->isThereEmoji($registration["location"])) {
  2876. $errors["location"] = "location is not valid";
  2877. }
  2878. if (array_key_exists("company_name", $registration) && strcasecmp($account_type, "0") == 0) {
  2879. $errors["company_name"] = "company_name parameter is not allowed for personal account";
  2880. }
  2881. if (!(array_key_exists("company_name", $registration)) && strcasecmp($account_type, "1") == 0) {
  2882. $errors["company_name"] = "company_name parameter is mandatory for business account";
  2883. } elseif ((strlen($registration["company_name"]) == 0) && strcasecmp($account_type, "1") == 0) {
  2884. $errors["company_name"] = "company_name cannot be empty";
  2885. } elseif($textUtility->isThereEmoji($registration["company_name"]) && strcasecmp($account_type, "1") == 0) {
  2886. $errors["company_name"] = "company_name is not valid";
  2887. }
  2888.  
  2889. if (array_key_exists("country", $registration) && strcasecmp($account_type, "0") == 0) {
  2890. $errors["country"] = "country parameter is not allowed for personal account";
  2891. }
  2892. if (! (array_key_exists("country", $registration)) && strcasecmp($account_type, "1") == 0) {
  2893. $errors["country"] = "country parameter is mandatory for business account";
  2894. } elseif ((strlen($registration["country"]) == 0) && strcasecmp($account_type, "1") == 0) {
  2895. $errors["country"] = "country cannot be empty";
  2896. }
  2897.  
  2898. if (array_key_exists("vat", $registration) && strcasecmp($account_type, "0") == 0) {
  2899. $errors["vat"] = "vat parameter is not allowed for personal account";
  2900. }
  2901. if (! (array_key_exists("vat", $registration)) && strcasecmp($account_type, "1") == 0) {
  2902. $errors["vat"] = "vat parameter is mandatory for business account";
  2903. } elseif ((strlen($registration["vat"]) == 0) && strcasecmp($account_type, "1") == 0) {
  2904. $errors["vat"] = "vat cannot be empty";
  2905. } elseif($textUtility->isThereEmoji($registration["vat"]) && strcasecmp($account_type, "1") == 0) {
  2906. $errors["vat"] = "vat is not valid";
  2907. }
  2908.  
  2909. if (array_key_exists("professional_work_fld", $registration) && strcasecmp($account_type, "0") == 0) {
  2910. $errors["professional_work_fld"] = "professional_work_fld parameter is not allowed for personal account";
  2911. }
  2912. if (! (array_key_exists("professional_work_fld", $registration)) && strcasecmp($account_type, "1") == 0) {
  2913. $errors["professional_work_fld"] = "professional_work_fld parameter is mandatory for business account";
  2914. } elseif ((strlen($registration["professional_work_fld"]) == 0) && strcasecmp($account_type, "1") == 0) {
  2915. $errors["professional_work_fld"] = "professional_work_fld parameter cannot be empty";
  2916. } elseif((strlen($registration["professional_work_fld"]) > 0) && strcasecmp($account_type, "1") == 0) {
  2917. $count = MyMongo_Connection::count("workfields", array("_id" => $registration["professional_work_fld"]));
  2918. if($count != 1) {
  2919. $errors["professional_work_fld"] = "professional_work_fld value not allowed";
  2920. }
  2921. }
  2922.  
  2923. if (array_key_exists("profile_photo", $registration) && (!(array_key_exists("profile_photo_rsz", $registration)))) {
  2924. $errors["profile_photo profile_photo_rsz"] ="both or neither parameters (profile_photo, profile_photo_rsz) must be provided";
  2925. }
  2926. if (! (array_key_exists("profile_photo", $registration)) && array_key_exists ( "profile_photo_rsz", $registration )) {
  2927. $errors["profile_photo profile_photo_rsz"] ="both or neither parameters (profile_photo, profile_photo_rsz) must be provided";
  2928. }
  2929.  
  2930. if (array_key_exists("email",$registration)) {
  2931. $validator = new Zend_Validate_EmailAddress();
  2932. if (!$validator->isValid($registration["email"])) {
  2933. $errors["email"] = 'You have entered a not valid mail!';
  2934. } else {
  2935. $result = MyMongo_Connection::count("users", array("email" => $registration["email"])); //$user_table->fetchAll($user_table->select()->where('email = ?',$registration["email"]));
  2936. if($result > 0) {
  2937. $errors["email"] = "email already used";
  2938. }
  2939. }
  2940. }
  2941. if (array_key_exists("password",$registration)){
  2942. if (strlen($registration["password"]) < 6 || strlen($registration["password"]) > 32)
  2943. $errors["password"] = "password must be at least 6 and less than 32 characters long";
  2944. }
  2945. if (array_key_exists("nickname", $registration)) {
  2946. if(strlen(trim($registration['nickname'])) < 4 || strlen(trim($registration['nickname'])) > 32) {
  2947. $errors["nickname"] = "nickname must be at least 6 and less than 32 characters long";
  2948. } else {
  2949. $userExtra = Engine_Api::_()->getApi('userextra', 'user');
  2950. $nicknameDenied = $userExtra->getNicknameDeniedFromSettings();
  2951. if (in_array(strtolower($registration["nickname"]), $nicknameDenied)){
  2952. $errors["nickname"] = "nickname not allowed";
  2953. } elseif (!preg_match('/^[a-zA-Z][a-zA-Z0-9]*$/i', $registration['nickname'])) {
  2954. $errors["nickname"] = "nickname must be contains only letters and numbers";
  2955. } else {
  2956. $result = MyMongo_Connection::count("users", array("username" => $registration["nickname"])); //$user_table->fetchAll($user_table->select()->where('username = ?',$registration["nickname"]));
  2957. if ($result > 0) {
  2958. $errors["nickname"] = "nickname already used";
  2959. }
  2960. }
  2961. }
  2962. }
  2963.  
  2964. if (sizeof($errors) > 0){
  2965. return array(
  2966. "Response" => "Request KO",
  2967. "errors" => $errors
  2968. );
  2969. }
  2970.  
  2971. try {
  2972. // IP
  2973. $ipObj = new Engine_IP();
  2974.  
  2975. // user key
  2976. $charid = strtoupper(md5(uniqid(rand(), true)));
  2977. $user_key = substr($charid, 0, 8) . '-' .
  2978. substr($charid, 8, 8) . '-' .
  2979. substr($charid, 16, 8) . '-' .
  2980. substr($charid, 24, 8);
  2981.  
  2982. $creation_date = new MongoDate();
  2983. $_id = hash("md5", $registration["surname"] . $creation_date->__toString());
  2984.  
  2985. $type = "personal";
  2986. if(strcasecmp($registration ['account_type'], "1") == 0) {
  2987. $type = "business";
  2988. }
  2989.  
  2990. // password
  2991. $static_salt = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.secret', 'staticSalt');
  2992. $salt = (string)rand(1000000, 9999999);
  2993. $hashed_psw = md5($static_salt . $registration['password'] . $salt);
  2994.  
  2995. $parametersArray = array();
  2996. $parametersArray["_id"] = $_id;
  2997. $parametersArray["email"] = $registration["email"];
  2998. $parametersArray["username"] = $registration["nickname"];
  2999. $parametersArray["name"] = $registration["name"];
  3000. $parametersArray["surname"] = $registration["surname"];
  3001. $parametersArray["type"] = $type;
  3002. $parametersArray["status"] = "Welcome!";
  3003. $parametersArray["password"] = $hashed_psw;
  3004. $parametersArray["salt"] = $salt;
  3005. $parametersArray["locale"] = $locale;
  3006. $parametersArray["language"] = $locale;
  3007. $parametersArray["timezone"] = Zend_Registry::get('timezone');
  3008. $parametersArray["level"] = intval(4);
  3009. $parametersArray["invites_used"] = intval(0);
  3010. $parametersArray["extra_invites"] = intval(0);
  3011. $parametersArray["enabled"] = false;
  3012. $parametersArray["disabled_by_admin"] = false;
  3013. $parametersArray["authentic"] = false;
  3014. $parametersArray["creation_date"] = $creation_date;
  3015. $parametersArray["creation_ip"] = $ipObj->toLong();
  3016. $parametersArray["modified_date"] = $creation_date;
  3017. $parametersArray["followers_count"] = intval(0);
  3018. $parametersArray["following_count"] = intval(0);
  3019. $parametersArray["views_count"] = intval(0);
  3020. $parametersArray["updates_subscribed"] = true;
  3021.  
  3022. if (array_key_exists("profile_photo", $registration ) && array_key_exists("profile_photo_rsz", $registration)) {
  3023. // the configuration (ini) file where are written paths
  3024. $fullpathConfFile = dirname ( dirname ( __FILE__ ) ) . "/settings/paths.ini";
  3025. // get the array with property refers paths (it reads path.ini)
  3026. $arrayPathProp = $this->getPropertyArray ( $fullpathConfFile );
  3027. $temporaryPath = $arrayPathProp ['temporaryPath'];
  3028.  
  3029. // this is the photo name compliant to SocialEngine
  3030. $photoCompliantName = md5 ( uniqid ( microtime () ) );
  3031.  
  3032. // create the phisically image in the specified path
  3033. $imagebase64 = $registration ['profile_photo'];
  3034. $imagebase64 = str_replace(" ", "+", $imagebase64);
  3035. $createFile = $this->createImageProfileAndFlowFromBase64String($imagebase64, $temporaryPath, $photoCompliantName);
  3036. $extension = $createFile ['extension'];
  3037. $filesize = $createFile ['filesize'];
  3038. $pathImage = $createFile ['pathimage'];
  3039.  
  3040. if(isset($createFile['pathimage']) && $createFile['pathimage'] != null && $createFile['pathimage'] != "") {
  3041. list($x, $y, $w, $h) = explode(':', $registration['profile_photo_rsz']);
  3042. $imgExpl = explode("/", $pathImage);
  3043. $img = $imgExpl[sizeof($imgExpl)-1];
  3044. $img_name = explode(".", $img)[0];
  3045.  
  3046. $final_img_name = "public/user/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
  3047. $s3 = new s3upload_S3(awsAccessKey, awsSecretKey);
  3048.  
  3049. // Convert main photo to Progressive JPEG if img type is .jpg or .jpeg
  3050. if($extension == "jpg" || $extension == "jpeg") {
  3051. $im = imagecreatefromjpeg($pathImage);
  3052. imageinterlace($im , true);
  3053. imagejpeg($im , $pathImage, 100);
  3054. imagedestroy($im);
  3055. }
  3056.  
  3057. if ($s3->putObjectFile($pathImage, bucket, $final_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
  3058. $parametersArray["fullsize_profilephoto_url"] = $final_img_name;
  3059. // handle cropped photo
  3060. $iProfilePath = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'temporary' . DIRECTORY_SEPARATOR . uniqid($img_name) . '_is.' . $extension;
  3061. $final_croppped_img_name = "public/user/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
  3062. $imageOriginal = Engine_Image::factory();
  3063. $imageOriginal->open($pathImage)->resample($x, $y, $w, $h, 120, 120)->write($iProfilePath)->destroy();
  3064.  
  3065. // Convert thumb photo to Progressive JPEG if img type is .jpg or .jpeg
  3066. if($extension == "jpg" || $extension == "jpeg") {
  3067. $im = imagecreatefromjpeg($iProfilePath);
  3068. imageinterlace($im , true);
  3069. imagejpeg($im , $iProfilePath, 100);
  3070. imagedestroy($im);
  3071. }
  3072.  
  3073. if ($s3->putObjectFile($iProfilePath, bucket, $final_croppped_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
  3074. $val = unlink($iProfilePath);
  3075. if(!$val) {
  3076. Utilities_Static::log("ERROR on unlink file: ".$iProfilePath);
  3077. }
  3078. $parametersArray["cropped_profilephoto_url"] = $final_croppped_img_name;
  3079. } else {
  3080. Utilities_Static::log("ERROR while uploading file: " . $iProfilePath);
  3081. @unlink($iProfilePath);
  3082. unset($parametersArray['fullsize_profilephoto_url']);
  3083. }
  3084. @unlink($pathImage);
  3085. } else {
  3086. Utilities_Static::log("ERROR while uploading file: " . $iMainPath);
  3087. @unlink($pathImage);
  3088. }
  3089. }
  3090. }
  3091.  
  3092. $parametersArray["current_rank"] = intval(0);
  3093. $parametersArray["previous_rank"] = intval(0);
  3094. $parametersArray["update_rank_date"] = $creation_date;
  3095. $parametersArray["enable_msg_enter_btn"] = false;
  3096. $parametersArray["user_key"] = $user_key;
  3097. $parametersArray["is_public"] = true;
  3098.  
  3099. if (array_key_exists("gender", $registration)){
  3100. $parametersArray["gender"] = $registration["gender"];
  3101. }
  3102.  
  3103. if (array_key_exists("birthday",$registration)){
  3104. $parametersArray["birthdate"] = new MongoDate(strtotime($registration["birthday"]));
  3105. }
  3106.  
  3107. if (array_key_exists("location", $registration)) {
  3108. $parametersArray["location"] = $registration["location"];
  3109. }
  3110.  
  3111. if (array_key_exists("company_name",$registration)) {
  3112. $parametersArray["company"] = $registration["company_name"];
  3113. }
  3114.  
  3115. if (array_key_exists("country",$registration)) {//es. US for United States
  3116. $parametersArray["country"] = $registration["country"];
  3117. }
  3118.  
  3119. if (array_key_exists("vat",$registration)) {
  3120. $parametersArray["vat"] = $registration["vat"];
  3121. }
  3122.  
  3123. if (array_key_exists("professional_work_fld",$registration)) {
  3124. $parametersArray["workfield"] = $registration["professional_work_fld"];
  3125. }
  3126.  
  3127. $settings = array();
  3128. $settings['photo_seen'] = false;
  3129. $settings['photo_moved'] = false;
  3130. $settings['message_new'] = false;
  3131. $settings['friend_follow'] = false;
  3132. $settings['commented_mention'] = false;
  3133. $parametersArray["notification_settings"] = $settings;
  3134.  
  3135.  
  3136. MyMongo_Connection::addDocument("users", $parametersArray);
  3137.  
  3138. // send verification mail
  3139. $verify_array = array (
  3140. 'code' => md5($parametersArray["email"] . $parametersArray["creation_date"]->__toString() . Engine_Api::_()->getApi('settings', 'core')->getSetting('core.secret', 'staticSalt') . (string) rand(1000000, 9999999)),
  3141. 'date' => $parametersArray["creation_date"]
  3142. );
  3143.  
  3144. MyMongo_Connection::updateCollectionFields("user_verify", array("user_id" => $parametersArray["_id"]), $verify_array, array('upsert' => true));
  3145.  
  3146. $mailParams = array (
  3147. 'host' => $_SERVER['HTTP_HOST'],
  3148. 'email' => $parametersArray["email"],
  3149. 'date' => time(),
  3150. 'recipient_title' => $parametersArray["username"],
  3151. 'recipient_link' => Utilities_Static::getUserutility()->getUserHref((object)$parametersArray),
  3152. 'recipient_photo' => Utilities_Static::getUserutility()->getUserPhotoURL((object)$parametersArray, true),
  3153. 'queue' => false
  3154. );
  3155.  
  3156. $mailParams['object_link'] = Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'verify'), 'user_signup', true) . '?' . http_build_query(array(
  3157. 'email' => $parametersArray["email"],
  3158. 'verify' => $verify_array["code"]
  3159. ));
  3160.  
  3161. Engine_Api::_()->getApi('mail', 'core')->sendSystem((object)$parametersArray, 'core_verification', $mailParams);
  3162.  
  3163. } catch ( Exception $e ) {
  3164. return array(
  3165. "Response" => "Request KO",
  3166. "errors" => array("DB Error" => "Error while saving data")
  3167. );
  3168. }
  3169. return array (
  3170. 'Response' => 'Request OK'
  3171. );
  3172. }
  3173.  
  3174. /**
  3175. * Consente a $userID di seguire $userIDToFollow
  3176. * @param $userID
  3177. * @param $userIDToFollow
  3178. * @return multitype:string
  3179. */
  3180. public function addFriend($userID, $userIDToFollow)
  3181. {
  3182. //verifico se l'utente sta tentando di seguire se stesso
  3183. if (strcmp ( $userID, $userIDToFollow ) == 0)
  3184. {
  3185. return array (
  3186. 'error',
  3187. 'You cannot befriend yourself'
  3188. );
  3189. }
  3190. $userUtility = Engine_Api::_()->getApi('userutility','core');
  3191. //verifico se $userID non segue l'owner della foto
  3192. if( !$userUtility->isFollowing($userID, $userIDToFollow) )
  3193. {
  3194. //esegue la logica di following (inviando la notifica di nuovo follower all'owner della foto)
  3195. Engine_Api::_()->user()->followSMUser
  3196. (
  3197. MyMongo_Connection::findOne(static::$usersCollection,array('_id' => $userID)),
  3198. MyMongo_Connection::findOne(static::$usersCollection,array('_id' => $userIDToFollow))
  3199. );
  3200. return array ('Response' => 'Request OK');
  3201. }
  3202. else
  3203. {
  3204. return array('error', 'Relation already exists');
  3205. }
  3206. }
  3207.  
  3208. /**
  3209. * it returns the flow of actions for the user that makes the request.
  3210. * @param $userID
  3211. * @param $lastReceivedID
  3212. * @param $numOfActions
  3213. * @param $isMinId: if value of this boolean var is false, then $lastReceivedID corresponds to a max_id
  3214. */
  3215. public function getFlow ($userID,$lastReceivedID,$numOfActions, $isMinId=true)
  3216. {
  3217. $activityUtility = Engine_Api::_()->getApi("activityutility","activity");
  3218. return $activityUtility->getFeed ($userID,$lastReceivedID,$numOfActions, $isMinId, true);
  3219. }
  3220.  
  3221. /**
  3222. *
  3223. * @param $userID
  3224. * @param $photoIDorObject
  3225. * @return returns a string in JSON format
  3226. */
  3227. public function getPhoto ($userID, $photoIDorObject) {
  3228. if(is_string($photoIDorObject)) {
  3229. $photo = MyMongo_Connection::findOne("photos", array("_id" => $photoIDorObject));
  3230. } else {
  3231. $photo = (object) $photoIDorObject;
  3232. }
  3233.  
  3234. $coolUtility = Engine_Api::_()->getApi("coolutility","core");
  3235. $photoUtility = Engine_Api::_()->getApi('photoutility', 'core');
  3236. $userUtility = Engine_Api::_()->getApi('userutility', 'core');
  3237.  
  3238. $photoseeArray = $photoUtility->getPhotoSeeFlattened($photo->_id);
  3239. $photoTags = (array)$photoUtility->getPhotoTags($photo);
  3240.  
  3241. $arrayCities = $photoUtility->getAllCoordinates($photo);
  3242. $uploadCity = $arrayCities[0]["city"];
  3243. $uploadLat = $arrayCities[0]["lat"];
  3244. $uploadLon = $arrayCities[0]["lon"];
  3245. $arrayCities = $photoUtility->getPhotoCities($photo);
  3246.  
  3247. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  3248.  
  3249. $photoURLThumb = SM_BUCKET . $photo->thumb_img["url"];
  3250. $photoURL = SM_BUCKET . $photo->fullsize_img["url"];
  3251.  
  3252. $qrDetails = 'https://'.$_SERVER['HTTP_HOST'].$appName."user/photodetail/view?p=".$photo->_id;
  3253.  
  3254. $already_followed = $userUtility->isFollowing($userID, $photo->owner_id);
  3255.  
  3256. $ownerArray = $this->getUserDetails($photo->owner_id);
  3257. $ownerArray["already_followed"] = $already_followed;
  3258.  
  3259. $pins_counter = $photo->moves_count;
  3260. if(isset($photo->upload_position)) {
  3261. $pins_counter++;
  3262. }
  3263.  
  3264. $user_cool = $coolUtility->isCooler($userID, 'photo', $photo->_id);
  3265.  
  3266. $result = array(
  3267. 'photo_id' => $photo->_id,
  3268. 'photo_description' => $photo->title,
  3269. 'photo_see' => $photoseeArray,
  3270. 'photo_tags' => $photoTags,
  3271. 'photo_miles' => $photo->distance,
  3272. 'upload_city' => urlencode($uploadCity),
  3273. 'upload_lat' => $uploadLat,
  3274. 'upload_lon' => $uploadLon,
  3275. 'map_upload_img_url' => SM_BUCKET . $photo->map_upload_img_url,
  3276. 'upload_date' => $photo->creation_date->sec,
  3277. 'photo_url_thumb' => $photoURLThumb,
  3278. 'photo_url' => $photoURL,
  3279. 'user_cool' => intval($user_cool),
  3280. "pin_counter" => $pins_counter,
  3281. "comment_counter" => $photo->comments_count,
  3282. "cool_counter" => $photo->cools_count,
  3283. 'qr_details' => $qrDetails,
  3284. 'image_orientation' => $photo->img_orientation,
  3285. 'photo_cities' => $arrayCities,
  3286. 'photo_upload_date' => $photo->creation_date->sec
  3287. );
  3288. return array(
  3289. 'photo' => $result,
  3290. 'owner' => $ownerArray
  3291. );
  3292. }
  3293.  
  3294.  
  3295. /**
  3296. * Returns the comments list for a specified object.
  3297. * @param $objectID
  3298. * @param $objectType
  3299. * @return returns a string in JSON format
  3300. */
  3301. public function commentList($objectID, $objectType) {
  3302. $commentsArray = MyMongo_Connection::find("comments", array("object_id" => $objectID, "object_type" => $objectType), array(), array("creation_date" => 1));
  3303.  
  3304. if (sizeof(iterator_to_array($commentsArray)) == 0) {
  3305. $errorArray = array();
  3306. return $errorArray;
  3307. } else {
  3308. $result = array();
  3309. $i = 0;
  3310. foreach ($commentsArray as $comment){
  3311. $userDetails = $this->getUserDetails($comment["poster_id"]);
  3312. $result[$i] = array(
  3313. 'comment_id' => $comment["_id"],
  3314. 'comment_body' => $comment["body"],
  3315. 'comment_date' => $comment["creation_date"]->sec,
  3316. 'poster' => $userDetails
  3317. );
  3318. $i++;
  3319. }
  3320. return $result;
  3321. }
  3322. }
  3323.  
  3324. /**
  3325. *
  3326. * @param $userID
  3327. * @param $recipientList
  3328. * @param $comment
  3329. * @return
  3330. */
  3331. public function sendNewMessage($userID, $recipientList, $comment, $conversationID=null)
  3332. {
  3333. $comment = htmlspecialchars($comment,ENT_NOQUOTES);
  3334. $recipients = explode ( ",", $recipientList );
  3335. //conterrà la lista degli altri utenti a cui sarà inviata la push (se hanno un device)
  3336. $usersToPush = $recipients;
  3337. if (sizeof ( $recipients ) == 0)
  3338. {
  3339. $errorArray = array
  3340. (
  3341. 'error' => 'recipient list is empty'
  3342. );
  3343. return $errorArray;
  3344. }
  3345. $participants = array(); //sarà inserito nell'array da salvare nel db
  3346. $visibleTo = "|".$userID."|"; //stringa che indica che il messaggio deve essere visibile a tutti i partecipanti compreso chi lo scrive
  3347. foreach ( $recipients as $recipient_id )
  3348. {
  3349. if (strcasecmp($userID,$recipient_id) == 0)
  3350. {
  3351. $errorArray = array (
  3352. 'error' => "You can't send a message to yourself "
  3353. );
  3354. return $errorArray;
  3355. }
  3356. array_push($participants, array('user_id' => $recipient_id));
  3357. $visibleTo.="|".$recipient_id."|";
  3358. }
  3359. array_push($participants, array('user_id' => $userID));//anche il creatore del messaggio è un participant per gli altri utenti che ricevono il messaggio
  3360. array_push($recipients, $userID);//per creare il conversationID è necessario anche l'id del creatore del messaggio
  3361. $participantsArray = $recipients;
  3362. if(is_null($conversationID))
  3363. {
  3364. //OTTENGO IL CONVERSATION ID UNIVOCO PER I PARTECIPANTI CORRENTI: INIZIO
  3365. natsort($recipients);
  3366. $conversationID = hash("md5",implode("",$recipients));
  3367. //OTTENGO IL CONVERSATION ID UNIVOCO PER I PARTECIPANTI CORRENTI: FINE
  3368. }
  3369. $conversation_members_count = sizeof($recipients);
  3370.  
  3371. $lastMessageDate = new MongoDate();
  3372. $lastMessageBody = $comment;
  3373. $messageMongoID = new MongoId();
  3374.  
  3375. $participantsCursor = MyMongo_Connection::find(static::$usersCollection,array('_id' => array('$in' => $participantsArray)),
  3376. array('username' => 1, '_id' => 1));
  3377. $participantsParamsForPushNotificationArr = array();
  3378. foreach ($participantsCursor as $currUserPart)
  3379. {
  3380. array_push($participantsParamsForPushNotificationArr, array('user_id' => $currUserPart['_id'], 'nickname' => $currUserPart['username']));
  3381. }
  3382. // Create recipients inbox
  3383. foreach ( $recipients as $recipient_id )
  3384. {
  3385. $currParticipants = $this->removeOwnerFromParticipants($recipient_id, $participants);
  3386. $read = strcasecmp($recipient_id, $userID) == 0 ? true : false; //il creatore del messaggio ha letto la conversazione in cui scrive
  3387. //creo o aggiorno la casella per la conversazione per l'utente corrente (compreso il creatore del messaggio)
  3388. MyMongo_Connection::updateCollectionFields(static::$conversationsColl,
  3389. array('conversation_id' => $conversationID, 'owner_id' => $recipient_id),
  3390. array ( 'participants' => $currParticipants, 'read' => $read, 'deleted' => false, 'last_sender_id' => $userID,
  3391. 'last_message_body' => $comment, 'last_message_date' => $lastMessageDate, 'conversation_members_count' => $conversation_members_count
  3392. ),
  3393. array('upsert' => true)
  3394. );
  3395. if(strcasecmp($userID, $recipient_id) != 0)
  3396. {
  3397. //aggiunge le notifiche per gli utenti che non sono il sender
  3398. Engine_Api::_()->getDbtable('notifications', 'activity')->addNotificationExceptPushNotification
  3399. (
  3400. $recipient_id,
  3401. $userID,
  3402. $conversationID,
  3403. 'conversation',
  3404. 'message_new',
  3405. array('message_id'=>$messageMongoID->__toString(),'message_body' => $comment, 'creation_date' => $lastMessageDate->sec,
  3406. 'participants' => $participantsParamsForPushNotificationArr
  3407. )
  3408. );
  3409. }
  3410. }
  3411. $messageToAdd = array('_id' => $messageMongoID, 'conversation_id' => $conversationID, 'sender_id' => $userID,
  3412. 'body' => $comment, 'creation_date' => $lastMessageDate, 'visible_to' => $visibleTo
  3413. );
  3414. // Create message
  3415. MyMongo_Connection::addDocument(static::$messagesColl, $messageToAdd);
  3416. $response = array (
  3417. "conversation_id" => $conversationID,
  3418. "msg_id" => $messageMongoID->__toString()
  3419. );
  3420. //invio le push notifications agli utenti
  3421. Engine_Api::_()->getApi("activityutility","activity")->sendInstantNotificationToAllPlatformsForMultipleUsers($usersToPush,false,$userID);
  3422. return $response;
  3423. }
  3424.  
  3425. /**
  3426. * Restituisce l'array dei partecipanti senza l'utente specificato
  3427. * @param $participants
  3428. * @return array di partecipanti senza l'utente specificato
  3429. */
  3430. private function removeOwnerFromParticipants($userIDToRemove, $participants)
  3431. {
  3432. $toReturn = $participants;
  3433. $dim = sizeof($toReturn);
  3434. for($i = 0; $i < $dim; $i++)
  3435. {
  3436. if(strcasecmp($userIDToRemove, $toReturn[$i]['user_id']) == 0)
  3437. {
  3438. unset($toReturn[$i]);
  3439. break;
  3440. }
  3441. }
  3442. //array_values azzera gli indici dell'array
  3443. return array_values($toReturn);
  3444. }
  3445.  
  3446. /**
  3447. * This method returns all of my events and those posted by my friends
  3448. * @param $userID
  3449. */
  3450. public function getEvents($userID) {
  3451. $eventAuxiliary = Engine_Api::_()->getApi('eventauxiliary', 'event');
  3452. $userUtility = Engine_Api::_()->getApi('userutility', 'core');
  3453.  
  3454. $events = $eventAuxiliary->getEventsByUserID($userID, null, null, true, false);
  3455.  
  3456. $arrayEvents = array();
  3457. $i = 0;
  3458. foreach ($events as $event) {
  3459. $photoURLCompleted = SM_BUCKET . $event["img_url"];
  3460.  
  3461. $user = $this->getUserDetails($event["owner_id"]);
  3462. $elementEvents = array (
  3463. 'event_id' => $event["_id"],
  3464. 'title' => $event ["title"],
  3465. 'description' => $event ["description"],
  3466. 'starttime' => $event["start_time"]->sec,
  3467. 'photo_url' => $photoURLCompleted,
  3468. 'member_count' => $event ["attenders_count"],
  3469. 'image_orientation' => $event["img_orientation"],
  3470. 'view_count' => $event ["views_count"],
  3471. 'qr_details' => "https://".$_SERVER['HTTP_HOST'].$eventAuxiliary->getEventHref(((object) $event)),
  3472. 'location_img_url' => SM_BUCKET . $event["location_img_url"]
  3473. );
  3474. $arrayEvents[$i] = array (
  3475. "event" => $elementEvents,
  3476. "owner" => $user
  3477. );
  3478. $i++;
  3479. }
  3480. $userUtility->resetNotificationTypeForUser($userID, "event_create");
  3481. return $arrayEvents;
  3482. }
  3483.  
  3484. /**
  3485. * this method return all information of specified event
  3486. *
  3487. * @param $userID
  3488. * @param $event_id
  3489. */
  3490. public function getEventInfo($userID, $event_id)
  3491. {
  3492. $event = MyMongo_Connection::findOne(static::$eventsColl, array('_id' => $event_id));
  3493. if (is_null($event))
  3494. {
  3495. $errorArray = array (
  3496. 'error' => 'specified event does not exist'
  3497. );
  3498. return $errorArray;
  3499. }
  3500. $startTime = $event->start_time->toDateTime()->getTimestamp();
  3501. $endTime = $event->end_time->toDateTime()->getTimestamp();
  3502. $userOwner = MyMongo_Connection::findOne(static::$usersCollection, array('_id' => $event->owner_id));
  3503. $currentUserMembershipRsvp = MyMongo_Connection::findOne(static::$eventMemberColl, array('user_id' => $userID, 'event_id' => $event_id));
  3504. $currRSVP = "";
  3505. //se non è presente l'utente nella membership dell'utente corrente
  3506. if(is_null($currentUserMembershipRsvp))
  3507. {
  3508. $currRSVP = 3;
  3509. MyMongo_Connection::addDocument(static::$eventMemberColl, array('event_id'=>$event_id, 'user_id' => $userID, 'rsvp' => $currRSVP));
  3510. }
  3511. else
  3512. {
  3513. $currRSVP = $currentUserMembershipRsvp->rsvp;
  3514. }
  3515. $photoURLCompleted = SM_BUCKET.$event->img_url;
  3516. // Incremento il contatore di visualizzazioni se non è l'owner dell'evento
  3517. if( strcasecmp($event->owner_id , $userID) != 0 )
  3518. {
  3519. MyMongo_Connection::updateAndOrIncCollectionFields(static::$eventsColl, array('_id' => $event_id), array(), array('views_count' => 1));
  3520. }
  3521.  
  3522. return array
  3523. (
  3524. 'event_id' => $event->_id,
  3525. 'title' => $event->title,
  3526. 'description' => $event->description,
  3527. 'starttime' => $startTime,
  3528. 'endtime' => $endTime,
  3529. 'photo_url' => $photoURLCompleted,
  3530. 'category' => $event->category,
  3531. 'location' => $event->location['address'],
  3532. 'latitude' => $event->location['lat'],
  3533. 'longitude' => $event->location['lon'],
  3534. 'exist_friendship_channel' => Utilities_Static::getUserutility()->checkFriendshipChannelBetweenTwoUsers($event->owner_id,$userID),
  3535. 'participants_number' => $event->attenders_count,
  3536. 'event_cools' => $event->cools_count,
  3537. 'owner' => $this->getUserDetails ( $event->owner_id ),
  3538. 'user_cool' => Engine_Api::_ ()->getApi ( "coolutility", "core" )->isCooler($userID,'event',$event_id) ? 1 : 0,
  3539. 'image_orientation' => $event->img_orientation,
  3540. 'is_public' => $userOwner->is_public,
  3541. 'userlogged_rsvp' => $currRSVP,
  3542. 'comment_counter' => $event->comments_count,
  3543. 'location_img_url' => SM_BUCKET.$event->location_img_url,
  3544. 'views' => $event->views_count
  3545. );
  3546. }
  3547.  
  3548. // function to get the address
  3549. public function get_lat_long($address){
  3550.  
  3551. $address = str_replace(" ", "+", $address);
  3552.  
  3553. $json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");
  3554. $json = json_decode($json);
  3555.  
  3556. $lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
  3557. $long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
  3558. return array("lat" => $lat, "lon" => $long);
  3559. }
  3560.  
  3561. /**
  3562. * this method set response of user to event invite
  3563. * @param $userID
  3564. * @param $eventID
  3565. * @param $option
  3566. */
  3567. public function eventResponse($userID, $eventID, $option)
  3568. {
  3569. //verifica se $option è numerico ed appartentente all'intervallo [0,3[
  3570. if (is_numeric($option) && ((int)$option >= 0) && ((int)$option < 3) )
  3571. {
  3572. $option = (int)$option;
  3573. $event = MyMongo_Connection::findOne(static::$eventsColl, array('_id' => $eventID));
  3574. //se l'evento non esiste
  3575. if (is_null($event))
  3576. {
  3577. return array ('error' => 'specified event does not exist');
  3578. }
  3579. //aggiorna o inserisci l'intenzione di partecipazione per l'utente specificato nell'evento specificato
  3580. MyMongo_Connection::updateCollectionFields
  3581. (
  3582. static::$eventMemberColl, array('event_id' => $eventID, 'user_id' => $userID),
  3583. array('rsvp' => $option),
  3584. array('upsert' => true)
  3585. );
  3586. $acceptorsCount = MyMongo_Connection::count(static::$eventMemberColl, array('event_id' => $eventID, 'rsvp' => 2));
  3587. MyMongo_Connection::updateCollectionFields(static::$eventsColl,array('_id' => $eventID), array('attenders_count' => (int)$acceptorsCount ));
  3588. return array('Response' => 'Request OK');
  3589. }
  3590. else
  3591. {
  3592. return array ('error' => 'option value must be set to 0 or 1 or 2');;
  3593. }
  3594. }
  3595.  
  3596. public function getOpenOffers($userID) {
  3597. $userRequester = Engine_Api::_()->user()->getUser($userID);
  3598.  
  3599. $offers = MyMongo_Connection::find("offers", array("closed" => false), array(), array("creation_date" => -1));
  3600. $arrayOffers = array();
  3601. $i = 0;
  3602. foreach($offers as $offer) {
  3603. $user = MyMongo_Connection::findOne("users", array("_id" => $offer['owner_id']));
  3604.  
  3605. $limitedValue = "No";
  3606. $limitData = isset($offer['limitations']['params']['expiration_date']) ? $offer['limitations']['params']['expiration_date']->sec : null;
  3607. $limitTypeValue = isset($offer['limitations']['params']['type']) ? $offer['limitations']['params']['type'] : null;
  3608. if($limitTypeValue != null) {
  3609. $limitedValue = "Yes";
  3610. }
  3611.  
  3612. $startTime = $offer["creation_date"]->sec;
  3613.  
  3614. $dateStart = new Zend_Date($startTime );
  3615. $dateStart->setTimezone($userRequester->timezone);
  3616.  
  3617. $photoURLCompleted = SM_BUCKET . $offer['img_url'];
  3618.  
  3619. $price = (int)$offer['price'];
  3620. $currency = $offer['currency'];
  3621. $location = $offer['location']['address'];
  3622. $qrDetails = Engine_Api::_()->getApi("offerauxiliary","classified")->getOfferHref($offer, true);
  3623.  
  3624. if (isset($limitTypeValue)) {
  3625. if (isset($limitData)) {
  3626. $elementOffers = array (
  3627. 'offer_id' => $offer ["_id"],
  3628. 'title' => $offer ["title"],
  3629. 'body' => $offer ["description"],
  3630. 'creation_date' => $startTime,
  3631. 'photo_url' => $photoURLCompleted,
  3632. 'price' => $price,
  3633. 'currency' => $currency,
  3634. 'location' => $location,
  3635. 'limited' => $limitedValue,
  3636. 'limit_type' => $limitTypeValue,
  3637. 'limit_date' => $limitData,
  3638. 'qr_details' => $qrDetails,
  3639. 'image_orientation' => $offer["img_orientation"]
  3640. );
  3641. } else {
  3642. $elementOffers = array (
  3643. 'offer_id' => $offer ["_id"],
  3644. 'title' => $offer ["title"],
  3645. 'body' => $offer ["description"],
  3646. 'creation_date' => $startTime,
  3647. 'photo_url' => $photoURLCompleted,
  3648. 'price' => $price,
  3649. 'currency' => $currency,
  3650. 'location' => $location,
  3651. 'limited' => $limitedValue,
  3652. 'limit_type' => $limitTypeValue,
  3653. 'qr_details' => $qrDetails,
  3654. 'image_orientation' => $offer["img_orientation"]
  3655. );
  3656. }
  3657. } else {
  3658. $elementOffers = array (
  3659. 'offer_id' => $offer ["_id"],
  3660. 'title' => $offer ["title"],
  3661. 'body' => $offer ["description"],
  3662. 'creation_date' => $startTime,
  3663. 'photo_url' => $photoURLCompleted,
  3664. 'price' => $price,
  3665. 'currency' => $currency,
  3666. 'location' => $location,
  3667. 'limited' => $limitedValue,
  3668. 'qr_details' => $qrDetails,
  3669. 'image_orientation' => $offer["img_orientation"]
  3670. );
  3671. }
  3672. $userDetails = $this->buildUserArr((array)$user);
  3673. $arrayOffers [$i] = array(
  3674. 'offer' => $elementOffers,
  3675. 'owner' => $userDetails
  3676. );
  3677. $i++;
  3678. }
  3679. Engine_Api::_()->getApi('userutility', 'core')->resetNotificationTypeForUser($userID, "classified_new");
  3680. return $arrayOffers;
  3681. }
  3682.  
  3683. /**
  3684. * Ritorna il dettaglio di una offerta
  3685. * @param $userID
  3686. * @param $offerID
  3687. * @return
  3688. */
  3689. public function getOfferInfo ( $userID, $offerID, $fromWS=false )
  3690. {
  3691. $coolUtility = Engine_Api::_()->getApi("coolutility","core");
  3692. $offerAux = Engine_Api::_()->getApi("offerauxiliary","classified");
  3693. $offer = (array)MyMongo_Connection::findOne(static::$offersColl, array('_id' => $offerID));
  3694. if(isset($offer["_id"])) {
  3695. $expired = false;
  3696. if(!is_null($offer['limitations']['params']['expiration_date']))
  3697. {
  3698. $today = new MongoDate();
  3699. $today = $today->sec;
  3700. $expired = $offer['limitations']['params']['expiration_date']->sec < $today;
  3701. }
  3702.  
  3703. //incremento di 1 il contatore visite
  3704. MyMongo_Connection::updateAndOrIncCollectionFields(static::$offersColl, array('_id' => $offerID), array(), array('views_count' => 1));
  3705.  
  3706. $canAccept = false;
  3707. if(strcasecmp($offer['owner_id'], $userID) != 0)
  3708. {
  3709. if(!$offerAux->hasUserAcceptedOffer($userID, $offer['_id']))
  3710. {
  3711. $canAccept = true;
  3712. }
  3713. }
  3714. $ownerDetail = $this->getUserDetails($offer['owner_id']);
  3715. $isCooler = $coolUtility->isCooler($userID,'offer',$offer ["_id"]);
  3716. if($fromWS)
  3717. {
  3718. $isCooler = $isCooler ? 1 : 0;
  3719. }
  3720. $elementOffer = array
  3721. (
  3722. 'classified_id' => $offer['_id'],
  3723. 'title' => $offer["title"],
  3724. 'body' => $offer["description"],
  3725. 'view_count' => $offer["views_count"],
  3726. 'creation_date' => $offer['creation_date']->sec,
  3727. 'photo_url' => SM_BUCKET.$offer['img_url'],
  3728. 'price' => (int)$offer ["price"],
  3729. 'currency' => $offer ["currency"],
  3730. 'location' => $offer['location']['address'],
  3731. 'latitude' => $offer['location']['lat'],
  3732. 'longitude' => $offer['location']['lon'],
  3733. 'limited' => $offer['limitations']['limited_time_offer'] ? "Yes" : "No",
  3734. 'limit_type' => $offer['limitations']['params']['type'],
  3735. 'limit_data' => empty($offer['limitations']['params']['expiration_date']) ? null : $offer['limitations']['params']['expiration_date']->sec,
  3736. 'qr_details' => 'https://'.$_SERVER['HTTP_HOST']."/".$offer['owner_id']."/".$offer['_id'],
  3737. 'participant_counter' => $offer['acceptors_count'],
  3738. 'offer_cools' => $offer['cools_count'],
  3739. 'user_cool' => $isCooler,
  3740. 'can_accept' => $canAccept,
  3741. 'image_orientation' => $offer['img_orientation'],
  3742. 'expired' => $expired,
  3743. 'comment_counter' => $offer['comments_count']
  3744. );
  3745. return array(
  3746. 'offer' => $elementOffer,
  3747. 'owner' => $ownerDetail
  3748. );
  3749. } else {
  3750. return array("error" => "offer was deleted");
  3751. }
  3752. }
  3753.  
  3754. public function acceptOffer($userID, $offerID) {
  3755. $offer = MyMongo_Connection::findOne("offers", array("_id" => $offerID));
  3756.  
  3757. if ($offer == null) {
  3758. $errorArray = array (
  3759. 'error' => 'Offer does not exist'
  3760. );
  3761. return $errorArray;
  3762. }
  3763. if ($offer->closed == true){
  3764. $errorArray = array (
  3765. 'error' => 'Offer is closed'
  3766. );
  3767. return $errorArray;
  3768. }
  3769. if($offer->owner_id === $userID) {
  3770. $errorArray = array (
  3771. 'error' => 'You are owner of the offer, you cannot accept the offer'
  3772. );
  3773. return $errorArray;
  3774. }
  3775.  
  3776. $dateValue = isset($offer->limitations['params']['expiration_date']) ? $offer->limitations['params']['expiration_date']->sec : null;
  3777.  
  3778. if ($dateValue != null) {
  3779. $today = strtotime(date('Y-m-d'));
  3780. $diff = $dateValue - $today;
  3781. $daysleft = round((($diff/24)/60)/60);
  3782. if ($daysleft < 0){
  3783. $errorArray = array (
  3784. 'error' => 'Offer expired'
  3785. );
  3786. return $errorArray;
  3787. }
  3788. }
  3789.  
  3790. $accepted = MyMongo_Connection::count("offers_accepted", array("offer_id" => $offerID, "acceptor_id" => $userID));
  3791. if ($accepted > 0) {
  3792. $errorArray = array (
  3793. 'error' => 'User has already accepted the offer'
  3794. );
  3795. return $errorArray;
  3796. }
  3797.  
  3798. $acceptedArr = array (
  3799. 'offer_id' => $offerID,
  3800. 'acceptor_id' => $userID,
  3801. 'accepted_date' => new MongoDate()
  3802. );
  3803. //aggiorno il contatore di acceptors
  3804. MyMongo_Connection::updateAndOrIncCollectionFields(static::$offersColl, array('_id' => $offerID), array(), array('acceptors_count' => 1));
  3805. MyMongo_Connection::addDocument("offers_accepted", $acceptedArr);
  3806.  
  3807. return array (
  3808. 'Response' => 'Request OK'
  3809. );
  3810. }
  3811.  
  3812. public function getLocations($userID) {
  3813. $photoUtility = Engine_Api::_()->getApi('photoutility', 'core');
  3814.  
  3815. $photos = MyMongo_Connection::find("photos", array("owner_id" => $userID));
  3816. $i = 0;
  3817. foreach ($photos as $photoElement) {
  3818. $arrayCities = $photoUtility->getPhotoCities($photoElement);
  3819. $uploadCity = $arrayCities[0]["city"];
  3820. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  3821. $photoURLCompleted = SM_BUCKET . $photoElement['thumb_img']['url'];
  3822. $qrDetails = 'https://'.$_SERVER['HTTP_HOST'] . $appName . "user/photodetail/view?p=".$photoElement["_id"];
  3823.  
  3824. $coordinates = $photoUtility->getCoordinates($photoElement);
  3825. if ($coordinates != null) {
  3826. if ($photoElement["deleted"] == false) {
  3827. $arrayLocations [$i] = array (
  3828. 'photo_id' => $photoElement["_id"],
  3829. 'description' => $photoElement ["title"],
  3830. 'upload_city' => $uploadCity,
  3831. 'coordinates' => $coordinates,
  3832. 'photo_url' => $photoURLCompleted,
  3833. 'qr_details' => $qrDetails,
  3834. 'photo_pins' => $photoUtility->getPhotoPins($photoElement),
  3835. 'photo_see' => $photoElement["photosee_count"],
  3836. 'photo_miles' => $photoElement["distance"]
  3837. );
  3838. $i ++;
  3839. }
  3840. }
  3841. }
  3842. $userDetails = $this->getUserDetails($userID);
  3843. return array ('locations' => $arrayLocations, 'owner' => $userDetails);
  3844. }
  3845.  
  3846. /**
  3847. * retrieve all user's Cool notifications
  3848. * @param $userID
  3849. */
  3850. public function getCoolNotification ( $userID ){
  3851. $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
  3852. $userUtility = Engine_Api::_()->getApi('userutility','core');
  3853. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  3854. $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
  3855.  
  3856. $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
  3857. $select = new Zend_Db_Select($notificationsTable->getAdapter());
  3858. $select->from(array('n' => $notificationsTable->info('name')),
  3859. array('n.notification_id','n.user_id','n.params AS paramsNot','n.subject_id AS subjectUser'))
  3860. ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
  3861. ->where('n.read = 0')
  3862. ->where('n.user_id = ?',$userID)
  3863. ->where('n.type = "liked"');
  3864. $data = $notificationsTable->getAdapter()->fetchAll($select);
  3865. $i = 0;
  3866. $notificationsArray = array();
  3867.  
  3868. foreach ($data as $note){
  3869. $user = Engine_Api::_()->getDbtable('users', 'user')
  3870. ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
  3871. if ($user->photo_id > 0) {
  3872. $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
  3873. } else {
  3874. $photoProfileUrl = "";
  3875. }
  3876. $userType = $userUtility->getUserType($user->user_id);
  3877. $params = json_decode($note['paramsNot']);
  3878. if (strcasecmp($userType,"personal") == 0){
  3879. $dataEntry = array(
  3880. 'notification_id' => $note["notification_id"],
  3881. 'user_id' => $note["subjectUser"],
  3882. 'display_name' => $user["displayname"],
  3883. 'nickname' => $user->username,
  3884. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  3885. 'photo_profile_url' => $photoProfileUrl,
  3886. 'gender' => $userUtility->getUserGender ( $user->user_id ),
  3887. 'user_type' => $userType,
  3888. 'action_id' => $note["action_id"],
  3889. 'object_type' => $note["object_type"],
  3890. 'object_id' => $note["object_id"],
  3891. 'label' => $params->{'label'}
  3892. );
  3893. } else {
  3894. $dataEntry = array(
  3895. 'notification_id' => $note["notification_id"],
  3896. 'user_id' => $note["subjectUser"],
  3897. 'display_name' => $user["displayname"],
  3898. 'nickname' => $user->username,
  3899. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  3900. 'photo_profile_url' => $photoProfileUrl,
  3901. 'user_type' => $userType,
  3902. 'action_id' => $note["action_id"],
  3903. 'object_type' => $note["object_type"],
  3904. 'object_id' => $note["object_id"],
  3905. 'label' => $params->{'label'}
  3906. );
  3907. }
  3908. $notificationsArray[$i] = $dataEntry;
  3909. $i = $i + 1;
  3910.  
  3911. $n = $notificationsTable->update (
  3912. array ('read' => 1 ),
  3913. array ('notification_id = ?' => $note["notification_id"])
  3914. );
  3915. }
  3916. return $notificationsArray;
  3917. }
  3918.  
  3919. /**
  3920. * this method retrieves all user's Comments notifications
  3921. * @param $userID
  3922. */
  3923. public function getCommentNotification ( $userID ){
  3924. $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
  3925. $userUtility = Engine_Api::_()->getApi('userutility','core');
  3926. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  3927. $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
  3928.  
  3929. $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
  3930. $select = new Zend_Db_Select($notificationsTable->getAdapter());
  3931. $select->from(array('n' => $notificationsTable->info('name')),
  3932. array('n.notification_id','n.user_id','n.params AS paramsNot','n.subject_id AS subjectUser','n.type AS notType'))
  3933. ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
  3934. ->where('n.read = 0')
  3935. ->where('n.user_id = ?',$userID)
  3936. ->where('n.type = "commented" OR n.type = "commented_commented"');
  3937.  
  3938. $data = $notificationsTable->getAdapter()->fetchAll($select);
  3939. $i = 0;
  3940. $notificationsArray = array();
  3941. foreach ($data as $note){
  3942. $user = Engine_Api::_()->getDbtable('users', 'user')
  3943. ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
  3944. $params = json_decode($note['paramsNot']);
  3945. if ($user->photo_id > 0) {
  3946. $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
  3947. } else {
  3948. $photoProfileUrl = "";
  3949. }
  3950.  
  3951. $userType = $userUtility->getUserType($user->user_id);
  3952. if (strcasecmp($userType,"personal") == 0){
  3953. $dataEntry = array(
  3954. 'notification_id' => $note["notification_id"],
  3955. 'notification_type' => $note["notType"], //tipo notifica commented o commented_commented
  3956. 'user_id' => $note["subjectUser"],//mia notifica
  3957. 'display_name' => $user["displayname"],
  3958. 'nickname' => $user->username,
  3959. 'photo_profile_url' => $photoProfileUrl,
  3960. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  3961. 'gender' => $userUtility->getUserGender ( $user->user_id ),
  3962. 'user_type' => $userType,
  3963. 'action_id' => $note["action_id"],
  3964. 'object_type' => $note["object_type"],//tipo di oggetti su cui ho commentato album_photo di action
  3965. 'object_id' => $note["object_id"],//id della foto nel caso
  3966. 'label' => $params->{'label'}
  3967. );
  3968. } else {
  3969. $dataEntry = array(
  3970. 'notification_id' => $note["notification_id"],
  3971. 'notification_type' => $note["notType"], //tipo notifica commented o commented_commented
  3972. 'user_id' => $note["subjectUser"],//mia notifica
  3973. 'display_name' => $user["displayname"],
  3974. 'nickname' => $user->username,
  3975. 'photo_profile_url' => $photoProfileUrl,
  3976. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  3977. 'user_type' => $userType,
  3978. 'action_id' => $note["action_id"],
  3979. 'object_type' => $note["object_type"],//tipo di oggetti su cui ho commentato album_photo di action
  3980. 'object_id' => $note["object_id"],//id della foto nel caso
  3981. 'label' => $params->{'label'}
  3982. );
  3983. }
  3984. $notificationsArray[$i] = $dataEntry;
  3985. $i = $i + 1;
  3986.  
  3987. $n = $notificationsTable->update (
  3988. array ('read' => 1 ),
  3989. array ('notification_id = ?' => $note["notification_id"])
  3990. );
  3991. }
  3992. return $notificationsArray;
  3993. }
  3994.  
  3995. /**
  3996. * this method retrieves all user's Photosee notifications
  3997. * @param $userID
  3998. */
  3999. public function getPhotoseeNotification( $userID ){
  4000. $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
  4001. $userUtility = Engine_Api::_()->getApi('userutility','core');
  4002. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  4003. $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
  4004.  
  4005. $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
  4006. $select = new Zend_Db_Select($notificationsTable->getAdapter());
  4007. $select->from(array('n' => $notificationsTable->info('name')),
  4008. array('n.notification_id','n.user_id','n.subject_id AS subjectUser','n.type AS notType'))
  4009. ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
  4010. ->where('n.read = 0')
  4011. ->where('n.user_id = ?',$userID)
  4012. ->where('n.type = "photo_seen" OR n.type = "photo_seen_seen"');
  4013.  
  4014. $data = $notificationsTable->getAdapter()->fetchAll($select);
  4015. $i = 0;
  4016. $notificationsArray = array();
  4017. foreach ($data as $note){
  4018. $user = Engine_Api::_()->getDbtable('users', 'user')
  4019. ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
  4020. if ($user->photo_id > 0) {
  4021. $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
  4022. } else {
  4023. $photoProfileUrl = "";
  4024. }
  4025.  
  4026. $userType = $userUtility->getUserType($user->user_id);
  4027. if (strcasecmp($userType,"personal") == 0){
  4028. $dataEntry = array(
  4029. 'notification_id' => $note["notification_id"],
  4030. 'notification_type' => $note["notType"], // tipo notifica tra photo_seen e photo_seen_seen
  4031. 'user_id' => $note["subjectUser"],//mia notifica
  4032. 'display_name' => $user["displayname"],
  4033. 'nickname' => $user["username"],
  4034. 'photo_profile_url' => $photoProfileUrl,
  4035. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4036. 'user_type' => $userType,
  4037. 'gender' => $userUtility->getUserGender($user->user_id),
  4038. 'action_id' => $note["action_id"],
  4039. 'object_type' => $note["object_type"],//tipo di oggetti su cui ho photosee album_photo di action
  4040. 'object_id' => $note["object_id"]//id della foto nel caso
  4041. );
  4042. } else {
  4043. $dataEntry = array(
  4044. 'notification_id' => $note["notification_id"],
  4045. 'notification_type' => $note["notType"], // tipo notifica tra photo_seen e photo_seen_seen
  4046. 'user_id' => $note["subjectUser"],//mia notifica
  4047. 'display_name' => $user["displayname"],
  4048. 'nickname' => $user["username"],
  4049. 'photo_profile_url' => $photoProfileUrl,
  4050. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4051. 'user_type' => $userType,
  4052. 'action_id' => $note["action_id"],
  4053. 'object_type' => $note["object_type"],//tipo di oggetti su cui ho photosee album_photo di action
  4054. 'object_id' => $note["object_id"]//id della foto nel caso
  4055. );
  4056. }
  4057. $notificationsArray[$i] = $dataEntry;
  4058. $i = $i + 1;
  4059.  
  4060. $n = $notificationsTable->update (
  4061. array ('read' => 1 ),
  4062. array ('notification_id = ?' => $note["notification_id"])
  4063. );
  4064. }
  4065. return $notificationsArray;
  4066. }
  4067.  
  4068. /**
  4069. * this method retrieves all user's Messages notifications
  4070. * @param $userID
  4071. */
  4072. public function getMessagesNotification($userID, $numOfNotifications, $numOfReceived) {
  4073. $userUtility = Engine_Api::_()->getApi('userutility','core');
  4074. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  4075.  
  4076. $where = array(
  4077. "user_id" => $userID,
  4078. "type" => "message_new"
  4079. );
  4080. $limit = null;
  4081. $offset = null;
  4082. if (isset($numOfNotifications)) {
  4083. if (isset($numOfReceived)) {
  4084. $limit = $numOfNotifications;
  4085. $offset = $numOfReceived;
  4086. } else {
  4087. $limit = $numOfNotifications;
  4088. $offset = 0;
  4089. }
  4090. } else {
  4091. $where["mitigated"] = false;
  4092. }
  4093. $order = array("date" => -1);
  4094.  
  4095. $data = MyMongo_Connection::find("notifications", $where, array(), $order, $limit, $offset);
  4096.  
  4097. $i = 0;
  4098. $toFlagAsRead = array();
  4099. $notificationsArray = array();
  4100. foreach ($data as $note) {
  4101. $user = MyMongo_Connection::findOne("users", array("_id" => $note["subject_id"]));
  4102. if (isset($user->cropped_profilephoto_url)) {
  4103. $photoProfileUrl = SM_BUCKET . $user->cropped_profilephoto_url;
  4104. } else {
  4105. $photoProfileUrl = "";
  4106. }
  4107. $userType = ucfirst($user->type);
  4108. if (strcasecmp($userType,"personal") == 0) {
  4109. $dataEntry = array(
  4110. 'notification_id' => $note["_id"],
  4111. 'notification_type' => $note["type"],
  4112. 'read' => $note["read"] == true ? 1 : 0,
  4113. 'mitigated' => $note["mitigated"] == true ? 1 : 0,
  4114. 'user_id' => $note["subject_id"],
  4115. 'nickname' => $user->username,
  4116. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4117. 'photo_profile_url' => $photoProfileUrl,
  4118. 'gender' => $user->gender,
  4119. 'user_type' => $userType,
  4120. 'conversation_id' => $note["object_id"],
  4121. 'messages_unread' => $note['params']['unread_msg']
  4122. );
  4123. } else {
  4124. $dataEntry = array(
  4125. 'notification_id' => $note["_id"],
  4126. 'notification_type' => $note["type"],
  4127. 'read' => $note["read"] == true ? 1 : 0,
  4128. 'mitigated' => $note["mitigated"] == true ? 1 : 0,
  4129. 'user_id' => $note["subject_id"],
  4130. 'nickname' => $user->username,
  4131. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4132. 'photo_profile_url' => $photoProfileUrl,
  4133. 'user_type' => $userType,
  4134. 'conversation_id' => $note["object_id"],
  4135. 'messages_unread' => $note['params']['unread_msg']
  4136. );
  4137. }
  4138. $notificationsArray[$i] = $dataEntry;
  4139. $i = $i + 1;
  4140.  
  4141. if ($note["read"] == false) {
  4142. array_push($toFlagAsRead, $note["_id"]);
  4143. }
  4144. }
  4145.  
  4146. if(sizeof($toFlagAsRead) > 0) {
  4147. MyMongo_Connection::updateCollectionFields("notifications", array("_id" => array('$in' => $toFlagAsRead)), array("read" => true), array("multiple" => true));
  4148. }
  4149. return $notificationsArray;
  4150. }
  4151.  
  4152. /**
  4153. * Resituisce un array che rappresenta un sottoinsieme di follower compresi vari flag (mitigated e read).
  4154. * Inoltre setta le notifiche a lette per ogni elemento restituito dal sottoinsieme.
  4155. * @param $userID
  4156. * @param $numOfNotifications offset
  4157. * @param $numOfReceived limite
  4158. */
  4159. public function getFollowersNotification( $userID,$numOfNotifications,$numOfReceived )
  4160. {
  4161. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  4162. $followerUserArray = Utilities_Static::getUserutility()->getFollowers($userID, $numOfReceived, $numOfReceived);
  4163. $follower = array();
  4164. $i = 0;
  4165. $notificationIDs = array();
  4166. foreach ( $followerUserArray as $followerUser )
  4167. {
  4168. $alreadyFollowed = "";
  4169. if (Utilities_Static::getUserutility()->isFollowing($userID, $followerUser["_id"]))
  4170. {
  4171. $alreadyFollowed = "true";
  4172. }
  4173. else
  4174. {
  4175. $alreadyFollowed = "false";
  4176. }
  4177. $arrayNoti = Utilities_Static::getUserutility()->getMitigatedFromFollowerNotification($userID, $followerUser['_id']);
  4178. array_push($notificationIDs, $arrayNoti['notification_id']);
  4179. $element = array
  4180. (
  4181. 'user_id' => $followerUser["_id"],
  4182. 'display_name' => Utilities_Static::getUserutility()->getNameOrCompanyOfUser($followerUser),
  4183. 'nickname' => $followerUser['username'],
  4184. 'status' => $followerUser['status'],
  4185. 'photo_profile_url' => Utilities_Static::getProfilePhotoURL($followerUser, true),
  4186. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $followerUser['username'],
  4187. 'user_type' => ucfirst($followerUser['type']),
  4188. 'mitigated' => $arrayNoti['mitigated'] ? "1" : "0",
  4189. 'already_followed' => $alreadyFollowed,
  4190. 'notification_id' => $arrayNoti['notification_id'],
  4191. 'notification_type' => 'friend_follow',
  4192. 'read' => $arrayNoti['read'] ? "1" : "0"
  4193. );
  4194. if (strcasecmp ( $followerUser['type'], "personal" ) == 0)
  4195. {
  4196. $element['gender'] = $followerUser['gender'];
  4197. }
  4198. $follower[$i] = $element;
  4199. $i = $i + 1;
  4200. }
  4201. //metto a letto le notifiche elaborate
  4202. MyMongo_Connection::updateCollectionFields
  4203. (
  4204. static::$notificationsColl,
  4205. array('type' => 'friend_follow', '_id' => array('$in' => $notificationIDs)),
  4206. array('read' => true),
  4207. array('multiple' => true)
  4208. );
  4209. return $follower;
  4210. }
  4211. /**
  4212. * this method retrieves all user's Postcard notifications
  4213. * @param $userID
  4214. */
  4215. public function getPostcardNotification($userID, $numOfNotifications, $numOfReceived){
  4216. $userUtility = Engine_Api::_()->getApi('userutility','core');
  4217. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  4218.  
  4219. $where = array(
  4220. "user_id" => $userID,
  4221. "mitigated" => false,
  4222. "type" => "send_postcard"
  4223. );
  4224. $limit = null;
  4225. $offset = null;
  4226.  
  4227. if (isset($numOfNotifications)) {
  4228. if (isset($numOfReceived)) {
  4229. $limit = $numOfNotifications;
  4230. $offset = $numOfReceived;
  4231. } else {
  4232. $limit = $numOfNotifications;
  4233. $offset = 0;
  4234. }
  4235. }
  4236.  
  4237. $order = array("date" => -1);
  4238. $data = MyMongo_Connection::find("notifications", $where, array(), $order, $limit, $offset);
  4239. $i = 0;
  4240. $notificationsArray = array();
  4241. foreach ($data as $note) {
  4242. $user = MyMongo_Connection::findOne("users", array("_id" => $note["subject_id"]));
  4243. if (isset($user->cropped_profilephoto_url)) {
  4244. $photoProfileUrl = SM_BUCKET . $user->cropped_profilephoto_url;
  4245. } else {
  4246. $photoProfileUrl = "";
  4247. }
  4248. $userType = ucfirst($user->type);
  4249. if (strcasecmp($userType,"personal") == 0) {
  4250. $dataEntry = array(
  4251. 'notification_id' => $note["_id"],
  4252. 'type' => $note["type"],
  4253. 'read' => $note["read"] == true ? 1 : 0,
  4254. 'mitigated' => $note["mitigated"] == true ? 1 : 0,
  4255. 'user_id' => $note["subject_id"],
  4256. 'nickname' => $user->username,
  4257. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4258. 'photo_profile_url' => $photoProfileUrl,
  4259. 'gender' => $user->gender,
  4260. 'user_type' => $userType,
  4261. 'photo_url' => $note['params']['photo_url']
  4262. );
  4263. } else {
  4264. $dataEntry = array(
  4265. 'notification_id' => $note["_id"],
  4266. 'type' => $note["type"],
  4267. 'read' => $note["read"] == true ? 1 : 0,
  4268. 'mitigated' => $note["mitigated"] == true ? 1 : 0,
  4269. 'user_id' => $note["subject_id"],
  4270. 'nickname' => $user->username,
  4271. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4272. 'photo_profile_url' => $photoProfileUrl,
  4273. 'user_type' => $userType,
  4274. 'photo_url' => $note['params']['photo_url']
  4275. );
  4276. }
  4277. $notificationsArray[$i] = $dataEntry;
  4278. $i = $i + 1;
  4279. }
  4280. return $notificationsArray;
  4281. }
  4282.  
  4283. /**
  4284. * this method retrieves all user's Photo notifications
  4285. * @param $userID
  4286. */
  4287. public function getPhotoNotification($userID,$numOfNotifications,$numOfReceived)
  4288. {
  4289. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  4290. $photoTypes = array("photo_moved","liked","commented_mention",
  4291. "commented","commented_commented","photo_seen","photo_seen_seen");
  4292.  
  4293. $limit = $offset = null;
  4294. $condition = array('type' => array('$in' => $photoTypes), 'user_id' => $userID);
  4295. if (isset($numOfNotifications))
  4296. {
  4297. if (isset($numOfReceived))
  4298. {
  4299. $limit = $numOfNotifications;
  4300. $offset = $numOfReceived;
  4301. }
  4302. else
  4303. {
  4304. $limit = $numOfNotifications;
  4305. $offset = 0;
  4306. }
  4307. }
  4308. else
  4309. {
  4310. $condition['read'] = false;
  4311. }
  4312.  
  4313.  
  4314. $data = MyMongo_Connection::find
  4315. (
  4316. static::$notificationsColl,
  4317. $condition,
  4318. array(),
  4319. array('date' => -1),
  4320. $limit,
  4321. $offset
  4322. );
  4323. $i = 0;
  4324. $notificationsArray = array();
  4325. $notIDs = array();
  4326. $activityUtility = Engine_Api::_()->getApi("activityutility","activity");
  4327. foreach ($data as $note)
  4328. {
  4329. $oldTypes = $activityUtility->getOldTypesName($note["object_type"]);
  4330. $userObject = Utilities_Static::getUserutility()->getUser($note['subject_id']);
  4331. $dataEntry = array(
  4332. 'notification_id' => $note["_id"],
  4333. 'type' => $note['type'],
  4334. 'read' => $note["read"] ? 1 : 0,
  4335. 'mitigated' => $note["mitigated"]? 1 : 0,
  4336. 'user_id' => $note["user_id"],
  4337. 'display_name' => Utilities_Static::getUserutility()->getNameOrCompanyOfUser($userObject),
  4338. 'nickname' => $userObject->username,
  4339. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $userObject->username,
  4340. 'photo_profile_url' => Utilities_Static::getProfilePhotoURL($userObject,true),
  4341. 'user_type' => ucfirst($userObject->type),
  4342. //'action_id' => $note["action_id"],
  4343. 'object_type' => $oldTypes["object_type"],
  4344. 'object_id' => $note["object_id"],
  4345. 'label' => $note['params']['label']
  4346. );
  4347. if( strcasecmp($userObject->type, 'personal') == 0 )
  4348. {
  4349. $dataEntry['gender'] = $userObject->gender;
  4350. }
  4351. $notificationsArray[$i] = $dataEntry;
  4352. $i++;
  4353. array_push($notIDs, $note["_id"]);
  4354. }
  4355. MyMongo_Connection::updateCollectionFields(static::$notificationsColl,array('_id' => array('$in' => $notIDs)), array('read' => true));
  4356. return $notificationsArray;
  4357. }
  4358.  
  4359. /**
  4360. * this method retrieves all user's commented-mention notifications
  4361. * @param $userID
  4362. */
  4363. public function getCommentedMentionNotification( $userID ){
  4364. $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
  4365. $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
  4366. $userUtility = Engine_Api::_()->getApi('userutility','core');
  4367. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  4368. $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
  4369.  
  4370. $select = new Zend_Db_Select($notificationsTable->getAdapter());
  4371. $select->from(array('n' => $notificationsTable->info('name')),
  4372. array('n.notification_id','n.user_id','n.params AS paramsNot','n.subject_id AS subjectUser','n.type AS notType'))
  4373. ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
  4374. ->where('n.read = 0')
  4375. ->where('n.user_id = ?',$userID)
  4376. ->where('n.type = "commented_mention" ')
  4377. ->order('n.date DESC');
  4378.  
  4379. $data = $notificationsTable->getAdapter()->fetchAll($select);
  4380. $i = 0;
  4381. $notificationsArray = array();
  4382. foreach ($data as $note){
  4383. $user = Engine_Api::_()->getDbtable('users', 'user')
  4384. ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
  4385. $params = json_decode($note['paramsNot']);
  4386. if ($user->photo_id > 0) {
  4387. $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
  4388. } else {
  4389. $photoProfileUrl = "";
  4390. }
  4391.  
  4392. $userType = $userUtility->getUserType($user->user_id);
  4393. if (strcasecmp($userType,"personal") == 0){
  4394. $dataEntry = array(
  4395. 'notification_id' => $note["notification_id"],
  4396. 'notification_type' => $note["notType"],
  4397. 'user_id' => $note["subjectUser"],//mia notifica
  4398. 'display_name' => $user["displayname"],
  4399. 'nickname' => $user["username"],
  4400. 'photo_profile_url' => $photoProfileUrl,
  4401. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4402. 'user_type' => $userType,
  4403. 'gender' => $userUtility->getUserGender($user->user_id),
  4404. 'action_id' => $note["action_id"],
  4405. 'object_type' => $note["object_type"],//tipo di oggetti su cui ho mention album_photo di action
  4406. 'object_id' => $note["object_id"],//id della foto nel caso
  4407. 'label' => $params->{'label'}
  4408. );
  4409. } else {
  4410. $dataEntry = array(
  4411. 'notification_id' => $note["notification_id"],
  4412. 'notification_type' => $note["notType"],
  4413. 'user_id' => $note["subjectUser"],//mia notifica
  4414. 'display_name' => $user["displayname"],
  4415. 'nickname' => $user["username"],
  4416. 'photo_profile_url' => $photoProfileUrl,
  4417. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4418. 'user_type' => $userType,
  4419. 'action_id' => $note["action_id"],
  4420. 'object_type' => $note["object_type"],//tipo di oggetti su cui ho mention album_photo di action
  4421. 'object_id' => $note["object_id"],//id della foto nel caso
  4422. 'label' => $params->{'label'}
  4423. );
  4424. }
  4425. $notificationsArray[$i] = $dataEntry;
  4426. $i = $i + 1;
  4427.  
  4428. $n = $notificationsTable->update (
  4429. array ('read' => 1 ),
  4430. array ('notification_id = ?' => $note["notification_id"])
  4431. );
  4432. }
  4433. return $notificationsArray;
  4434. }
  4435.  
  4436. /**
  4437. * this method retrieves all user's Photosee notifications
  4438. * @param $userID
  4439. */
  4440. public function getAllNotification( $userID ){
  4441. $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
  4442. $userUtility = Engine_Api::_()->getApi('userutility','core');
  4443. $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
  4444. $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
  4445.  
  4446. $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
  4447. $select = new Zend_Db_Select($notificationsTable->getAdapter());
  4448. $select->from(array('n' => $notificationsTable->info('name')),
  4449. array('n.notification_id','n.user_id','n.subject_id AS subjectUser','n.type AS notType'))
  4450. ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
  4451. ->where('n.read = 0')
  4452. ->where('n.user_id = ?',$userID)
  4453. ->where('n.type = "photo_seen" OR n.type = "photo_seen_seen" OR n.type = "commented" OR
  4454. n.type = "commented_commented" OR n.type = "commented_mention OR
  4455. n.type = "message_new" OR n.type = "friend_follow" OR n.type = "liked" ');
  4456.  
  4457. $data = $notificationsTable->getAdapter()->fetchAll($select);
  4458. $i = 0;
  4459. $notificationsArray = array();
  4460. foreach ($data as $note){
  4461. $user = Engine_Api::_()->getDbtable('users', 'user')
  4462. ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
  4463. if ($user->photo_id > 0) {
  4464. $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
  4465. } else {
  4466. $photoProfileUrl = "";
  4467. }
  4468.  
  4469. $userType = $userUtility->getUserType($user->user_id);
  4470. if (strcasecmp($userType,"personal") == 0){
  4471. $dataEntry = array(
  4472. 'notification_id' => $note["notification_id"],
  4473. 'notification_type' => $note["notType"], // tipo notifica
  4474. 'user_id' => $note["subjectUser"],//mia notifica
  4475. 'display_name' => $user["displayname"],
  4476. 'nickname' => $user["username"],
  4477. 'photo_profile_url' => $photoProfileUrl,
  4478. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4479. 'user_type' => $userType,
  4480. 'gender' => $userUtility->getUserGender($user->user_id),
  4481. 'action_id' => $note["action_id"],
  4482. 'object_type' => $note["object_type"],//tipo di oggetti
  4483. 'object_id' => $note["object_id"]//id dell'oggetto di riferimento
  4484. );
  4485. } else {
  4486. $dataEntry = array(
  4487. 'notification_id' => $note["notification_id"],
  4488. 'notification_type' => $note["notType"], // tipo notifica
  4489. 'user_id' => $note["subjectUser"],//mia notifica
  4490. 'display_name' => $user["displayname"],
  4491. 'nickname' => $user["username"],
  4492. 'photo_profile_url' => $photoProfileUrl,
  4493. 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
  4494. 'user_type' => $userType,
  4495. 'action_id' => $note["action_id"],
  4496. 'object_type' => $note["object_type"],//tipo di oggetti
  4497. 'object_id' => $note["object_id"]//id dell'oggetto di riferimento
  4498. );
  4499. }
  4500. $notificationsArray[$i] = $dataEntry;
  4501. $i = $i + 1;
  4502.  
  4503. $n = $notificationsTable->update (
  4504. array ('read' => 1 ),
  4505. array ('notification_id = ?' => $note["notification_id"])
  4506. );
  4507. }
  4508. return $notificationsArray;
  4509. }
  4510.  
  4511. /**
  4512. * This method allows user delete from SMPN
  4513. */
  4514. public function deleteUser($userID, $motivationID, $device_id)
  4515. {
  4516. $deleteRequest = MyMongo_Connection::findOne('core_pendingdeleterequests', array('user_id' => $userID));
  4517. if (!is_null($deleteRequest))
  4518. {
  4519. $errorArray = array (
  4520. 'error' => 'Delete request already done'
  4521. );
  4522. return $errorArray;
  4523. }
  4524. else
  4525. {
  4526. Engine_Api::_()->user()->removeSocialmaticUser(MyMongo_Connection::findOne(static::$usersCollection,array('_id' => $userID)), $motivationID);
  4527. return array (
  4528. 'Response' => 'Request OK'
  4529. );
  4530. }
  4531. }
  4532.  
  4533. /**
  4534. * This method returns all of my past events
  4535. * @param $userID
  4536. */
  4537. public function getPastEvents ( $userID )
  4538. {
  4539. $eventAuxiliary = Engine_Api::_ ()->getApi ( 'eventauxiliary', 'event' );
  4540. $eventsPast = $eventAuxiliary->getEventsByUserID($userID,null,null,false,false);
  4541. $arrayEvents = $this->buildEventsList($eventsPast);
  4542. Utilities_Static::getUserutility()->resetNotificationTypeForUser($userID, "event_create");
  4543. return $arrayEvents;
  4544. }
  4545.  
  4546. /**
  4547. * This method returns all of my events
  4548. * @param $userID
  4549. */
  4550. public function getMyEvents ( $userID )
  4551. {
  4552. $eventAuxiliary = Engine_Api::_ ()->getApi ( 'eventauxiliary', 'event' );
  4553. $myEvents = $eventAuxiliary->getEventsByUserID($userID,null,null,null,true);
  4554. $arrayEvents = $this->buildEventsList($myEvents);
  4555. return $arrayEvents;
  4556. }
  4557.  
  4558. private function buildEventsList($eventsList)
  4559. {
  4560. $arrayEvents = array();
  4561. $i = 0;
  4562. foreach ( $eventsList as $event )
  4563. {
  4564. $startTime = $event["start_time"]->sec;
  4565. $user = $this->getUserDetails ( $event ["owner_id"] );
  4566. $elementEvents = array (
  4567. 'event_id' => $event ["_id"],
  4568. 'title' => $event ["title"],
  4569. 'description' => $event ["description"],
  4570. 'starttime' => $startTime,
  4571. 'photo_url' => SM_BUCKET.$event['img_url'],
  4572. 'member_count' => $event ["attenders_count"],
  4573. 'image_orientation' => $event['img_orientation']
  4574. );
  4575. $arrayEvents [$i] = array (
  4576. "event" => $elementEvents,
  4577. "owner" => $user
  4578. );
  4579. $i ++;
  4580. }
  4581. return $arrayEvents;
  4582. }
  4583.  
  4584. public function getMyOffers($userID) {
  4585. $user = Engine_Api::_()->user()->getUser($userID);
  4586. $userDetails = $this->buildUserArr((array)$user);
  4587.  
  4588. $offers = MyMongo_Connection::find("offers", array("owner_id" => $userID), array(), array('creation_date' => -1));
  4589. $arrayOffers = array();
  4590. $i = 0;
  4591. foreach($offers as $offer) {
  4592.  
  4593. $limitedValue = "No";
  4594. $limitData = isset($offer['limitations']['params']['expiration_date']) ? $offer['limitations']['params']['expiration_date']->sec : null;
  4595. $limitTypeValue = isset($offer['limitations']['params']['type']) ? $offer['limitations']['params']['type'] : null;
  4596. if($limitTypeValue != null) {
  4597. $limitedValue = "Yes";
  4598. }
  4599.  
  4600. $startTime = $offer["creation_date"]->sec;
  4601.  
  4602. $dateStart = new Zend_Date($startTime );
  4603. $dateStart->setTimezone($user->timezone);
  4604.  
  4605. $photoURLCompleted = SM_BUCKET . $offer['img_url'];
  4606.  
  4607. $price = $offer['price'];
  4608. $currency = $offer['currency'];
  4609. $location = $offer['location']['address'];
  4610. $qrDetails = Engine_Api::_()->getApi("offerauxiliary","classified")->getOfferHref($offer, true);
  4611.  
  4612. if (isset($limitTypeValue)) {
  4613. if (isset($limitData)) {
  4614. $elementOffers = array (
  4615. 'offer_id' => $offer ["_id"],
  4616. 'title' => $offer ["title"],
  4617. 'body' => $offer ["description"],
  4618. 'creation_date' => $startTime,
  4619. 'photo_url' => $photoURLCompleted,
  4620. 'closed' => $offer["closed"],
  4621. 'price' => $price,
  4622. 'currency' => $currency,
  4623. 'location' => $location,
  4624. 'limited' => $limitedValue,
  4625. 'limit_type' => $limitTypeValue,
  4626. 'limit_date' => $limitData,
  4627. 'qr_details' => $qrDetails,
  4628. 'image_orientation' => $offer["img_orientation"]
  4629. );
  4630. } else {
  4631. $elementOffers = array (
  4632. 'offer_id' => $offer ["_id"],
  4633. 'title' => $offer ["title"],
  4634. 'body' => $offer ["description"],
  4635. 'creation_date' => $startTime,
  4636. 'photo_url' => $photoURLCompleted,
  4637. 'closed' => $offer["closed"],
  4638. 'price' => $price,
  4639. 'currency' => $currency,
  4640. 'location' => $location,
  4641. 'limited' => $limitedValue,
  4642. 'limit_type' => $limitTypeValue,
  4643. 'qr_details' => $qrDetails,
  4644. 'image_orientation' => $offer["img_orientation"]
  4645. );
  4646. }
  4647. } else {
  4648. $elementOffers = array (
  4649. 'offer_id' => $offer ["_id"],
  4650. 'title' => $offer ["title"],
  4651. 'body' => $offer ["description"],
  4652. 'creation_date' => $startTime,
  4653. 'photo_url' => $photoURLCompleted,
  4654. 'closed' => $offer["closed"],
  4655. 'price' => $price,
  4656. 'currency' => $currency,
  4657. 'location' => $location,
  4658. 'limited' => $limitedValue,
  4659. 'qr_details' => $qrDetails,
  4660. 'image_orientation' => $offer["img_orientation"]
  4661. );
  4662. }
  4663. $arrayOffers [$i] = array(
  4664. 'offer' => $elementOffers,
  4665. 'owner' => $userDetails
  4666. );
  4667. $i++;
  4668. }
  4669. return $arrayOffers;
  4670. }
  4671. /**
  4672. * this function post a new offer
  4673. */
  4674. public function postOffer( $userID, $offerParameters)
  4675. {
  4676. $parameterArrays = Zend_Json_Decoder::decode ( $offerParameters, true ); // decode JSON to associative array
  4677. if (! array_key_exists("offer_title",$parameterArrays[0])){
  4678. return array (
  4679. "error",
  4680. "offer_title parameter must be setted"
  4681. );
  4682. }
  4683. if (! array_key_exists("offer_type",$parameterArrays[0])){
  4684. return array (
  4685. "error",
  4686. "offer_type parameter must be setted"
  4687. );
  4688. }
  4689. if (! array_key_exists("description",$parameterArrays[0])){
  4690. return array (
  4691. "error",
  4692. "description parameter must be setted"
  4693. );
  4694. }
  4695. if (! array_key_exists("price",$parameterArrays[0])){
  4696. return array (
  4697. "error",
  4698. "price parameter must be setted"
  4699. );
  4700. }
  4701. if (! array_key_exists("currency",$parameterArrays[0])){
  4702. return array (
  4703. "error",
  4704. "currency parameter must be setted"
  4705. );
  4706. }
  4707. if (! array_key_exists("location",$parameterArrays[0])){
  4708. return array (
  4709. "error",
  4710. "location parameter must be setted"
  4711. );
  4712. }
  4713. if (! array_key_exists("limited_time_offer",$parameterArrays[0])){
  4714. return array (
  4715. "error",
  4716. "limited_time_offer parameter must be setted"
  4717. );
  4718. }
  4719.  
  4720. if (MyMongo_Connection::count(static::$offersCategoriesCollection, array('_id' => (int)$parameterArrays[0]["offer_type"])) == 0)
  4721. {
  4722. return array (
  4723. "error",
  4724. "value of offer_type is not allowed"
  4725. );
  4726. }
  4727. if (! is_numeric($parameterArrays[0]["price"]))
  4728. {
  4729. return array (
  4730. "error",
  4731. "value of price must be numeric"
  4732. );
  4733. }
  4734. $currency = MyMongo_Connection::findOne(static::$offerCurrenciesCollection, array('_id' => (int)$parameterArrays[0]["currency"]));
  4735. if (is_null($currency))
  4736. {
  4737. return array (
  4738. "error",
  4739. "currency value is not allowed"
  4740. );
  4741. }
  4742. $currency = $currency->currency;
  4743.  
  4744. $isLimited = $parameterArrays[0]["limited_time_offer"]; //Yes oppure No
  4745. //se non è né yes né no
  4746. if(strcasecmp($isLimited, "yes") != 0 && strcasecmp($isLimited, "no") != 0)
  4747. {
  4748. return array (
  4749. "error",
  4750. "limited_time_offer value is not allowed"
  4751. );
  4752. }
  4753. $limitationTypeOffer = null;
  4754. //se l'offerta è limitata
  4755. if(strcasecmp($isLimited, "yes") == 0)
  4756. {
  4757. //se non è specificata la tipologia
  4758. if ((!array_key_exists("limitation_type",$parameterArrays[0])))
  4759. { return array
  4760. (
  4761. "error",
  4762. "if limited_time_offer value is Yes, limitation_type must be setted"
  4763. );
  4764. }
  4765. $expirationTypeDoc = MyMongo_Connection::findOne(static::$offerLimitationTypes,array('_id' => (int)$parameterArrays[0]["limitation_type"]));
  4766. $limitationTypeOffer = $expirationTypeDoc->type;
  4767. //se è di tipo expires on e non ha una data di scadenza
  4768. if (strcasecmp($limitationTypeOffer,"Expires on") == 0 && !array_key_exists("expiration_date",$parameterArrays[0]))
  4769. {
  4770. return array
  4771. (
  4772. "error",
  4773. "if limitation_type value is 'expires on', expiration_date must be setted"
  4774. );
  4775. }
  4776. //se è While stocks last
  4777. if(strcasecmp($limitationTypeOffer,"While stocks last") == 0 && array_key_exists('expiration_date', $parameterArrays[0]))
  4778. {
  4779. return array (
  4780. "error",
  4781. "if limitation_type value is 'while stocks last', expiration_date parameter is not allowed"
  4782. );
  4783. }
  4784. //se è di tipo expires on
  4785. if(strcasecmp($limitationTypeOffer,"Expires on") == 0)
  4786. {
  4787. // value string must be in the form of yyyy-mm-dd
  4788. $validator = new Zend_Validate_Date(array('format'=>'yyyy-MM-dd'));
  4789. if (!$validator->isValid( $parameterArrays[0]["expiration_date"] ))
  4790. {
  4791. return array (
  4792. "error",
  4793. "expiration_date must be in format 'yyyy-mm-dd'"
  4794. );
  4795. }
  4796. $date = strtotime($parameterArrays[0]["expiration_date"]);
  4797. if ($date < time()-24*60*60)
  4798. {
  4799. return array (
  4800. "error",
  4801. "expiration_date is in the past"
  4802. );
  4803. }
  4804. }
  4805. }
  4806.  
  4807. //se l'offerta non è limitata
  4808. else
  4809. {
  4810. //se non è limitata non devono essere specificati parametri
  4811. if((array_key_exists("limitation_type",$parameterArrays[0])))
  4812. {
  4813. return array (
  4814. "error",
  4815. "if limited_time_offer value is No, limitation_type parameter is not allowed"
  4816. );
  4817. }
  4818. }
  4819.  
  4820. if (!array_key_exists("photo_id",$parameterArrays[0]) && !array_key_exists("photo_base64",$parameterArrays[0]))
  4821. {
  4822. return array (
  4823. "error",
  4824. "photo_id or the photo_base64 must be provided"
  4825. );
  4826. }
  4827. if (array_key_exists("photo_id",$parameterArrays[0]) && array_key_exists("photo_base64",$parameterArrays[0]))
  4828. { return array (
  4829. "error",
  4830. "photo_id or the photo_base64 must be provided not both"
  4831. );
  4832. }
  4833. $photoURL = "";
  4834. $orientation = "";
  4835.  
  4836. if (array_key_exists("photo_id", $parameterArrays[0]))
  4837. {
  4838. $photoId = $parameterArrays[0]["photo_id"];
  4839. $photo = MyMongo_Connection::findOne(static::$photosColl, array('_id'=>$photoId, 'owner_id' => $userID));
  4840. if (is_null($photo))
  4841. {
  4842. return array (
  4843. "error",
  4844. "photo_id value is not allowed or you aren't owner of photo"
  4845. );
  4846. }
  4847. else
  4848. {
  4849. $photoURL = $photo->fullsize_img['url'];
  4850. $orientation = $photo->img_orientation;
  4851. }
  4852. }
  4853. elseif (array_key_exists("photo_base64",$parameterArrays[0]))
  4854. {
  4855. if ((array_key_exists("photo_base64",$parameterArrays[0])) && (!array_key_exists("crop_coord",$parameterArrays[0])))
  4856. {
  4857. return array (
  4858. "error",
  4859. "crop_coord must be setted"
  4860. );
  4861. }
  4862. else
  4863. {
  4864. $coords = explode(":",$parameterArrays[0]['crop_coord']);
  4865. $orientation = 'horizontal';
  4866. if((int)$coords[2] < (int)$coords[3])
  4867. {
  4868. $orientation = 'vertical';
  4869. }
  4870. $photoURL = Engine_Api::_()->getApi("offerauxiliary","classified")->saveCustomOfferImage($userID, str_replace(" ", "+", $parameterArrays[0]['photo_base64']), $coords, $orientation, false, true);
  4871. }
  4872. }
  4873. $creation_date = new MongoDate();
  4874. $_id = hash("md5",$userID . $creation_date->__toString());
  4875.  
  4876. $cat = MyMongo_Connection::findOne(static::$offersCategoriesCollection, array('_id' => (int)$parameterArrays[0]["offer_type"]));
  4877. $cat = $cat->type;
  4878.  
  4879. //ottengo coordinate dal nome della località
  4880. $coordinates = $this->get_lat_long($parameterArrays[0]['location']);
  4881.  
  4882. $limitationsArray = array('limited_time_offer' => false);
  4883. //se l'offerta ha delle limitazioni
  4884. if(strcasecmp($isLimited, "yes") == 0)
  4885. {
  4886. $limitationsArray = array('limited_time_offer' => true);
  4887. //se ha una limitazione di tipo scadenza (expires on)
  4888. if(strcasecmp($limitationTypeOffer, "Expires on") == 0)
  4889. {
  4890. $expirationTime = $date;
  4891. $limitationsArray['params'] = array(
  4892. 'type' => "Expires on",
  4893. 'expiration_date' => new MongoDate($expirationTime)
  4894. );
  4895. }
  4896. else
  4897. {
  4898. $limitationsArray['params'] = array('type' => "While stocks last");
  4899. }
  4900. }
  4901. // deviceID=9C65F910-6EF8-4340-2121-054520480426-5814&authtoken=E5E6FAB6-ACDF513F-759E8098-3F11CDCA&userID=5c5b7e654a126750dab7a83cf6b3c85a&offerParameters=[{"offer_title":"Offerta test","offer_type":"1","description":"Descrizione offerta","price":"1","currency":"2","location":"Benevento","limited_time_offer":"No","photo_id":"4cd8028b76a490ef839b7a22b18db50b"}]
  4902. //aggiungo l'offerta nel db
  4903. MyMongo_Connection::addDocument(static::$offersColl,
  4904. array
  4905. (
  4906. '_id' => $_id,
  4907. 'title' => $parameterArrays[0]['offer_title'],
  4908. 'description' => $parameterArrays[0]['description'],
  4909. 'owner_id' => $userID,
  4910. 'category' => $cat,
  4911. 'creation_date' => $creation_date,
  4912. 'modified_date' => $creation_date,
  4913. 'views_count' => 0,
  4914. 'comments_count' => 0,
  4915. 'closed' => false,
  4916. 'img_url' => $photoURL,
  4917. 'img_orientation' => $orientation,
  4918. 'acceptors_count' => 0,
  4919. 'cools_count' => 0,
  4920. 'price' => (int)$parameterArrays[0]['price'],
  4921. 'currency' => $currency,
  4922. 'location' => array('address' => $parameterArrays[0]['location'], 'lat' => $coordinates['lat'], 'lon' => $coordinates['lon']),
  4923. 'limitations' => $limitationsArray
  4924. )
  4925. );
  4926. $now = $creation_date;
  4927. /*metto in coda per le notifiche l'offerta appena creata (usercreationdate_offset viene usato come offset, ovvero ogni volta che scatta il task sarò inviata la
  4928. notifica a tutti coloro che si sono iscritti in precedenza a questa data).
  4929. */
  4930. MyMongo_Connection::addDocument(static::$offersTaskColl, array(
  4931. 'offer_id' => $_id,
  4932. 'owner_id' => $userID,
  4933. 'taskcreation_date' => $now,
  4934. 'usercreationdate_offset' => $now,
  4935. 'active' => true,
  4936. 'type' => 'offer',
  4937. 'title' => $parameterArrays[0]['offer_title'],
  4938. 'photo_url' => SM_BUCKET.$photoURL,
  4939. 'photo_orientation' => $orientation,
  4940. 'price' => floatval(str_replace(",", ".", $parameterArrays[0]['price'])),
  4941. 'currency' => $currency,
  4942. 'location' => array('address' => $parameterArrays[0]['location'], 'lat' => $coordinates['lat'], 'lon' => $coordinates['lon']),
  4943. 'limited' => ucfirst($isLimited)
  4944. ));
  4945. $flowItem = array('item_id'=>$_id,'item_type'=>'offer','poster_id'=>$userID,'post_date'=>$now);
  4946. //aggiungo nel flow del poster
  4947. //MyMongo_Connection::addInArrayInDocument(static::$feedsColl, array('_id' => $userID), 'posts', $flowItem);
  4948. MyMongo_Connection::addInFeed($userID, array($flowItem), 128);
  4949.  
  4950. //aggiungo il post nella collection generale dei post
  4951. MyMongo_Connection::addDocument(static::$postsColl, $flowItem);
  4952. return array('Response' => 'Request OK', 'offer' =>
  4953. array(
  4954. 'offer_id' => $_id,
  4955. 'photo_url' => SM_BUCKET.$photoURL,
  4956. 'photo_orientation' => $orientation,
  4957. 'creation_date' => $now->sec,
  4958. 'limited' => ucfirst($isLimited),
  4959. 'currency' => $currency,
  4960. 'limit_type' => $limitationsArray
  4961. ));
  4962. }
  4963.  
  4964. public function postEvent($userID, $eventParameters) {
  4965. $eventParams = array();
  4966. $parameterArrays = Zend_Json_Decoder::decode($eventParameters, true); // decode JSON to associative array
  4967.  
  4968. $eventParams['owner_id'] = $userID;
  4969. if (! array_key_exists("title", $parameterArrays[0])) {
  4970. return array(
  4971. "error",
  4972. "title parameter must be setted"
  4973. );
  4974. } else {
  4975. $eventParams["title"] = $parameterArrays[0]["title"];
  4976. }
  4977. if (! array_key_exists("description",$parameterArrays[0])) {
  4978. return array(
  4979. "error",
  4980. "description parameter must be setted"
  4981. );
  4982. } else {
  4983. $eventParams["description"] = $parameterArrays[0]["description"];
  4984. }
  4985. if (! array_key_exists("starttime",$parameterArrays[0])) {
  4986. return array (
  4987. "error",
  4988. "starttime parameter must be setted"
  4989. );
  4990. }
  4991. if (! array_key_exists("endtime",$parameterArrays[0])) {
  4992. return array (
  4993. "error",
  4994. "endtime parameter must be setted"
  4995. );
  4996. }
  4997. if (! array_key_exists("location",$parameterArrays[0])) {
  4998. return array (
  4999. "error",
  5000. "location parameter must be setted"
  5001. );
  5002. }
  5003. else
  5004. {
  5005. if(Utilities_Static::getTextUtility()->isThereEmoji($parameterArrays[0]["location"]))
  5006. {
  5007. return array("error","location is not valid");
  5008. }
  5009. else
  5010. {
  5011. $eventParams["location"] = $parameterArrays[0]["location"];
  5012. }
  5013. }
  5014. if (! array_key_exists("category_id",$parameterArrays[0])) {
  5015. return array (
  5016. "error",
  5017. "category_id parameter must be setted"
  5018. );
  5019. }
  5020. $category = MyMongo_Connection::findOne("event_categories", array("category_id" => (int)$parameterArrays[0]["category_id"]));
  5021. if ($category == null) {
  5022. return array (
  5023. "error",
  5024. "category_id value not allowed"
  5025. );
  5026. } else {
  5027. $eventParams['category'] = $category->title;
  5028. }
  5029. $startstring = str_replace(" "," +",$parameterArrays[0]["starttime"]);
  5030. $validator = new Zend_Validate_Date(array('format'=>'yyyy-MM-dd H:i:s '));
  5031. if ((!preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]) ([+-](2[0-3]|[0-1][0-9]):([0-5][0-9]))$/", $startstring)) || (!$validator->isValid($startstring))) {
  5032. return array (
  5033. "error",
  5034. "starttime must be in format 'yyyy-mm-dd H:i:s [+|-]xx:zz'"
  5035. );
  5036. }
  5037. $start = new DateTime($startstring);
  5038. $oldTz = date_default_timezone_get();
  5039. date_default_timezone_set($start->getTimezone()->getName());
  5040. $starttime = strtotime($startstring);
  5041.  
  5042. date_default_timezone_set($oldTz);
  5043. $endstring = str_replace(" "," +",$parameterArrays[0]["endtime"]);
  5044. $validator = new Zend_Validate_Date(array('format'=>'yyyy-MM-dd H:i:s '));
  5045. if ((!preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]) ([+-](2[0-3]|[0-1][0-9]):([0-5][0-9]))$/", $endstring)) || (!$validator->isValid($endstring))) {
  5046. return array (
  5047. "error",
  5048. "endtime must be in format 'yyyy-mm-dd H:i:s [+|-]xx:zz'"
  5049. );
  5050. }
  5051. $end = new DateTime($endstring);
  5052. date_default_timezone_set($end->getTimezone()->getName());
  5053. $endtime = strtotime($endstring);
  5054. date_default_timezone_set($oldTz);
  5055. if ($endtime < $starttime) {
  5056. return array (
  5057. "error",
  5058. "endtime is before of starttime"
  5059. );
  5060. }
  5061. if ($starttime < time()) {
  5062. return array (
  5063. "error",
  5064. "starttime is in the past"
  5065. );
  5066. }
  5067. if ($endtime < time()) {
  5068. return array (
  5069. "error",
  5070. "endtime is in the past"
  5071. );
  5072. }
  5073.  
  5074. // ----------------------------------------------
  5075. // Handling event's photo
  5076. if (!array_key_exists("photo_id", $parameterArrays[0]) && !array_key_exists("photo_base64", $parameterArrays[0])) {
  5077. return array (
  5078. "error",
  5079. "photo_id or the photo_base64 must be provided"
  5080. );
  5081. }
  5082. if (array_key_exists("photo_id", $parameterArrays[0]) && array_key_exists("photo_base64", $parameterArrays[0])) {
  5083. return array (
  5084. "error",
  5085. "photo_id or the photo_base64 must be provided not both"
  5086. );
  5087. }
  5088. if (array_key_exists("photo_id", $parameterArrays[0])) {
  5089. $photo = MyMongo_Connection::findOne("photos", array("_id" => $parameterArrays[0]["photo_id"], "owner_id" => $userID));
  5090. if ($photo == null) {
  5091. return array (
  5092. "error",
  5093. "photo_id value is not allowed or you aren't owner of photo"
  5094. );
  5095. }
  5096. $eventParams['localPhotoUpload'] = false;
  5097. $eventParams['base64OrURL'] = $photo->fullsize_img['url'];
  5098. $eventParams['photoOrientation'] = $photo->img_orientation;
  5099. } elseif(array_key_exists("photo_base64", $parameterArrays[0])) {
  5100. if ((array_key_exists("photo_base64", $parameterArrays[0])) && (!array_key_exists("crop_coord", $parameterArrays[0]))) {
  5101. return array (
  5102. "error",
  5103. "crop_coord must be setted"
  5104. );
  5105. }
  5106. $coord = explode ( ":", $parameterArrays [0] ["crop_coord"] );
  5107.  
  5108. if (intval ( $coord [2] ) > intval ( $coord [3] )) {
  5109. $eventParams['photoOrientation'] = "horizontal";
  5110. } else {
  5111. $eventParams['photoOrientation'] = "vertical";
  5112. }
  5113. $coord [2] = intval ( $coord [0] ) + intval ( $coord [2] );
  5114. $coord [3] = intval ( $coord [1] ) + intval ( $coord [3] );
  5115. if (strcasecmp ( $parameterArrays [0] ["photo_base64"], "" ) != 0) {
  5116. $eventParams['cropCoordinates'] = implode(";", $coord);
  5117. $eventParams['localPhotoUpload'] = true;
  5118. $eventParams['base64OrURL'] = str_replace(" ", "+", $parameterArrays[0]["photo_base64"]);
  5119. } else {
  5120. return array (
  5121. "error",
  5122. "photo_base64 value can not be empty"
  5123. );
  5124. }
  5125. }
  5126. //----------------------------------------------
  5127. $user = MyMongo_Connection::findOne("users", array("_id" => $userID));
  5128. $start_date = new Zend_Date(date("m/d/Y H:i", $starttime), Zend_Date::DATETIME_FULL, $user->locale);
  5129. $end_date = new Zend_Date(date("m/d/Y H:i", $endtime), Zend_Date::DATETIME_FULL, $user->locale);
  5130.  
  5131. // Create event
  5132. $eventAuxiliary = Engine_Api::_()->getApi('eventauxiliary', 'event');
  5133. $response = $eventAuxiliary->createEvent($eventParams, $start_date, $end_date, (array)$user, true);
  5134. return array('Response' => 'Request OK', 'event' =>
  5135. array
  5136. (
  5137. 'event_id' => $response['messages']['eventID'],
  5138. 'photo_url' => $response['messages']['photo_url'],
  5139. 'photo_orientation' => $response['messages']['photo_orientation'],
  5140. 'starttime' => $response['messages']['starttime'],
  5141. 'endtime' => $response['messages']['endtime']
  5142. )
  5143. );
  5144. }
  5145.  
  5146. /**
  5147. * In base alla versione passata in input, questo metodo restituisce il firmware aggiornato o un
  5148. * messaggio che indica che la versione passata è già aggiornata (o che non ci sono aggiornamenti).
  5149. * @param $version array con due campi status (0 no aggiornamenti, 1 aggiornamenti) e content (messaggio se status è 0
  5150. * oppure firmware in base64 se status vale 1)
  5151. * @return
  5152. */
  5153. public function getFirmwareUpdates($version) {
  5154. $firmware = MyMongo_Connection::findOne("core_printingfirmware", array("_id" => array('$exists' => true)));
  5155. $response = array(
  5156. "status" => 0,
  5157. "content" => "No updates available",
  5158. );
  5159. if($firmware != null) {
  5160. //if the user has an older version
  5161. if(intval($firmware->version) > intval($version)) {
  5162. $response = array(
  5163. "status" => 1,
  5164. "content" => $firmware->content,
  5165. "md5checksum" => $firmware->md5checksum
  5166. );
  5167. }
  5168. }
  5169. return $response;
  5170. }
  5171. /**
  5172. * Verifica l'esistenza di una certa risorsa di un certo tipo
  5173. * @param $objectID id della risorsa
  5174. * @param $objectType tipologia della risorsa
  5175. */
  5176. public function checkObjectExistence ($objectID, $objectType)
  5177. {
  5178. $collection = "";
  5179. //album_photo, classified, event ----> valori assumibili da objectType
  5180. if(strcasecmp($objectType, "album_photo") == 0)
  5181. {
  5182. $collection = 'photos';
  5183. }
  5184. else if(strcasecmp($objectType, "classified") == 0)
  5185. {
  5186. $collection = 'offers';
  5187. }
  5188. else if(strcasecmp($objectType, "event") == 0)
  5189. {
  5190. $collection = 'events';
  5191. }
  5192. else
  5193. {
  5194. return false;
  5195. }
  5196. if(strcasecmp($objectType, "album_photo") == 0) {
  5197. return MyMongo_Connection::count($collection, array('_id' => $objectID, "deleted" => false)) > 0;
  5198. } else {
  5199. return MyMongo_Connection::count($collection, array('_id' => $objectID)) > 0;
  5200. }
  5201. }
  5202.  
  5203. }
Add Comment
Please, Sign In to add comment